4c2b5a817111ffbbc4d7aab111937e27c53a31a0
[pandora-kernel.git] / drivers / scsi / aic7xxx / aic79xx_core.c
1 /*
2  * Core routines and tables shareable across OS platforms.
3  *
4  * Copyright (c) 1994-2002 Justin T. Gibbs.
5  * Copyright (c) 2000-2003 Adaptec Inc.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions, and the following disclaimer,
13  *    without modification.
14  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
15  *    substantially similar to the "NO WARRANTY" disclaimer below
16  *    ("Disclaimer") and any redistribution must be conditioned upon
17  *    including a substantially similar Disclaimer requirement for further
18  *    binary redistribution.
19  * 3. Neither the names of the above-listed copyright holders nor the names
20  *    of any contributors may be used to endorse or promote products derived
21  *    from this software without specific prior written permission.
22  *
23  * Alternatively, this software may be distributed under the terms of the
24  * GNU General Public License ("GPL") version 2 as published by the Free
25  * Software Foundation.
26  *
27  * NO WARRANTY
28  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
31  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
36  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
37  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
38  * POSSIBILITY OF SUCH DAMAGES.
39  *
40  * $Id: //depot/aic7xxx/aic7xxx/aic79xx.c#250 $
41  */
42
43 #ifdef __linux__
44 #include "aic79xx_osm.h"
45 #include "aic79xx_inline.h"
46 #include "aicasm/aicasm_insformat.h"
47 #else
48 #include <dev/aic7xxx/aic79xx_osm.h>
49 #include <dev/aic7xxx/aic79xx_inline.h>
50 #include <dev/aic7xxx/aicasm/aicasm_insformat.h>
51 #endif
52
53
54 /***************************** Lookup Tables **********************************/
55 static char *ahd_chip_names[] =
56 {
57         "NONE",
58         "aic7901",
59         "aic7902",
60         "aic7901A"
61 };
62 static const u_int num_chip_names = ARRAY_SIZE(ahd_chip_names);
63
64 /*
65  * Hardware error codes.
66  */
67 struct ahd_hard_error_entry {
68         uint8_t errno;
69         char *errmesg;
70 };
71
72 static struct ahd_hard_error_entry ahd_hard_errors[] = {
73         { DSCTMOUT,     "Discard Timer has timed out" },
74         { ILLOPCODE,    "Illegal Opcode in sequencer program" },
75         { SQPARERR,     "Sequencer Parity Error" },
76         { DPARERR,      "Data-path Parity Error" },
77         { MPARERR,      "Scratch or SCB Memory Parity Error" },
78         { CIOPARERR,    "CIOBUS Parity Error" },
79 };
80 static const u_int num_errors = ARRAY_SIZE(ahd_hard_errors);
81
82 static struct ahd_phase_table_entry ahd_phase_table[] =
83 {
84         { P_DATAOUT,    MSG_NOOP,               "in Data-out phase"     },
85         { P_DATAIN,     MSG_INITIATOR_DET_ERR,  "in Data-in phase"      },
86         { P_DATAOUT_DT, MSG_NOOP,               "in DT Data-out phase"  },
87         { P_DATAIN_DT,  MSG_INITIATOR_DET_ERR,  "in DT Data-in phase"   },
88         { P_COMMAND,    MSG_NOOP,               "in Command phase"      },
89         { P_MESGOUT,    MSG_NOOP,               "in Message-out phase"  },
90         { P_STATUS,     MSG_INITIATOR_DET_ERR,  "in Status phase"       },
91         { P_MESGIN,     MSG_PARITY_ERROR,       "in Message-in phase"   },
92         { P_BUSFREE,    MSG_NOOP,               "while idle"            },
93         { 0,            MSG_NOOP,               "in unknown phase"      }
94 };
95
96 /*
97  * In most cases we only wish to itterate over real phases, so
98  * exclude the last element from the count.
99  */
100 static const u_int num_phases = ARRAY_SIZE(ahd_phase_table) - 1;
101
102 /* Our Sequencer Program */
103 #include "aic79xx_seq.h"
104
105 /**************************** Function Declarations ***************************/
106 static void             ahd_handle_transmission_error(struct ahd_softc *ahd);
107 static void             ahd_handle_lqiphase_error(struct ahd_softc *ahd,
108                                                   u_int lqistat1);
109 static int              ahd_handle_pkt_busfree(struct ahd_softc *ahd,
110                                                u_int busfreetime);
111 static int              ahd_handle_nonpkt_busfree(struct ahd_softc *ahd);
112 static void             ahd_handle_proto_violation(struct ahd_softc *ahd);
113 static void             ahd_force_renegotiation(struct ahd_softc *ahd,
114                                                 struct ahd_devinfo *devinfo);
115
116 static struct ahd_tmode_tstate*
117                         ahd_alloc_tstate(struct ahd_softc *ahd,
118                                          u_int scsi_id, char channel);
119 #ifdef AHD_TARGET_MODE
120 static void             ahd_free_tstate(struct ahd_softc *ahd,
121                                         u_int scsi_id, char channel, int force);
122 #endif
123 static void             ahd_devlimited_syncrate(struct ahd_softc *ahd,
124                                                 struct ahd_initiator_tinfo *,
125                                                 u_int *period,
126                                                 u_int *ppr_options,
127                                                 role_t role);
128 static void             ahd_update_neg_table(struct ahd_softc *ahd,
129                                              struct ahd_devinfo *devinfo,
130                                              struct ahd_transinfo *tinfo);
131 static void             ahd_update_pending_scbs(struct ahd_softc *ahd);
132 static void             ahd_fetch_devinfo(struct ahd_softc *ahd,
133                                           struct ahd_devinfo *devinfo);
134 static void             ahd_scb_devinfo(struct ahd_softc *ahd,
135                                         struct ahd_devinfo *devinfo,
136                                         struct scb *scb);
137 static void             ahd_setup_initiator_msgout(struct ahd_softc *ahd,
138                                                    struct ahd_devinfo *devinfo,
139                                                    struct scb *scb);
140 static void             ahd_build_transfer_msg(struct ahd_softc *ahd,
141                                                struct ahd_devinfo *devinfo);
142 static void             ahd_construct_sdtr(struct ahd_softc *ahd,
143                                            struct ahd_devinfo *devinfo,
144                                            u_int period, u_int offset);
145 static void             ahd_construct_wdtr(struct ahd_softc *ahd,
146                                            struct ahd_devinfo *devinfo,
147                                            u_int bus_width);
148 static void             ahd_construct_ppr(struct ahd_softc *ahd,
149                                           struct ahd_devinfo *devinfo,
150                                           u_int period, u_int offset,
151                                           u_int bus_width, u_int ppr_options);
152 static void             ahd_clear_msg_state(struct ahd_softc *ahd);
153 static void             ahd_handle_message_phase(struct ahd_softc *ahd);
154 typedef enum {
155         AHDMSG_1B,
156         AHDMSG_2B,
157         AHDMSG_EXT
158 } ahd_msgtype;
159 static int              ahd_sent_msg(struct ahd_softc *ahd, ahd_msgtype type,
160                                      u_int msgval, int full);
161 static int              ahd_parse_msg(struct ahd_softc *ahd,
162                                       struct ahd_devinfo *devinfo);
163 static int              ahd_handle_msg_reject(struct ahd_softc *ahd,
164                                               struct ahd_devinfo *devinfo);
165 static void             ahd_handle_ign_wide_residue(struct ahd_softc *ahd,
166                                                 struct ahd_devinfo *devinfo);
167 static void             ahd_reinitialize_dataptrs(struct ahd_softc *ahd);
168 static void             ahd_handle_devreset(struct ahd_softc *ahd,
169                                             struct ahd_devinfo *devinfo,
170                                             u_int lun, cam_status status,
171                                             char *message, int verbose_level);
172 #ifdef AHD_TARGET_MODE
173 static void             ahd_setup_target_msgin(struct ahd_softc *ahd,
174                                                struct ahd_devinfo *devinfo,
175                                                struct scb *scb);
176 #endif
177
178 static u_int            ahd_sglist_size(struct ahd_softc *ahd);
179 static u_int            ahd_sglist_allocsize(struct ahd_softc *ahd);
180 static bus_dmamap_callback_t
181                         ahd_dmamap_cb; 
182 static void             ahd_initialize_hscbs(struct ahd_softc *ahd);
183 static int              ahd_init_scbdata(struct ahd_softc *ahd);
184 static void             ahd_fini_scbdata(struct ahd_softc *ahd);
185 static void             ahd_setup_iocell_workaround(struct ahd_softc *ahd);
186 static void             ahd_iocell_first_selection(struct ahd_softc *ahd);
187 static void             ahd_add_col_list(struct ahd_softc *ahd,
188                                          struct scb *scb, u_int col_idx);
189 static void             ahd_rem_col_list(struct ahd_softc *ahd,
190                                          struct scb *scb);
191 static void             ahd_chip_init(struct ahd_softc *ahd);
192 static void             ahd_qinfifo_requeue(struct ahd_softc *ahd,
193                                             struct scb *prev_scb,
194                                             struct scb *scb);
195 static int              ahd_qinfifo_count(struct ahd_softc *ahd);
196 static int              ahd_search_scb_list(struct ahd_softc *ahd, int target,
197                                             char channel, int lun, u_int tag,
198                                             role_t role, uint32_t status,
199                                             ahd_search_action action,
200                                             u_int *list_head, u_int *list_tail,
201                                             u_int tid);
202 static void             ahd_stitch_tid_list(struct ahd_softc *ahd,
203                                             u_int tid_prev, u_int tid_cur,
204                                             u_int tid_next);
205 static void             ahd_add_scb_to_free_list(struct ahd_softc *ahd,
206                                                  u_int scbid);
207 static u_int            ahd_rem_wscb(struct ahd_softc *ahd, u_int scbid,
208                                      u_int prev, u_int next, u_int tid);
209 static void             ahd_reset_current_bus(struct ahd_softc *ahd);
210 static ahd_callback_t   ahd_stat_timer;
211 #ifdef AHD_DUMP_SEQ
212 static void             ahd_dumpseq(struct ahd_softc *ahd);
213 #endif
214 static void             ahd_loadseq(struct ahd_softc *ahd);
215 static int              ahd_check_patch(struct ahd_softc *ahd,
216                                         struct patch **start_patch,
217                                         u_int start_instr, u_int *skip_addr);
218 static u_int            ahd_resolve_seqaddr(struct ahd_softc *ahd,
219                                             u_int address);
220 static void             ahd_download_instr(struct ahd_softc *ahd,
221                                            u_int instrptr, uint8_t *dconsts);
222 static int              ahd_probe_stack_size(struct ahd_softc *ahd);
223 static int              ahd_scb_active_in_fifo(struct ahd_softc *ahd,
224                                                struct scb *scb);
225 static void             ahd_run_data_fifo(struct ahd_softc *ahd,
226                                           struct scb *scb);
227
228 #ifdef AHD_TARGET_MODE
229 static void             ahd_queue_lstate_event(struct ahd_softc *ahd,
230                                                struct ahd_tmode_lstate *lstate,
231                                                u_int initiator_id,
232                                                u_int event_type,
233                                                u_int event_arg);
234 static void             ahd_update_scsiid(struct ahd_softc *ahd,
235                                           u_int targid_mask);
236 static int              ahd_handle_target_cmd(struct ahd_softc *ahd,
237                                               struct target_cmd *cmd);
238 #endif
239
240 static int              ahd_abort_scbs(struct ahd_softc *ahd, int target,
241                                        char channel, int lun, u_int tag,
242                                        role_t role, uint32_t status);
243 static void             ahd_alloc_scbs(struct ahd_softc *ahd);
244 static void             ahd_busy_tcl(struct ahd_softc *ahd, u_int tcl,
245                                      u_int scbid);
246 static void             ahd_calc_residual(struct ahd_softc *ahd,
247                                           struct scb *scb);
248 static void             ahd_clear_critical_section(struct ahd_softc *ahd);
249 static void             ahd_clear_intstat(struct ahd_softc *ahd);
250 static void             ahd_enable_coalescing(struct ahd_softc *ahd,
251                                               int enable);
252 static u_int            ahd_find_busy_tcl(struct ahd_softc *ahd, u_int tcl);
253 static void             ahd_freeze_devq(struct ahd_softc *ahd,
254                                         struct scb *scb);
255 static void             ahd_handle_scb_status(struct ahd_softc *ahd,
256                                               struct scb *scb);
257 static struct ahd_phase_table_entry* ahd_lookup_phase_entry(int phase);
258 static void             ahd_shutdown(void *arg);
259 static void             ahd_update_coalescing_values(struct ahd_softc *ahd,
260                                                      u_int timer,
261                                                      u_int maxcmds,
262                                                      u_int mincmds);
263 static int              ahd_verify_vpd_cksum(struct vpd_config *vpd);
264 static int              ahd_wait_seeprom(struct ahd_softc *ahd);
265
266 /******************************** Private Inlines *****************************/
267
268 static __inline void
269 ahd_assert_atn(struct ahd_softc *ahd)
270 {
271         ahd_outb(ahd, SCSISIGO, ATNO);
272 }
273
274 /*
275  * Determine if the current connection has a packetized
276  * agreement.  This does not necessarily mean that we
277  * are currently in a packetized transfer.  We could
278  * just as easily be sending or receiving a message.
279  */
280 static __inline int
281 ahd_currently_packetized(struct ahd_softc *ahd)
282 {
283         ahd_mode_state   saved_modes;
284         int              packetized;
285
286         saved_modes = ahd_save_modes(ahd);
287         if ((ahd->bugs & AHD_PKTIZED_STATUS_BUG) != 0) {
288                 /*
289                  * The packetized bit refers to the last
290                  * connection, not the current one.  Check
291                  * for non-zero LQISTATE instead.
292                  */
293                 ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
294                 packetized = ahd_inb(ahd, LQISTATE) != 0;
295         } else {
296                 ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
297                 packetized = ahd_inb(ahd, LQISTAT2) & PACKETIZED;
298         }
299         ahd_restore_modes(ahd, saved_modes);
300         return (packetized);
301 }
302
303 static __inline int
304 ahd_set_active_fifo(struct ahd_softc *ahd)
305 {
306         u_int active_fifo;
307
308         AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
309         active_fifo = ahd_inb(ahd, DFFSTAT) & CURRFIFO;
310         switch (active_fifo) {
311         case 0:
312         case 1:
313                 ahd_set_modes(ahd, active_fifo, active_fifo);
314                 return (1);
315         default:
316                 return (0);
317         }
318 }
319
320 static __inline void
321 ahd_unbusy_tcl(struct ahd_softc *ahd, u_int tcl)
322 {
323         ahd_busy_tcl(ahd, tcl, SCB_LIST_NULL);
324 }
325
326 /*
327  * Determine whether the sequencer reported a residual
328  * for this SCB/transaction.
329  */
330 static __inline void
331 ahd_update_residual(struct ahd_softc *ahd, struct scb *scb)
332 {
333         uint32_t sgptr;
334
335         sgptr = ahd_le32toh(scb->hscb->sgptr);
336         if ((sgptr & SG_STATUS_VALID) != 0)
337                 ahd_calc_residual(ahd, scb);
338 }
339
340 static __inline void
341 ahd_complete_scb(struct ahd_softc *ahd, struct scb *scb)
342 {
343         uint32_t sgptr;
344
345         sgptr = ahd_le32toh(scb->hscb->sgptr);
346         if ((sgptr & SG_STATUS_VALID) != 0)
347                 ahd_handle_scb_status(ahd, scb);
348         else
349                 ahd_done(ahd, scb);
350 }
351
352
353 /************************* Sequencer Execution Control ************************/
354 /*
355  * Restart the sequencer program from address zero
356  */
357 static void
358 ahd_restart(struct ahd_softc *ahd)
359 {
360
361         ahd_pause(ahd);
362
363         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
364
365         /* No more pending messages */
366         ahd_clear_msg_state(ahd);
367         ahd_outb(ahd, SCSISIGO, 0);             /* De-assert BSY */
368         ahd_outb(ahd, MSG_OUT, MSG_NOOP);       /* No message to send */
369         ahd_outb(ahd, SXFRCTL1, ahd_inb(ahd, SXFRCTL1) & ~BITBUCKET);
370         ahd_outb(ahd, SEQINTCTL, 0);
371         ahd_outb(ahd, LASTPHASE, P_BUSFREE);
372         ahd_outb(ahd, SEQ_FLAGS, 0);
373         ahd_outb(ahd, SAVED_SCSIID, 0xFF);
374         ahd_outb(ahd, SAVED_LUN, 0xFF);
375
376         /*
377          * Ensure that the sequencer's idea of TQINPOS
378          * matches our own.  The sequencer increments TQINPOS
379          * only after it sees a DMA complete and a reset could
380          * occur before the increment leaving the kernel to believe
381          * the command arrived but the sequencer to not.
382          */
383         ahd_outb(ahd, TQINPOS, ahd->tqinfifonext);
384
385         /* Always allow reselection */
386         ahd_outb(ahd, SCSISEQ1,
387                  ahd_inb(ahd, SCSISEQ_TEMPLATE) & (ENSELI|ENRSELI|ENAUTOATNP));
388         ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
389
390         /*
391          * Clear any pending sequencer interrupt.  It is no
392          * longer relevant since we're resetting the Program
393          * Counter.
394          */
395         ahd_outb(ahd, CLRINT, CLRSEQINT);
396
397         ahd_outb(ahd, SEQCTL0, FASTMODE|SEQRESET);
398         ahd_unpause(ahd);
399 }
400
401 static void
402 ahd_clear_fifo(struct ahd_softc *ahd, u_int fifo)
403 {
404         ahd_mode_state   saved_modes;
405
406 #ifdef AHD_DEBUG
407         if ((ahd_debug & AHD_SHOW_FIFOS) != 0)
408                 printf("%s: Clearing FIFO %d\n", ahd_name(ahd), fifo);
409 #endif
410         saved_modes = ahd_save_modes(ahd);
411         ahd_set_modes(ahd, fifo, fifo);
412         ahd_outb(ahd, DFFSXFRCTL, RSTCHN|CLRSHCNT);
413         if ((ahd_inb(ahd, SG_STATE) & FETCH_INPROG) != 0)
414                 ahd_outb(ahd, CCSGCTL, CCSGRESET);
415         ahd_outb(ahd, LONGJMP_ADDR + 1, INVALID_ADDR);
416         ahd_outb(ahd, SG_STATE, 0);
417         ahd_restore_modes(ahd, saved_modes);
418 }
419
420 /************************* Input/Output Queues ********************************/
421 /*
422  * Flush and completed commands that are sitting in the command
423  * complete queues down on the chip but have yet to be dma'ed back up.
424  */
425 static void
426 ahd_flush_qoutfifo(struct ahd_softc *ahd)
427 {
428         struct          scb *scb;
429         ahd_mode_state  saved_modes;
430         u_int           saved_scbptr;
431         u_int           ccscbctl;
432         u_int           scbid;
433         u_int           next_scbid;
434
435         saved_modes = ahd_save_modes(ahd);
436
437         /*
438          * Flush the good status FIFO for completed packetized commands.
439          */
440         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
441         saved_scbptr = ahd_get_scbptr(ahd);
442         while ((ahd_inb(ahd, LQISTAT2) & LQIGSAVAIL) != 0) {
443                 u_int fifo_mode;
444                 u_int i;
445                 
446                 scbid = ahd_inw(ahd, GSFIFO);
447                 scb = ahd_lookup_scb(ahd, scbid);
448                 if (scb == NULL) {
449                         printf("%s: Warning - GSFIFO SCB %d invalid\n",
450                                ahd_name(ahd), scbid);
451                         continue;
452                 }
453                 /*
454                  * Determine if this transaction is still active in
455                  * any FIFO.  If it is, we must flush that FIFO to
456                  * the host before completing the  command.
457                  */
458                 fifo_mode = 0;
459 rescan_fifos:
460                 for (i = 0; i < 2; i++) {
461                         /* Toggle to the other mode. */
462                         fifo_mode ^= 1;
463                         ahd_set_modes(ahd, fifo_mode, fifo_mode);
464
465                         if (ahd_scb_active_in_fifo(ahd, scb) == 0)
466                                 continue;
467
468                         ahd_run_data_fifo(ahd, scb);
469
470                         /*
471                          * Running this FIFO may cause a CFG4DATA for
472                          * this same transaction to assert in the other
473                          * FIFO or a new snapshot SAVEPTRS interrupt
474                          * in this FIFO.  Even running a FIFO may not
475                          * clear the transaction if we are still waiting
476                          * for data to drain to the host. We must loop
477                          * until the transaction is not active in either
478                          * FIFO just to be sure.  Reset our loop counter
479                          * so we will visit both FIFOs again before
480                          * declaring this transaction finished.  We
481                          * also delay a bit so that status has a chance
482                          * to change before we look at this FIFO again.
483                          */
484                         ahd_delay(200);
485                         goto rescan_fifos;
486                 }
487                 ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
488                 ahd_set_scbptr(ahd, scbid);
489                 if ((ahd_inb_scbram(ahd, SCB_SGPTR) & SG_LIST_NULL) == 0
490                  && ((ahd_inb_scbram(ahd, SCB_SGPTR) & SG_FULL_RESID) != 0
491                   || (ahd_inb_scbram(ahd, SCB_RESIDUAL_SGPTR)
492                       & SG_LIST_NULL) != 0)) {
493                         u_int comp_head;
494
495                         /*
496                          * The transfer completed with a residual.
497                          * Place this SCB on the complete DMA list
498                          * so that we update our in-core copy of the
499                          * SCB before completing the command.
500                          */
501                         ahd_outb(ahd, SCB_SCSI_STATUS, 0);
502                         ahd_outb(ahd, SCB_SGPTR,
503                                  ahd_inb_scbram(ahd, SCB_SGPTR)
504                                  | SG_STATUS_VALID);
505                         ahd_outw(ahd, SCB_TAG, scbid);
506                         ahd_outw(ahd, SCB_NEXT_COMPLETE, SCB_LIST_NULL);
507                         comp_head = ahd_inw(ahd, COMPLETE_DMA_SCB_HEAD);
508                         if (SCBID_IS_NULL(comp_head)) {
509                                 ahd_outw(ahd, COMPLETE_DMA_SCB_HEAD, scbid);
510                                 ahd_outw(ahd, COMPLETE_DMA_SCB_TAIL, scbid);
511                         } else {
512                                 u_int tail;
513
514                                 tail = ahd_inw(ahd, COMPLETE_DMA_SCB_TAIL);
515                                 ahd_set_scbptr(ahd, tail);
516                                 ahd_outw(ahd, SCB_NEXT_COMPLETE, scbid);
517                                 ahd_outw(ahd, COMPLETE_DMA_SCB_TAIL, scbid);
518                                 ahd_set_scbptr(ahd, scbid);
519                         }
520                 } else
521                         ahd_complete_scb(ahd, scb);
522         }
523         ahd_set_scbptr(ahd, saved_scbptr);
524
525         /*
526          * Setup for command channel portion of flush.
527          */
528         ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
529
530         /*
531          * Wait for any inprogress DMA to complete and clear DMA state
532          * if this if for an SCB in the qinfifo.
533          */
534         while (((ccscbctl = ahd_inb(ahd, CCSCBCTL)) & (CCARREN|CCSCBEN)) != 0) {
535
536                 if ((ccscbctl & (CCSCBDIR|CCARREN)) == (CCSCBDIR|CCARREN)) {
537                         if ((ccscbctl & ARRDONE) != 0)
538                                 break;
539                 } else if ((ccscbctl & CCSCBDONE) != 0)
540                         break;
541                 ahd_delay(200);
542         }
543         /*
544          * We leave the sequencer to cleanup in the case of DMA's to
545          * update the qoutfifo.  In all other cases (DMA's to the
546          * chip or a push of an SCB from the COMPLETE_DMA_SCB list),
547          * we disable the DMA engine so that the sequencer will not
548          * attempt to handle the DMA completion.
549          */
550         if ((ccscbctl & CCSCBDIR) != 0 || (ccscbctl & ARRDONE) != 0)
551                 ahd_outb(ahd, CCSCBCTL, ccscbctl & ~(CCARREN|CCSCBEN));
552
553         /*
554          * Complete any SCBs that just finished
555          * being DMA'ed into the qoutfifo.
556          */
557         ahd_run_qoutfifo(ahd);
558
559         saved_scbptr = ahd_get_scbptr(ahd);
560         /*
561          * Manually update/complete any completed SCBs that are waiting to be
562          * DMA'ed back up to the host.
563          */
564         scbid = ahd_inw(ahd, COMPLETE_DMA_SCB_HEAD);
565         while (!SCBID_IS_NULL(scbid)) {
566                 uint8_t *hscb_ptr;
567                 u_int    i;
568                 
569                 ahd_set_scbptr(ahd, scbid);
570                 next_scbid = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
571                 scb = ahd_lookup_scb(ahd, scbid);
572                 if (scb == NULL) {
573                         printf("%s: Warning - DMA-up and complete "
574                                "SCB %d invalid\n", ahd_name(ahd), scbid);
575                         continue;
576                 }
577                 hscb_ptr = (uint8_t *)scb->hscb;
578                 for (i = 0; i < sizeof(struct hardware_scb); i++)
579                         *hscb_ptr++ = ahd_inb_scbram(ahd, SCB_BASE + i);
580
581                 ahd_complete_scb(ahd, scb);
582                 scbid = next_scbid;
583         }
584         ahd_outw(ahd, COMPLETE_DMA_SCB_HEAD, SCB_LIST_NULL);
585         ahd_outw(ahd, COMPLETE_DMA_SCB_TAIL, SCB_LIST_NULL);
586
587         scbid = ahd_inw(ahd, COMPLETE_ON_QFREEZE_HEAD);
588         while (!SCBID_IS_NULL(scbid)) {
589
590                 ahd_set_scbptr(ahd, scbid);
591                 next_scbid = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
592                 scb = ahd_lookup_scb(ahd, scbid);
593                 if (scb == NULL) {
594                         printf("%s: Warning - Complete Qfrz SCB %d invalid\n",
595                                ahd_name(ahd), scbid);
596                         continue;
597                 }
598
599                 ahd_complete_scb(ahd, scb);
600                 scbid = next_scbid;
601         }
602         ahd_outw(ahd, COMPLETE_ON_QFREEZE_HEAD, SCB_LIST_NULL);
603
604         scbid = ahd_inw(ahd, COMPLETE_SCB_HEAD);
605         while (!SCBID_IS_NULL(scbid)) {
606
607                 ahd_set_scbptr(ahd, scbid);
608                 next_scbid = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
609                 scb = ahd_lookup_scb(ahd, scbid);
610                 if (scb == NULL) {
611                         printf("%s: Warning - Complete SCB %d invalid\n",
612                                ahd_name(ahd), scbid);
613                         continue;
614                 }
615
616                 ahd_complete_scb(ahd, scb);
617                 scbid = next_scbid;
618         }
619         ahd_outw(ahd, COMPLETE_SCB_HEAD, SCB_LIST_NULL);
620
621         /*
622          * Restore state.
623          */
624         ahd_set_scbptr(ahd, saved_scbptr);
625         ahd_restore_modes(ahd, saved_modes);
626         ahd->flags |= AHD_UPDATE_PEND_CMDS;
627 }
628
629 /*
630  * Determine if an SCB for a packetized transaction
631  * is active in a FIFO.
632  */
633 static int
634 ahd_scb_active_in_fifo(struct ahd_softc *ahd, struct scb *scb)
635 {
636
637         /*
638          * The FIFO is only active for our transaction if
639          * the SCBPTR matches the SCB's ID and the firmware
640          * has installed a handler for the FIFO or we have
641          * a pending SAVEPTRS or CFG4DATA interrupt.
642          */
643         if (ahd_get_scbptr(ahd) != SCB_GET_TAG(scb)
644          || ((ahd_inb(ahd, LONGJMP_ADDR+1) & INVALID_ADDR) != 0
645           && (ahd_inb(ahd, SEQINTSRC) & (CFG4DATA|SAVEPTRS)) == 0))
646                 return (0);
647
648         return (1);
649 }
650
651 /*
652  * Run a data fifo to completion for a transaction we know
653  * has completed across the SCSI bus (good status has been
654  * received).  We are already set to the correct FIFO mode
655  * on entry to this routine.
656  *
657  * This function attempts to operate exactly as the firmware
658  * would when running this FIFO.  Care must be taken to update
659  * this routine any time the firmware's FIFO algorithm is
660  * changed.
661  */
662 static void
663 ahd_run_data_fifo(struct ahd_softc *ahd, struct scb *scb)
664 {
665         u_int seqintsrc;
666
667         seqintsrc = ahd_inb(ahd, SEQINTSRC);
668         if ((seqintsrc & CFG4DATA) != 0) {
669                 uint32_t datacnt;
670                 uint32_t sgptr;
671
672                 /*
673                  * Clear full residual flag.
674                  */
675                 sgptr = ahd_inl_scbram(ahd, SCB_SGPTR) & ~SG_FULL_RESID;
676                 ahd_outb(ahd, SCB_SGPTR, sgptr);
677
678                 /*
679                  * Load datacnt and address.
680                  */
681                 datacnt = ahd_inl_scbram(ahd, SCB_DATACNT);
682                 if ((datacnt & AHD_DMA_LAST_SEG) != 0) {
683                         sgptr |= LAST_SEG;
684                         ahd_outb(ahd, SG_STATE, 0);
685                 } else
686                         ahd_outb(ahd, SG_STATE, LOADING_NEEDED);
687                 ahd_outq(ahd, HADDR, ahd_inq_scbram(ahd, SCB_DATAPTR));
688                 ahd_outl(ahd, HCNT, datacnt & AHD_SG_LEN_MASK);
689                 ahd_outb(ahd, SG_CACHE_PRE, sgptr);
690                 ahd_outb(ahd, DFCNTRL, PRELOADEN|SCSIEN|HDMAEN);
691
692                 /*
693                  * Initialize Residual Fields.
694                  */
695                 ahd_outb(ahd, SCB_RESIDUAL_DATACNT+3, datacnt >> 24);
696                 ahd_outl(ahd, SCB_RESIDUAL_SGPTR, sgptr & SG_PTR_MASK);
697
698                 /*
699                  * Mark the SCB as having a FIFO in use.
700                  */
701                 ahd_outb(ahd, SCB_FIFO_USE_COUNT,
702                          ahd_inb_scbram(ahd, SCB_FIFO_USE_COUNT) + 1);
703
704                 /*
705                  * Install a "fake" handler for this FIFO.
706                  */
707                 ahd_outw(ahd, LONGJMP_ADDR, 0);
708
709                 /*
710                  * Notify the hardware that we have satisfied
711                  * this sequencer interrupt.
712                  */
713                 ahd_outb(ahd, CLRSEQINTSRC, CLRCFG4DATA);
714         } else if ((seqintsrc & SAVEPTRS) != 0) {
715                 uint32_t sgptr;
716                 uint32_t resid;
717
718                 if ((ahd_inb(ahd, LONGJMP_ADDR+1)&INVALID_ADDR) != 0) {
719                         /*
720                          * Snapshot Save Pointers.  All that
721                          * is necessary to clear the snapshot
722                          * is a CLRCHN.
723                          */
724                         goto clrchn;
725                 }
726
727                 /*
728                  * Disable S/G fetch so the DMA engine
729                  * is available to future users.
730                  */
731                 if ((ahd_inb(ahd, SG_STATE) & FETCH_INPROG) != 0)
732                         ahd_outb(ahd, CCSGCTL, 0);
733                 ahd_outb(ahd, SG_STATE, 0);
734
735                 /*
736                  * Flush the data FIFO.  Strickly only
737                  * necessary for Rev A parts.
738                  */
739                 ahd_outb(ahd, DFCNTRL, ahd_inb(ahd, DFCNTRL) | FIFOFLUSH);
740
741                 /*
742                  * Calculate residual.
743                  */
744                 sgptr = ahd_inl_scbram(ahd, SCB_RESIDUAL_SGPTR);
745                 resid = ahd_inl(ahd, SHCNT);
746                 resid |= ahd_inb_scbram(ahd, SCB_RESIDUAL_DATACNT+3) << 24;
747                 ahd_outl(ahd, SCB_RESIDUAL_DATACNT, resid);
748                 if ((ahd_inb(ahd, SG_CACHE_SHADOW) & LAST_SEG) == 0) {
749                         /*
750                          * Must back up to the correct S/G element.
751                          * Typically this just means resetting our
752                          * low byte to the offset in the SG_CACHE,
753                          * but if we wrapped, we have to correct
754                          * the other bytes of the sgptr too.
755                          */
756                         if ((ahd_inb(ahd, SG_CACHE_SHADOW) & 0x80) != 0
757                          && (sgptr & 0x80) == 0)
758                                 sgptr -= 0x100;
759                         sgptr &= ~0xFF;
760                         sgptr |= ahd_inb(ahd, SG_CACHE_SHADOW)
761                                & SG_ADDR_MASK;
762                         ahd_outl(ahd, SCB_RESIDUAL_SGPTR, sgptr);
763                         ahd_outb(ahd, SCB_RESIDUAL_DATACNT + 3, 0);
764                 } else if ((resid & AHD_SG_LEN_MASK) == 0) {
765                         ahd_outb(ahd, SCB_RESIDUAL_SGPTR,
766                                  sgptr | SG_LIST_NULL);
767                 }
768                 /*
769                  * Save Pointers.
770                  */
771                 ahd_outq(ahd, SCB_DATAPTR, ahd_inq(ahd, SHADDR));
772                 ahd_outl(ahd, SCB_DATACNT, resid);
773                 ahd_outl(ahd, SCB_SGPTR, sgptr);
774                 ahd_outb(ahd, CLRSEQINTSRC, CLRSAVEPTRS);
775                 ahd_outb(ahd, SEQIMODE,
776                          ahd_inb(ahd, SEQIMODE) | ENSAVEPTRS);
777                 /*
778                  * If the data is to the SCSI bus, we are
779                  * done, otherwise wait for FIFOEMP.
780                  */
781                 if ((ahd_inb(ahd, DFCNTRL) & DIRECTION) != 0)
782                         goto clrchn;
783         } else if ((ahd_inb(ahd, SG_STATE) & LOADING_NEEDED) != 0) {
784                 uint32_t sgptr;
785                 uint64_t data_addr;
786                 uint32_t data_len;
787                 u_int    dfcntrl;
788
789                 /*
790                  * Disable S/G fetch so the DMA engine
791                  * is available to future users.  We won't
792                  * be using the DMA engine to load segments.
793                  */
794                 if ((ahd_inb(ahd, SG_STATE) & FETCH_INPROG) != 0) {
795                         ahd_outb(ahd, CCSGCTL, 0);
796                         ahd_outb(ahd, SG_STATE, LOADING_NEEDED);
797                 }
798
799                 /*
800                  * Wait for the DMA engine to notice that the
801                  * host transfer is enabled and that there is
802                  * space in the S/G FIFO for new segments before
803                  * loading more segments.
804                  */
805                 if ((ahd_inb(ahd, DFSTATUS) & PRELOAD_AVAIL) != 0
806                  && (ahd_inb(ahd, DFCNTRL) & HDMAENACK) != 0) {
807
808                         /*
809                          * Determine the offset of the next S/G
810                          * element to load.
811                          */
812                         sgptr = ahd_inl_scbram(ahd, SCB_RESIDUAL_SGPTR);
813                         sgptr &= SG_PTR_MASK;
814                         if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0) {
815                                 struct ahd_dma64_seg *sg;
816
817                                 sg = ahd_sg_bus_to_virt(ahd, scb, sgptr);
818                                 data_addr = sg->addr;
819                                 data_len = sg->len;
820                                 sgptr += sizeof(*sg);
821                         } else {
822                                 struct  ahd_dma_seg *sg;
823
824                                 sg = ahd_sg_bus_to_virt(ahd, scb, sgptr);
825                                 data_addr = sg->len & AHD_SG_HIGH_ADDR_MASK;
826                                 data_addr <<= 8;
827                                 data_addr |= sg->addr;
828                                 data_len = sg->len;
829                                 sgptr += sizeof(*sg);
830                         }
831
832                         /*
833                          * Update residual information.
834                          */
835                         ahd_outb(ahd, SCB_RESIDUAL_DATACNT+3, data_len >> 24);
836                         ahd_outl(ahd, SCB_RESIDUAL_SGPTR, sgptr);
837
838                         /*
839                          * Load the S/G.
840                          */
841                         if (data_len & AHD_DMA_LAST_SEG) {
842                                 sgptr |= LAST_SEG;
843                                 ahd_outb(ahd, SG_STATE, 0);
844                         }
845                         ahd_outq(ahd, HADDR, data_addr);
846                         ahd_outl(ahd, HCNT, data_len & AHD_SG_LEN_MASK);
847                         ahd_outb(ahd, SG_CACHE_PRE, sgptr & 0xFF);
848
849                         /*
850                          * Advertise the segment to the hardware.
851                          */
852                         dfcntrl = ahd_inb(ahd, DFCNTRL)|PRELOADEN|HDMAEN;
853                         if ((ahd->features & AHD_NEW_DFCNTRL_OPTS) != 0) {
854                                 /*
855                                  * Use SCSIENWRDIS so that SCSIEN
856                                  * is never modified by this
857                                  * operation.
858                                  */
859                                 dfcntrl |= SCSIENWRDIS;
860                         }
861                         ahd_outb(ahd, DFCNTRL, dfcntrl);
862                 }
863         } else if ((ahd_inb(ahd, SG_CACHE_SHADOW) & LAST_SEG_DONE) != 0) {
864
865                 /*
866                  * Transfer completed to the end of SG list
867                  * and has flushed to the host.
868                  */
869                 ahd_outb(ahd, SCB_SGPTR,
870                          ahd_inb_scbram(ahd, SCB_SGPTR) | SG_LIST_NULL);
871                 goto clrchn;
872         } else if ((ahd_inb(ahd, DFSTATUS) & FIFOEMP) != 0) {
873 clrchn:
874                 /*
875                  * Clear any handler for this FIFO, decrement
876                  * the FIFO use count for the SCB, and release
877                  * the FIFO.
878                  */
879                 ahd_outb(ahd, LONGJMP_ADDR + 1, INVALID_ADDR);
880                 ahd_outb(ahd, SCB_FIFO_USE_COUNT,
881                          ahd_inb_scbram(ahd, SCB_FIFO_USE_COUNT) - 1);
882                 ahd_outb(ahd, DFFSXFRCTL, CLRCHN);
883         }
884 }
885
886 /*
887  * Look for entries in the QoutFIFO that have completed.
888  * The valid_tag completion field indicates the validity
889  * of the entry - the valid value toggles each time through
890  * the queue. We use the sg_status field in the completion
891  * entry to avoid referencing the hscb if the completion
892  * occurred with no errors and no residual.  sg_status is
893  * a copy of the first byte (little endian) of the sgptr
894  * hscb field.
895  */
896 void
897 ahd_run_qoutfifo(struct ahd_softc *ahd)
898 {
899         struct ahd_completion *completion;
900         struct scb *scb;
901         u_int  scb_index;
902
903         if ((ahd->flags & AHD_RUNNING_QOUTFIFO) != 0)
904                 panic("ahd_run_qoutfifo recursion");
905         ahd->flags |= AHD_RUNNING_QOUTFIFO;
906         ahd_sync_qoutfifo(ahd, BUS_DMASYNC_POSTREAD);
907         for (;;) {
908                 completion = &ahd->qoutfifo[ahd->qoutfifonext];
909
910                 if (completion->valid_tag != ahd->qoutfifonext_valid_tag)
911                         break;
912
913                 scb_index = ahd_le16toh(completion->tag);
914                 scb = ahd_lookup_scb(ahd, scb_index);
915                 if (scb == NULL) {
916                         printf("%s: WARNING no command for scb %d "
917                                "(cmdcmplt)\nQOUTPOS = %d\n",
918                                ahd_name(ahd), scb_index,
919                                ahd->qoutfifonext);
920                         ahd_dump_card_state(ahd);
921                 } else if ((completion->sg_status & SG_STATUS_VALID) != 0) {
922                         ahd_handle_scb_status(ahd, scb);
923                 } else {
924                         ahd_done(ahd, scb);
925                 }
926
927                 ahd->qoutfifonext = (ahd->qoutfifonext+1) & (AHD_QOUT_SIZE-1);
928                 if (ahd->qoutfifonext == 0)
929                         ahd->qoutfifonext_valid_tag ^= QOUTFIFO_ENTRY_VALID;
930         }
931         ahd->flags &= ~AHD_RUNNING_QOUTFIFO;
932 }
933
934 /************************* Interrupt Handling *********************************/
935 void
936 ahd_handle_hwerrint(struct ahd_softc *ahd)
937 {
938         /*
939          * Some catastrophic hardware error has occurred.
940          * Print it for the user and disable the controller.
941          */
942         int i;
943         int error;
944
945         error = ahd_inb(ahd, ERROR);
946         for (i = 0; i < num_errors; i++) {
947                 if ((error & ahd_hard_errors[i].errno) != 0)
948                         printf("%s: hwerrint, %s\n",
949                                ahd_name(ahd), ahd_hard_errors[i].errmesg);
950         }
951
952         ahd_dump_card_state(ahd);
953         panic("BRKADRINT");
954
955         /* Tell everyone that this HBA is no longer available */
956         ahd_abort_scbs(ahd, CAM_TARGET_WILDCARD, ALL_CHANNELS,
957                        CAM_LUN_WILDCARD, SCB_LIST_NULL, ROLE_UNKNOWN,
958                        CAM_NO_HBA);
959
960         /* Tell the system that this controller has gone away. */
961         ahd_free(ahd);
962 }
963
964 #ifdef AHD_DEBUG
965 static void
966 ahd_dump_sglist(struct scb *scb)
967 {
968         int i;
969
970         if (scb->sg_count > 0) {
971                 if ((scb->ahd_softc->flags & AHD_64BIT_ADDRESSING) != 0) {
972                         struct ahd_dma64_seg *sg_list;
973
974                         sg_list = (struct ahd_dma64_seg*)scb->sg_list;
975                         for (i = 0; i < scb->sg_count; i++) {
976                                 uint64_t addr;
977                                 uint32_t len;
978
979                                 addr = ahd_le64toh(sg_list[i].addr);
980                                 len = ahd_le32toh(sg_list[i].len);
981                                 printf("sg[%d] - Addr 0x%x%x : Length %d%s\n",
982                                        i,
983                                        (uint32_t)((addr >> 32) & 0xFFFFFFFF),
984                                        (uint32_t)(addr & 0xFFFFFFFF),
985                                        sg_list[i].len & AHD_SG_LEN_MASK,
986                                        (sg_list[i].len & AHD_DMA_LAST_SEG)
987                                      ? " Last" : "");
988                         }
989                 } else {
990                         struct ahd_dma_seg *sg_list;
991
992                         sg_list = (struct ahd_dma_seg*)scb->sg_list;
993                         for (i = 0; i < scb->sg_count; i++) {
994                                 uint32_t len;
995
996                                 len = ahd_le32toh(sg_list[i].len);
997                                 printf("sg[%d] - Addr 0x%x%x : Length %d%s\n",
998                                        i,
999                                        (len & AHD_SG_HIGH_ADDR_MASK) >> 24,
1000                                        ahd_le32toh(sg_list[i].addr),
1001                                        len & AHD_SG_LEN_MASK,
1002                                        len & AHD_DMA_LAST_SEG ? " Last" : "");
1003                         }
1004                 }
1005         }
1006 }
1007 #endif  /*  AHD_DEBUG  */
1008
1009 void
1010 ahd_handle_seqint(struct ahd_softc *ahd, u_int intstat)
1011 {
1012         u_int seqintcode;
1013
1014         /*
1015          * Save the sequencer interrupt code and clear the SEQINT
1016          * bit. We will unpause the sequencer, if appropriate,
1017          * after servicing the request.
1018          */
1019         seqintcode = ahd_inb(ahd, SEQINTCODE);
1020         ahd_outb(ahd, CLRINT, CLRSEQINT);
1021         if ((ahd->bugs & AHD_INTCOLLISION_BUG) != 0) {
1022                 /*
1023                  * Unpause the sequencer and let it clear
1024                  * SEQINT by writing NO_SEQINT to it.  This
1025                  * will cause the sequencer to be paused again,
1026                  * which is the expected state of this routine.
1027                  */
1028                 ahd_unpause(ahd);
1029                 while (!ahd_is_paused(ahd))
1030                         ;
1031                 ahd_outb(ahd, CLRINT, CLRSEQINT);
1032         }
1033         ahd_update_modes(ahd);
1034 #ifdef AHD_DEBUG
1035         if ((ahd_debug & AHD_SHOW_MISC) != 0)
1036                 printf("%s: Handle Seqint Called for code %d\n",
1037                        ahd_name(ahd), seqintcode);
1038 #endif
1039         switch (seqintcode) {
1040         case ENTERING_NONPACK:
1041         {
1042                 struct  scb *scb;
1043                 u_int   scbid;
1044
1045                 AHD_ASSERT_MODES(ahd, ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK),
1046                                  ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK));
1047                 scbid = ahd_get_scbptr(ahd);
1048                 scb = ahd_lookup_scb(ahd, scbid);
1049                 if (scb == NULL) {
1050                         /*
1051                          * Somehow need to know if this
1052                          * is from a selection or reselection.
1053                          * From that, we can determine target
1054                          * ID so we at least have an I_T nexus.
1055                          */
1056                 } else {
1057                         ahd_outb(ahd, SAVED_SCSIID, scb->hscb->scsiid);
1058                         ahd_outb(ahd, SAVED_LUN, scb->hscb->lun);
1059                         ahd_outb(ahd, SEQ_FLAGS, 0x0);
1060                 }
1061                 if ((ahd_inb(ahd, LQISTAT2) & LQIPHASE_OUTPKT) != 0
1062                  && (ahd_inb(ahd, SCSISIGO) & ATNO) != 0) {
1063                         /*
1064                          * Phase change after read stream with
1065                          * CRC error with P0 asserted on last
1066                          * packet.
1067                          */
1068 #ifdef AHD_DEBUG
1069                         if ((ahd_debug & AHD_SHOW_RECOVERY) != 0)
1070                                 printf("%s: Assuming LQIPHASE_NLQ with "
1071                                        "P0 assertion\n", ahd_name(ahd));
1072 #endif
1073                 }
1074 #ifdef AHD_DEBUG
1075                 if ((ahd_debug & AHD_SHOW_RECOVERY) != 0)
1076                         printf("%s: Entering NONPACK\n", ahd_name(ahd));
1077 #endif
1078                 break;
1079         }
1080         case INVALID_SEQINT:
1081                 printf("%s: Invalid Sequencer interrupt occurred, "
1082                        "resetting channel.\n",
1083                        ahd_name(ahd));
1084 #ifdef AHD_DEBUG
1085                 if ((ahd_debug & AHD_SHOW_RECOVERY) != 0)
1086                         ahd_dump_card_state(ahd);
1087 #endif
1088                 ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
1089                 break;
1090         case STATUS_OVERRUN:
1091         {
1092                 struct  scb *scb;
1093                 u_int   scbid;
1094
1095                 scbid = ahd_get_scbptr(ahd);
1096                 scb = ahd_lookup_scb(ahd, scbid);
1097                 if (scb != NULL)
1098                         ahd_print_path(ahd, scb);
1099                 else
1100                         printf("%s: ", ahd_name(ahd));
1101                 printf("SCB %d Packetized Status Overrun", scbid);
1102                 ahd_dump_card_state(ahd);
1103                 ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
1104                 break;
1105         }
1106         case CFG4ISTAT_INTR:
1107         {
1108                 struct  scb *scb;
1109                 u_int   scbid;
1110
1111                 scbid = ahd_get_scbptr(ahd);
1112                 scb = ahd_lookup_scb(ahd, scbid);
1113                 if (scb == NULL) {
1114                         ahd_dump_card_state(ahd);
1115                         printf("CFG4ISTAT: Free SCB %d referenced", scbid);
1116                         panic("For safety");
1117                 }
1118                 ahd_outq(ahd, HADDR, scb->sense_busaddr);
1119                 ahd_outw(ahd, HCNT, AHD_SENSE_BUFSIZE);
1120                 ahd_outb(ahd, HCNT + 2, 0);
1121                 ahd_outb(ahd, SG_CACHE_PRE, SG_LAST_SEG);
1122                 ahd_outb(ahd, DFCNTRL, PRELOADEN|SCSIEN|HDMAEN);
1123                 break;
1124         }
1125         case ILLEGAL_PHASE:
1126         {
1127                 u_int bus_phase;
1128
1129                 bus_phase = ahd_inb(ahd, SCSISIGI) & PHASE_MASK;
1130                 printf("%s: ILLEGAL_PHASE 0x%x\n",
1131                        ahd_name(ahd), bus_phase);
1132
1133                 switch (bus_phase) {
1134                 case P_DATAOUT:
1135                 case P_DATAIN:
1136                 case P_DATAOUT_DT:
1137                 case P_DATAIN_DT:
1138                 case P_MESGOUT:
1139                 case P_STATUS:
1140                 case P_MESGIN:
1141                         ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
1142                         printf("%s: Issued Bus Reset.\n", ahd_name(ahd));
1143                         break;
1144                 case P_COMMAND:
1145                 {
1146                         struct  ahd_devinfo devinfo;
1147                         struct  scb *scb;
1148                         struct  ahd_initiator_tinfo *targ_info;
1149                         struct  ahd_tmode_tstate *tstate;
1150                         struct  ahd_transinfo *tinfo;
1151                         u_int   scbid;
1152
1153                         /*
1154                          * If a target takes us into the command phase
1155                          * assume that it has been externally reset and
1156                          * has thus lost our previous packetized negotiation
1157                          * agreement.
1158                          * Revert to async/narrow transfers until we
1159                          * can renegotiate with the device and notify
1160                          * the OSM about the reset.
1161                          */
1162                         scbid = ahd_get_scbptr(ahd);
1163                         scb = ahd_lookup_scb(ahd, scbid);
1164                         if (scb == NULL) {
1165                                 printf("Invalid phase with no valid SCB.  "
1166                                        "Resetting bus.\n");
1167                                 ahd_reset_channel(ahd, 'A',
1168                                                   /*Initiate Reset*/TRUE);
1169                                 break;
1170                         }
1171                         ahd_compile_devinfo(&devinfo, SCB_GET_OUR_ID(scb),
1172                                             SCB_GET_TARGET(ahd, scb),
1173                                             SCB_GET_LUN(scb),
1174                                             SCB_GET_CHANNEL(ahd, scb),
1175                                             ROLE_INITIATOR);
1176                         targ_info = ahd_fetch_transinfo(ahd,
1177                                                         devinfo.channel,
1178                                                         devinfo.our_scsiid,
1179                                                         devinfo.target,
1180                                                         &tstate);
1181                         tinfo = &targ_info->curr;
1182                         ahd_set_width(ahd, &devinfo, MSG_EXT_WDTR_BUS_8_BIT,
1183                                       AHD_TRANS_ACTIVE, /*paused*/TRUE);
1184                         ahd_set_syncrate(ahd, &devinfo, /*period*/0,
1185                                          /*offset*/0, /*ppr_options*/0,
1186                                          AHD_TRANS_ACTIVE, /*paused*/TRUE);
1187                         scb->flags |= SCB_EXTERNAL_RESET;
1188                         ahd_freeze_devq(ahd, scb);
1189                         ahd_set_transaction_status(scb, CAM_REQUEUE_REQ);
1190                         ahd_freeze_scb(scb);
1191
1192                         /* Notify XPT */
1193                         ahd_send_async(ahd, devinfo.channel, devinfo.target,
1194                                        CAM_LUN_WILDCARD, AC_SENT_BDR);
1195
1196                         /*
1197                          * Allow the sequencer to continue with
1198                          * non-pack processing.
1199                          */
1200                         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
1201                         ahd_outb(ahd, CLRLQOINT1, CLRLQOPHACHGINPKT);
1202                         if ((ahd->bugs & AHD_CLRLQO_AUTOCLR_BUG) != 0) {
1203                                 ahd_outb(ahd, CLRLQOINT1, 0);
1204                         }
1205 #ifdef AHD_DEBUG
1206                         if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) {
1207                                 ahd_print_path(ahd, scb);
1208                                 printf("Unexpected command phase from "
1209                                        "packetized target\n");
1210                         }
1211 #endif
1212                         break;
1213                 }
1214                 }
1215                 break;
1216         }
1217         case CFG4OVERRUN:
1218         {
1219                 struct  scb *scb;
1220                 u_int   scb_index;
1221                 
1222 #ifdef AHD_DEBUG
1223                 if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) {
1224                         printf("%s: CFG4OVERRUN mode = %x\n", ahd_name(ahd),
1225                                ahd_inb(ahd, MODE_PTR));
1226                 }
1227 #endif
1228                 scb_index = ahd_get_scbptr(ahd);
1229                 scb = ahd_lookup_scb(ahd, scb_index);
1230                 if (scb == NULL) {
1231                         /*
1232                          * Attempt to transfer to an SCB that is
1233                          * not outstanding.
1234                          */
1235                         ahd_assert_atn(ahd);
1236                         ahd_outb(ahd, MSG_OUT, HOST_MSG);
1237                         ahd->msgout_buf[0] = MSG_ABORT_TASK;
1238                         ahd->msgout_len = 1;
1239                         ahd->msgout_index = 0;
1240                         ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
1241                         /*
1242                          * Clear status received flag to prevent any
1243                          * attempt to complete this bogus SCB.
1244                          */
1245                         ahd_outb(ahd, SCB_CONTROL,
1246                                  ahd_inb_scbram(ahd, SCB_CONTROL)
1247                                  & ~STATUS_RCVD);
1248                 }
1249                 break;
1250         }
1251         case DUMP_CARD_STATE:
1252         {
1253                 ahd_dump_card_state(ahd);
1254                 break;
1255         }
1256         case PDATA_REINIT:
1257         {
1258 #ifdef AHD_DEBUG
1259                 if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) {
1260                         printf("%s: PDATA_REINIT - DFCNTRL = 0x%x "
1261                                "SG_CACHE_SHADOW = 0x%x\n",
1262                                ahd_name(ahd), ahd_inb(ahd, DFCNTRL),
1263                                ahd_inb(ahd, SG_CACHE_SHADOW));
1264                 }
1265 #endif
1266                 ahd_reinitialize_dataptrs(ahd);
1267                 break;
1268         }
1269         case HOST_MSG_LOOP:
1270         {
1271                 struct ahd_devinfo devinfo;
1272
1273                 /*
1274                  * The sequencer has encountered a message phase
1275                  * that requires host assistance for completion.
1276                  * While handling the message phase(s), we will be
1277                  * notified by the sequencer after each byte is
1278                  * transfered so we can track bus phase changes.
1279                  *
1280                  * If this is the first time we've seen a HOST_MSG_LOOP
1281                  * interrupt, initialize the state of the host message
1282                  * loop.
1283                  */
1284                 ahd_fetch_devinfo(ahd, &devinfo);
1285                 if (ahd->msg_type == MSG_TYPE_NONE) {
1286                         struct scb *scb;
1287                         u_int scb_index;
1288                         u_int bus_phase;
1289
1290                         bus_phase = ahd_inb(ahd, SCSISIGI) & PHASE_MASK;
1291                         if (bus_phase != P_MESGIN
1292                          && bus_phase != P_MESGOUT) {
1293                                 printf("ahd_intr: HOST_MSG_LOOP bad "
1294                                        "phase 0x%x\n", bus_phase);
1295                                 /*
1296                                  * Probably transitioned to bus free before
1297                                  * we got here.  Just punt the message.
1298                                  */
1299                                 ahd_dump_card_state(ahd);
1300                                 ahd_clear_intstat(ahd);
1301                                 ahd_restart(ahd);
1302                                 return;
1303                         }
1304
1305                         scb_index = ahd_get_scbptr(ahd);
1306                         scb = ahd_lookup_scb(ahd, scb_index);
1307                         if (devinfo.role == ROLE_INITIATOR) {
1308                                 if (bus_phase == P_MESGOUT)
1309                                         ahd_setup_initiator_msgout(ahd,
1310                                                                    &devinfo,
1311                                                                    scb);
1312                                 else {
1313                                         ahd->msg_type =
1314                                             MSG_TYPE_INITIATOR_MSGIN;
1315                                         ahd->msgin_index = 0;
1316                                 }
1317                         }
1318 #ifdef AHD_TARGET_MODE
1319                         else {
1320                                 if (bus_phase == P_MESGOUT) {
1321                                         ahd->msg_type =
1322                                             MSG_TYPE_TARGET_MSGOUT;
1323                                         ahd->msgin_index = 0;
1324                                 }
1325                                 else 
1326                                         ahd_setup_target_msgin(ahd,
1327                                                                &devinfo,
1328                                                                scb);
1329                         }
1330 #endif
1331                 }
1332
1333                 ahd_handle_message_phase(ahd);
1334                 break;
1335         }
1336         case NO_MATCH:
1337         {
1338                 /* Ensure we don't leave the selection hardware on */
1339                 AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
1340                 ahd_outb(ahd, SCSISEQ0, ahd_inb(ahd, SCSISEQ0) & ~ENSELO);
1341
1342                 printf("%s:%c:%d: no active SCB for reconnecting "
1343                        "target - issuing BUS DEVICE RESET\n",
1344                        ahd_name(ahd), 'A', ahd_inb(ahd, SELID) >> 4);
1345                 printf("SAVED_SCSIID == 0x%x, SAVED_LUN == 0x%x, "
1346                        "REG0 == 0x%x ACCUM = 0x%x\n",
1347                        ahd_inb(ahd, SAVED_SCSIID), ahd_inb(ahd, SAVED_LUN),
1348                        ahd_inw(ahd, REG0), ahd_inb(ahd, ACCUM));
1349                 printf("SEQ_FLAGS == 0x%x, SCBPTR == 0x%x, BTT == 0x%x, "
1350                        "SINDEX == 0x%x\n",
1351                        ahd_inb(ahd, SEQ_FLAGS), ahd_get_scbptr(ahd),
1352                        ahd_find_busy_tcl(ahd,
1353                                          BUILD_TCL(ahd_inb(ahd, SAVED_SCSIID),
1354                                                    ahd_inb(ahd, SAVED_LUN))),
1355                        ahd_inw(ahd, SINDEX));
1356                 printf("SELID == 0x%x, SCB_SCSIID == 0x%x, SCB_LUN == 0x%x, "
1357                        "SCB_CONTROL == 0x%x\n",
1358                        ahd_inb(ahd, SELID), ahd_inb_scbram(ahd, SCB_SCSIID),
1359                        ahd_inb_scbram(ahd, SCB_LUN),
1360                        ahd_inb_scbram(ahd, SCB_CONTROL));
1361                 printf("SCSIBUS[0] == 0x%x, SCSISIGI == 0x%x\n",
1362                        ahd_inb(ahd, SCSIBUS), ahd_inb(ahd, SCSISIGI));
1363                 printf("SXFRCTL0 == 0x%x\n", ahd_inb(ahd, SXFRCTL0));
1364                 printf("SEQCTL0 == 0x%x\n", ahd_inb(ahd, SEQCTL0));
1365                 ahd_dump_card_state(ahd);
1366                 ahd->msgout_buf[0] = MSG_BUS_DEV_RESET;
1367                 ahd->msgout_len = 1;
1368                 ahd->msgout_index = 0;
1369                 ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
1370                 ahd_outb(ahd, MSG_OUT, HOST_MSG);
1371                 ahd_assert_atn(ahd);
1372                 break;
1373         }
1374         case PROTO_VIOLATION:
1375         {
1376                 ahd_handle_proto_violation(ahd);
1377                 break;
1378         }
1379         case IGN_WIDE_RES:
1380         {
1381                 struct ahd_devinfo devinfo;
1382
1383                 ahd_fetch_devinfo(ahd, &devinfo);
1384                 ahd_handle_ign_wide_residue(ahd, &devinfo);
1385                 break;
1386         }
1387         case BAD_PHASE:
1388         {
1389                 u_int lastphase;
1390
1391                 lastphase = ahd_inb(ahd, LASTPHASE);
1392                 printf("%s:%c:%d: unknown scsi bus phase %x, "
1393                        "lastphase = 0x%x.  Attempting to continue\n",
1394                        ahd_name(ahd), 'A',
1395                        SCSIID_TARGET(ahd, ahd_inb(ahd, SAVED_SCSIID)),
1396                        lastphase, ahd_inb(ahd, SCSISIGI));
1397                 break;
1398         }
1399         case MISSED_BUSFREE:
1400         {
1401                 u_int lastphase;
1402
1403                 lastphase = ahd_inb(ahd, LASTPHASE);
1404                 printf("%s:%c:%d: Missed busfree. "
1405                        "Lastphase = 0x%x, Curphase = 0x%x\n",
1406                        ahd_name(ahd), 'A',
1407                        SCSIID_TARGET(ahd, ahd_inb(ahd, SAVED_SCSIID)),
1408                        lastphase, ahd_inb(ahd, SCSISIGI));
1409                 ahd_restart(ahd);
1410                 return;
1411         }
1412         case DATA_OVERRUN:
1413         {
1414                 /*
1415                  * When the sequencer detects an overrun, it
1416                  * places the controller in "BITBUCKET" mode
1417                  * and allows the target to complete its transfer.
1418                  * Unfortunately, none of the counters get updated
1419                  * when the controller is in this mode, so we have
1420                  * no way of knowing how large the overrun was.
1421                  */
1422                 struct  scb *scb;
1423                 u_int   scbindex;
1424 #ifdef AHD_DEBUG
1425                 u_int   lastphase;
1426 #endif
1427
1428                 scbindex = ahd_get_scbptr(ahd);
1429                 scb = ahd_lookup_scb(ahd, scbindex);
1430 #ifdef AHD_DEBUG
1431                 lastphase = ahd_inb(ahd, LASTPHASE);
1432                 if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) {
1433                         ahd_print_path(ahd, scb);
1434                         printf("data overrun detected %s.  Tag == 0x%x.\n",
1435                                ahd_lookup_phase_entry(lastphase)->phasemsg,
1436                                SCB_GET_TAG(scb));
1437                         ahd_print_path(ahd, scb);
1438                         printf("%s seen Data Phase.  Length = %ld.  "
1439                                "NumSGs = %d.\n",
1440                                ahd_inb(ahd, SEQ_FLAGS) & DPHASE
1441                                ? "Have" : "Haven't",
1442                                ahd_get_transfer_length(scb), scb->sg_count);
1443                         ahd_dump_sglist(scb);
1444                 }
1445 #endif
1446
1447                 /*
1448                  * Set this and it will take effect when the
1449                  * target does a command complete.
1450                  */
1451                 ahd_freeze_devq(ahd, scb);
1452                 ahd_set_transaction_status(scb, CAM_DATA_RUN_ERR);
1453                 ahd_freeze_scb(scb);
1454                 break;
1455         }
1456         case MKMSG_FAILED:
1457         {
1458                 struct ahd_devinfo devinfo;
1459                 struct scb *scb;
1460                 u_int scbid;
1461
1462                 ahd_fetch_devinfo(ahd, &devinfo);
1463                 printf("%s:%c:%d:%d: Attempt to issue message failed\n",
1464                        ahd_name(ahd), devinfo.channel, devinfo.target,
1465                        devinfo.lun);
1466                 scbid = ahd_get_scbptr(ahd);
1467                 scb = ahd_lookup_scb(ahd, scbid);
1468                 if (scb != NULL
1469                  && (scb->flags & SCB_RECOVERY_SCB) != 0)
1470                         /*
1471                          * Ensure that we didn't put a second instance of this
1472                          * SCB into the QINFIFO.
1473                          */
1474                         ahd_search_qinfifo(ahd, SCB_GET_TARGET(ahd, scb),
1475                                            SCB_GET_CHANNEL(ahd, scb),
1476                                            SCB_GET_LUN(scb), SCB_GET_TAG(scb),
1477                                            ROLE_INITIATOR, /*status*/0,
1478                                            SEARCH_REMOVE);
1479                 ahd_outb(ahd, SCB_CONTROL,
1480                          ahd_inb_scbram(ahd, SCB_CONTROL) & ~MK_MESSAGE);
1481                 break;
1482         }
1483         case TASKMGMT_FUNC_COMPLETE:
1484         {
1485                 u_int   scbid;
1486                 struct  scb *scb;
1487
1488                 scbid = ahd_get_scbptr(ahd);
1489                 scb = ahd_lookup_scb(ahd, scbid);
1490                 if (scb != NULL) {
1491                         u_int      lun;
1492                         u_int      tag;
1493                         cam_status error;
1494
1495                         ahd_print_path(ahd, scb);
1496                         printf("Task Management Func 0x%x Complete\n",
1497                                scb->hscb->task_management);
1498                         lun = CAM_LUN_WILDCARD;
1499                         tag = SCB_LIST_NULL;
1500
1501                         switch (scb->hscb->task_management) {
1502                         case SIU_TASKMGMT_ABORT_TASK:
1503                                 tag = SCB_GET_TAG(scb);
1504                         case SIU_TASKMGMT_ABORT_TASK_SET:
1505                         case SIU_TASKMGMT_CLEAR_TASK_SET:
1506                                 lun = scb->hscb->lun;
1507                                 error = CAM_REQ_ABORTED;
1508                                 ahd_abort_scbs(ahd, SCB_GET_TARGET(ahd, scb),
1509                                                'A', lun, tag, ROLE_INITIATOR,
1510                                                error);
1511                                 break;
1512                         case SIU_TASKMGMT_LUN_RESET:
1513                                 lun = scb->hscb->lun;
1514                         case SIU_TASKMGMT_TARGET_RESET:
1515                         {
1516                                 struct ahd_devinfo devinfo;
1517
1518                                 ahd_scb_devinfo(ahd, &devinfo, scb);
1519                                 error = CAM_BDR_SENT;
1520                                 ahd_handle_devreset(ahd, &devinfo, lun,
1521                                                     CAM_BDR_SENT,
1522                                                     lun != CAM_LUN_WILDCARD
1523                                                     ? "Lun Reset"
1524                                                     : "Target Reset",
1525                                                     /*verbose_level*/0);
1526                                 break;
1527                         }
1528                         default:
1529                                 panic("Unexpected TaskMgmt Func\n");
1530                                 break;
1531                         }
1532                 }
1533                 break;
1534         }
1535         case TASKMGMT_CMD_CMPLT_OKAY:
1536         {
1537                 u_int   scbid;
1538                 struct  scb *scb;
1539
1540                 /*
1541                  * An ABORT TASK TMF failed to be delivered before
1542                  * the targeted command completed normally.
1543                  */
1544                 scbid = ahd_get_scbptr(ahd);
1545                 scb = ahd_lookup_scb(ahd, scbid);
1546                 if (scb != NULL) {
1547                         /*
1548                          * Remove the second instance of this SCB from
1549                          * the QINFIFO if it is still there.
1550                          */
1551                         ahd_print_path(ahd, scb);
1552                         printf("SCB completes before TMF\n");
1553                         /*
1554                          * Handle losing the race.  Wait until any
1555                          * current selection completes.  We will then
1556                          * set the TMF back to zero in this SCB so that
1557                          * the sequencer doesn't bother to issue another
1558                          * sequencer interrupt for its completion.
1559                          */
1560                         while ((ahd_inb(ahd, SCSISEQ0) & ENSELO) != 0
1561                             && (ahd_inb(ahd, SSTAT0) & SELDO) == 0
1562                             && (ahd_inb(ahd, SSTAT1) & SELTO) == 0)
1563                                 ;
1564                         ahd_outb(ahd, SCB_TASK_MANAGEMENT, 0);
1565                         ahd_search_qinfifo(ahd, SCB_GET_TARGET(ahd, scb),
1566                                            SCB_GET_CHANNEL(ahd, scb),  
1567                                            SCB_GET_LUN(scb), SCB_GET_TAG(scb), 
1568                                            ROLE_INITIATOR, /*status*/0,   
1569                                            SEARCH_REMOVE);
1570                 }
1571                 break;
1572         }
1573         case TRACEPOINT0:
1574         case TRACEPOINT1:
1575         case TRACEPOINT2:
1576         case TRACEPOINT3:
1577                 printf("%s: Tracepoint %d\n", ahd_name(ahd),
1578                        seqintcode - TRACEPOINT0);
1579                 break;
1580         case NO_SEQINT:
1581                 break;
1582         case SAW_HWERR:
1583                 ahd_handle_hwerrint(ahd);
1584                 break;
1585         default:
1586                 printf("%s: Unexpected SEQINTCODE %d\n", ahd_name(ahd),
1587                        seqintcode);
1588                 break;
1589         }
1590         /*
1591          *  The sequencer is paused immediately on
1592          *  a SEQINT, so we should restart it when
1593          *  we're done.
1594          */
1595         ahd_unpause(ahd);
1596 }
1597
1598 void
1599 ahd_handle_scsiint(struct ahd_softc *ahd, u_int intstat)
1600 {
1601         struct scb      *scb;
1602         u_int            status0;
1603         u_int            status3;
1604         u_int            status;
1605         u_int            lqistat1;
1606         u_int            lqostat0;
1607         u_int            scbid;
1608         u_int            busfreetime;
1609
1610         ahd_update_modes(ahd);
1611         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
1612
1613         status3 = ahd_inb(ahd, SSTAT3) & (NTRAMPERR|OSRAMPERR);
1614         status0 = ahd_inb(ahd, SSTAT0) & (IOERR|OVERRUN|SELDI|SELDO);
1615         status = ahd_inb(ahd, SSTAT1) & (SELTO|SCSIRSTI|BUSFREE|SCSIPERR);
1616         lqistat1 = ahd_inb(ahd, LQISTAT1);
1617         lqostat0 = ahd_inb(ahd, LQOSTAT0);
1618         busfreetime = ahd_inb(ahd, SSTAT2) & BUSFREETIME;
1619
1620         /*
1621          * Ignore external resets after a bus reset.
1622          */
1623         if (((status & SCSIRSTI) != 0) && (ahd->flags & AHD_BUS_RESET_ACTIVE))
1624                 return;
1625
1626         /*
1627          * Clear bus reset flag
1628          */
1629         ahd->flags &= ~AHD_BUS_RESET_ACTIVE;
1630
1631         if ((status0 & (SELDI|SELDO)) != 0) {
1632                 u_int simode0;
1633
1634                 ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
1635                 simode0 = ahd_inb(ahd, SIMODE0);
1636                 status0 &= simode0 & (IOERR|OVERRUN|SELDI|SELDO);
1637                 ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
1638         }
1639         scbid = ahd_get_scbptr(ahd);
1640         scb = ahd_lookup_scb(ahd, scbid);
1641         if (scb != NULL
1642          && (ahd_inb(ahd, SEQ_FLAGS) & NOT_IDENTIFIED) != 0)
1643                 scb = NULL;
1644
1645         if ((status0 & IOERR) != 0) {
1646                 u_int now_lvd;
1647
1648                 now_lvd = ahd_inb(ahd, SBLKCTL) & ENAB40;
1649                 printf("%s: Transceiver State Has Changed to %s mode\n",
1650                        ahd_name(ahd), now_lvd ? "LVD" : "SE");
1651                 ahd_outb(ahd, CLRSINT0, CLRIOERR);
1652                 /*
1653                  * A change in I/O mode is equivalent to a bus reset.
1654                  */
1655                 ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
1656                 ahd_pause(ahd);
1657                 ahd_setup_iocell_workaround(ahd);
1658                 ahd_unpause(ahd);
1659         } else if ((status0 & OVERRUN) != 0) {
1660
1661                 printf("%s: SCSI offset overrun detected.  Resetting bus.\n",
1662                        ahd_name(ahd));
1663                 ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
1664         } else if ((status & SCSIRSTI) != 0) {
1665
1666                 printf("%s: Someone reset channel A\n", ahd_name(ahd));
1667                 ahd_reset_channel(ahd, 'A', /*Initiate Reset*/FALSE);
1668         } else if ((status & SCSIPERR) != 0) {
1669
1670                 /* Make sure the sequencer is in a safe location. */
1671                 ahd_clear_critical_section(ahd);
1672
1673                 ahd_handle_transmission_error(ahd);
1674         } else if (lqostat0 != 0) {
1675
1676                 printf("%s: lqostat0 == 0x%x!\n", ahd_name(ahd), lqostat0);
1677                 ahd_outb(ahd, CLRLQOINT0, lqostat0);
1678                 if ((ahd->bugs & AHD_CLRLQO_AUTOCLR_BUG) != 0)
1679                         ahd_outb(ahd, CLRLQOINT1, 0);
1680         } else if ((status & SELTO) != 0) {
1681                 u_int  scbid;
1682
1683                 /* Stop the selection */
1684                 ahd_outb(ahd, SCSISEQ0, 0);
1685
1686                 /* Make sure the sequencer is in a safe location. */
1687                 ahd_clear_critical_section(ahd);
1688
1689                 /* No more pending messages */
1690                 ahd_clear_msg_state(ahd);
1691
1692                 /* Clear interrupt state */
1693                 ahd_outb(ahd, CLRSINT1, CLRSELTIMEO|CLRBUSFREE|CLRSCSIPERR);
1694
1695                 /*
1696                  * Although the driver does not care about the
1697                  * 'Selection in Progress' status bit, the busy
1698                  * LED does.  SELINGO is only cleared by a sucessfull
1699                  * selection, so we must manually clear it to insure
1700                  * the LED turns off just incase no future successful
1701                  * selections occur (e.g. no devices on the bus).
1702                  */
1703                 ahd_outb(ahd, CLRSINT0, CLRSELINGO);
1704
1705                 scbid = ahd_inw(ahd, WAITING_TID_HEAD);
1706                 scb = ahd_lookup_scb(ahd, scbid);
1707                 if (scb == NULL) {
1708                         printf("%s: ahd_intr - referenced scb not "
1709                                "valid during SELTO scb(0x%x)\n",
1710                                ahd_name(ahd), scbid);
1711                         ahd_dump_card_state(ahd);
1712                 } else {
1713                         struct ahd_devinfo devinfo;
1714 #ifdef AHD_DEBUG
1715                         if ((ahd_debug & AHD_SHOW_SELTO) != 0) {
1716                                 ahd_print_path(ahd, scb);
1717                                 printf("Saw Selection Timeout for SCB 0x%x\n",
1718                                        scbid);
1719                         }
1720 #endif
1721                         ahd_scb_devinfo(ahd, &devinfo, scb);
1722                         ahd_set_transaction_status(scb, CAM_SEL_TIMEOUT);
1723                         ahd_freeze_devq(ahd, scb);
1724
1725                         /*
1726                          * Cancel any pending transactions on the device
1727                          * now that it seems to be missing.  This will
1728                          * also revert us to async/narrow transfers until
1729                          * we can renegotiate with the device.
1730                          */
1731                         ahd_handle_devreset(ahd, &devinfo,
1732                                             CAM_LUN_WILDCARD,
1733                                             CAM_SEL_TIMEOUT,
1734                                             "Selection Timeout",
1735                                             /*verbose_level*/1);
1736                 }
1737                 ahd_outb(ahd, CLRINT, CLRSCSIINT);
1738                 ahd_iocell_first_selection(ahd);
1739                 ahd_unpause(ahd);
1740         } else if ((status0 & (SELDI|SELDO)) != 0) {
1741
1742                 ahd_iocell_first_selection(ahd);
1743                 ahd_unpause(ahd);
1744         } else if (status3 != 0) {
1745                 printf("%s: SCSI Cell parity error SSTAT3 == 0x%x\n",
1746                        ahd_name(ahd), status3);
1747                 ahd_outb(ahd, CLRSINT3, status3);
1748         } else if ((lqistat1 & (LQIPHASE_LQ|LQIPHASE_NLQ)) != 0) {
1749
1750                 /* Make sure the sequencer is in a safe location. */
1751                 ahd_clear_critical_section(ahd);
1752
1753                 ahd_handle_lqiphase_error(ahd, lqistat1);
1754         } else if ((lqistat1 & LQICRCI_NLQ) != 0) {
1755                 /*
1756                  * This status can be delayed during some
1757                  * streaming operations.  The SCSIPHASE
1758                  * handler has already dealt with this case
1759                  * so just clear the error.
1760                  */
1761                 ahd_outb(ahd, CLRLQIINT1, CLRLQICRCI_NLQ);
1762         } else if ((status & BUSFREE) != 0
1763                 || (lqistat1 & LQOBUSFREE) != 0) {
1764                 u_int lqostat1;
1765                 int   restart;
1766                 int   clear_fifo;
1767                 int   packetized;
1768                 u_int mode;
1769
1770                 /*
1771                  * Clear our selection hardware as soon as possible.
1772                  * We may have an entry in the waiting Q for this target,
1773                  * that is affected by this busfree and we don't want to
1774                  * go about selecting the target while we handle the event.
1775                  */
1776                 ahd_outb(ahd, SCSISEQ0, 0);
1777
1778                 /* Make sure the sequencer is in a safe location. */
1779                 ahd_clear_critical_section(ahd);
1780
1781                 /*
1782                  * Determine what we were up to at the time of
1783                  * the busfree.
1784                  */
1785                 mode = AHD_MODE_SCSI;
1786                 busfreetime = ahd_inb(ahd, SSTAT2) & BUSFREETIME;
1787                 lqostat1 = ahd_inb(ahd, LQOSTAT1);
1788                 switch (busfreetime) {
1789                 case BUSFREE_DFF0:
1790                 case BUSFREE_DFF1:
1791                 {
1792                         u_int   scbid;
1793                         struct  scb *scb;
1794
1795                         mode = busfreetime == BUSFREE_DFF0
1796                              ? AHD_MODE_DFF0 : AHD_MODE_DFF1;
1797                         ahd_set_modes(ahd, mode, mode);
1798                         scbid = ahd_get_scbptr(ahd);
1799                         scb = ahd_lookup_scb(ahd, scbid);
1800                         if (scb == NULL) {
1801                                 printf("%s: Invalid SCB %d in DFF%d "
1802                                        "during unexpected busfree\n",
1803                                        ahd_name(ahd), scbid, mode);
1804                                 packetized = 0;
1805                         } else
1806                                 packetized = (scb->flags & SCB_PACKETIZED) != 0;
1807                         clear_fifo = 1;
1808                         break;
1809                 }
1810                 case BUSFREE_LQO:
1811                         clear_fifo = 0;
1812                         packetized = 1;
1813                         break;
1814                 default:
1815                         clear_fifo = 0;
1816                         packetized =  (lqostat1 & LQOBUSFREE) != 0;
1817                         if (!packetized
1818                          && ahd_inb(ahd, LASTPHASE) == P_BUSFREE
1819                          && (ahd_inb(ahd, SSTAT0) & SELDI) == 0
1820                          && ((ahd_inb(ahd, SSTAT0) & SELDO) == 0
1821                           || (ahd_inb(ahd, SCSISEQ0) & ENSELO) == 0))
1822                                 /*
1823                                  * Assume packetized if we are not
1824                                  * on the bus in a non-packetized
1825                                  * capacity and any pending selection
1826                                  * was a packetized selection.
1827                                  */
1828                                 packetized = 1;
1829                         break;
1830                 }
1831
1832 #ifdef AHD_DEBUG
1833                 if ((ahd_debug & AHD_SHOW_MISC) != 0)
1834                         printf("Saw Busfree.  Busfreetime = 0x%x.\n",
1835                                busfreetime);
1836 #endif
1837                 /*
1838                  * Busfrees that occur in non-packetized phases are
1839                  * handled by the nonpkt_busfree handler.
1840                  */
1841                 if (packetized && ahd_inb(ahd, LASTPHASE) == P_BUSFREE) {
1842                         restart = ahd_handle_pkt_busfree(ahd, busfreetime);
1843                 } else {
1844                         packetized = 0;
1845                         restart = ahd_handle_nonpkt_busfree(ahd);
1846                 }
1847                 /*
1848                  * Clear the busfree interrupt status.  The setting of
1849                  * the interrupt is a pulse, so in a perfect world, we
1850                  * would not need to muck with the ENBUSFREE logic.  This
1851                  * would ensure that if the bus moves on to another
1852                  * connection, busfree protection is still in force.  If
1853                  * BUSFREEREV is broken, however, we must manually clear
1854                  * the ENBUSFREE if the busfree occurred during a non-pack
1855                  * connection so that we don't get false positives during
1856                  * future, packetized, connections.
1857                  */
1858                 ahd_outb(ahd, CLRSINT1, CLRBUSFREE);
1859                 if (packetized == 0
1860                  && (ahd->bugs & AHD_BUSFREEREV_BUG) != 0)
1861                         ahd_outb(ahd, SIMODE1,
1862                                  ahd_inb(ahd, SIMODE1) & ~ENBUSFREE);
1863
1864                 if (clear_fifo)
1865                         ahd_clear_fifo(ahd, mode);
1866
1867                 ahd_clear_msg_state(ahd);
1868                 ahd_outb(ahd, CLRINT, CLRSCSIINT);
1869                 if (restart) {
1870                         ahd_restart(ahd);
1871                 } else {
1872                         ahd_unpause(ahd);
1873                 }
1874         } else {
1875                 printf("%s: Missing case in ahd_handle_scsiint. status = %x\n",
1876                        ahd_name(ahd), status);
1877                 ahd_dump_card_state(ahd);
1878                 ahd_clear_intstat(ahd);
1879                 ahd_unpause(ahd);
1880         }
1881 }
1882
1883 static void
1884 ahd_handle_transmission_error(struct ahd_softc *ahd)
1885 {
1886         struct  scb *scb;
1887         u_int   scbid;
1888         u_int   lqistat1;
1889         u_int   lqistat2;
1890         u_int   msg_out;
1891         u_int   curphase;
1892         u_int   lastphase;
1893         u_int   perrdiag;
1894         u_int   cur_col;
1895         int     silent;
1896
1897         scb = NULL;
1898         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
1899         lqistat1 = ahd_inb(ahd, LQISTAT1) & ~(LQIPHASE_LQ|LQIPHASE_NLQ);
1900         lqistat2 = ahd_inb(ahd, LQISTAT2);
1901         if ((lqistat1 & (LQICRCI_NLQ|LQICRCI_LQ)) == 0
1902          && (ahd->bugs & AHD_NLQICRC_DELAYED_BUG) != 0) {
1903                 u_int lqistate;
1904
1905                 ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
1906                 lqistate = ahd_inb(ahd, LQISTATE);
1907                 if ((lqistate >= 0x1E && lqistate <= 0x24)
1908                  || (lqistate == 0x29)) {
1909 #ifdef AHD_DEBUG
1910                         if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) {
1911                                 printf("%s: NLQCRC found via LQISTATE\n",
1912                                        ahd_name(ahd));
1913                         }
1914 #endif
1915                         lqistat1 |= LQICRCI_NLQ;
1916                 }
1917                 ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
1918         }
1919
1920         ahd_outb(ahd, CLRLQIINT1, lqistat1);
1921         lastphase = ahd_inb(ahd, LASTPHASE);
1922         curphase = ahd_inb(ahd, SCSISIGI) & PHASE_MASK;
1923         perrdiag = ahd_inb(ahd, PERRDIAG);
1924         msg_out = MSG_INITIATOR_DET_ERR;
1925         ahd_outb(ahd, CLRSINT1, CLRSCSIPERR);
1926         
1927         /*
1928          * Try to find the SCB associated with this error.
1929          */
1930         silent = FALSE;
1931         if (lqistat1 == 0
1932          || (lqistat1 & LQICRCI_NLQ) != 0) {
1933                 if ((lqistat1 & (LQICRCI_NLQ|LQIOVERI_NLQ)) != 0)
1934                         ahd_set_active_fifo(ahd);
1935                 scbid = ahd_get_scbptr(ahd);
1936                 scb = ahd_lookup_scb(ahd, scbid);
1937                 if (scb != NULL && SCB_IS_SILENT(scb))
1938                         silent = TRUE;
1939         }
1940
1941         cur_col = 0;
1942         if (silent == FALSE) {
1943                 printf("%s: Transmission error detected\n", ahd_name(ahd));
1944                 ahd_lqistat1_print(lqistat1, &cur_col, 50);
1945                 ahd_lastphase_print(lastphase, &cur_col, 50);
1946                 ahd_scsisigi_print(curphase, &cur_col, 50);
1947                 ahd_perrdiag_print(perrdiag, &cur_col, 50);
1948                 printf("\n");
1949                 ahd_dump_card_state(ahd);
1950         }
1951
1952         if ((lqistat1 & (LQIOVERI_LQ|LQIOVERI_NLQ)) != 0) {
1953                 if (silent == FALSE) {
1954                         printf("%s: Gross protocol error during incoming "
1955                                "packet.  lqistat1 == 0x%x.  Resetting bus.\n",
1956                                ahd_name(ahd), lqistat1);
1957                 }
1958                 ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
1959                 return;
1960         } else if ((lqistat1 & LQICRCI_LQ) != 0) {
1961                 /*
1962                  * A CRC error has been detected on an incoming LQ.
1963                  * The bus is currently hung on the last ACK.
1964                  * Hit LQIRETRY to release the last ack, and
1965                  * wait for the sequencer to determine that ATNO
1966                  * is asserted while in message out to take us
1967                  * to our host message loop.  No NONPACKREQ or
1968                  * LQIPHASE type errors will occur in this
1969                  * scenario.  After this first LQIRETRY, the LQI
1970                  * manager will be in ISELO where it will
1971                  * happily sit until another packet phase begins.
1972                  * Unexpected bus free detection is enabled
1973                  * through any phases that occur after we release
1974                  * this last ack until the LQI manager sees a
1975                  * packet phase.  This implies we may have to
1976                  * ignore a perfectly valid "unexected busfree"
1977                  * after our "initiator detected error" message is
1978                  * sent.  A busfree is the expected response after
1979                  * we tell the target that it's L_Q was corrupted.
1980                  * (SPI4R09 10.7.3.3.3)
1981                  */
1982                 ahd_outb(ahd, LQCTL2, LQIRETRY);
1983                 printf("LQIRetry for LQICRCI_LQ to release ACK\n");
1984         } else if ((lqistat1 & LQICRCI_NLQ) != 0) {
1985                 /*
1986                  * We detected a CRC error in a NON-LQ packet.
1987                  * The hardware has varying behavior in this situation
1988                  * depending on whether this packet was part of a
1989                  * stream or not.
1990                  *
1991                  * PKT by PKT mode:
1992                  * The hardware has already acked the complete packet.
1993                  * If the target honors our outstanding ATN condition,
1994                  * we should be (or soon will be) in MSGOUT phase.
1995                  * This will trigger the LQIPHASE_LQ status bit as the
1996                  * hardware was expecting another LQ.  Unexpected
1997                  * busfree detection is enabled.  Once LQIPHASE_LQ is
1998                  * true (first entry into host message loop is much
1999                  * the same), we must clear LQIPHASE_LQ and hit
2000                  * LQIRETRY so the hardware is ready to handle
2001                  * a future LQ.  NONPACKREQ will not be asserted again
2002                  * once we hit LQIRETRY until another packet is
2003                  * processed.  The target may either go busfree
2004                  * or start another packet in response to our message.
2005                  *
2006                  * Read Streaming P0 asserted:
2007                  * If we raise ATN and the target completes the entire
2008                  * stream (P0 asserted during the last packet), the
2009                  * hardware will ack all data and return to the ISTART
2010                  * state.  When the target reponds to our ATN condition,
2011                  * LQIPHASE_LQ will be asserted.  We should respond to
2012                  * this with an LQIRETRY to prepare for any future
2013                  * packets.  NONPACKREQ will not be asserted again
2014                  * once we hit LQIRETRY until another packet is
2015                  * processed.  The target may either go busfree or
2016                  * start another packet in response to our message.
2017                  * Busfree detection is enabled.
2018                  *
2019                  * Read Streaming P0 not asserted:
2020                  * If we raise ATN and the target transitions to
2021                  * MSGOUT in or after a packet where P0 is not
2022                  * asserted, the hardware will assert LQIPHASE_NLQ.
2023                  * We should respond to the LQIPHASE_NLQ with an
2024                  * LQIRETRY.  Should the target stay in a non-pkt
2025                  * phase after we send our message, the hardware
2026                  * will assert LQIPHASE_LQ.  Recovery is then just as
2027                  * listed above for the read streaming with P0 asserted.
2028                  * Busfree detection is enabled.
2029                  */
2030                 if (silent == FALSE)
2031                         printf("LQICRC_NLQ\n");
2032                 if (scb == NULL) {
2033                         printf("%s: No SCB valid for LQICRC_NLQ.  "
2034                                "Resetting bus\n", ahd_name(ahd));
2035                         ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
2036                         return;
2037                 }
2038         } else if ((lqistat1 & LQIBADLQI) != 0) {
2039                 printf("Need to handle BADLQI!\n");
2040                 ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
2041                 return;
2042         } else if ((perrdiag & (PARITYERR|PREVPHASE)) == PARITYERR) {
2043                 if ((curphase & ~P_DATAIN_DT) != 0) {
2044                         /* Ack the byte.  So we can continue. */
2045                         if (silent == FALSE)
2046                                 printf("Acking %s to clear perror\n",
2047                                     ahd_lookup_phase_entry(curphase)->phasemsg);
2048                         ahd_inb(ahd, SCSIDAT);
2049                 }
2050         
2051                 if (curphase == P_MESGIN)
2052                         msg_out = MSG_PARITY_ERROR;
2053         }
2054
2055         /*
2056          * We've set the hardware to assert ATN if we 
2057          * get a parity error on "in" phases, so all we
2058          * need to do is stuff the message buffer with
2059          * the appropriate message.  "In" phases have set
2060          * mesg_out to something other than MSG_NOP.
2061          */
2062         ahd->send_msg_perror = msg_out;
2063         if (scb != NULL && msg_out == MSG_INITIATOR_DET_ERR)
2064                 scb->flags |= SCB_TRANSMISSION_ERROR;
2065         ahd_outb(ahd, MSG_OUT, HOST_MSG);
2066         ahd_outb(ahd, CLRINT, CLRSCSIINT);
2067         ahd_unpause(ahd);
2068 }
2069
2070 static void
2071 ahd_handle_lqiphase_error(struct ahd_softc *ahd, u_int lqistat1)
2072 {
2073         /*
2074          * Clear the sources of the interrupts.
2075          */
2076         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
2077         ahd_outb(ahd, CLRLQIINT1, lqistat1);
2078
2079         /*
2080          * If the "illegal" phase changes were in response
2081          * to our ATN to flag a CRC error, AND we ended up
2082          * on packet boundaries, clear the error, restart the
2083          * LQI manager as appropriate, and go on our merry
2084          * way toward sending the message.  Otherwise, reset
2085          * the bus to clear the error.
2086          */
2087         ahd_set_active_fifo(ahd);
2088         if ((ahd_inb(ahd, SCSISIGO) & ATNO) != 0
2089          && (ahd_inb(ahd, MDFFSTAT) & DLZERO) != 0) {
2090                 if ((lqistat1 & LQIPHASE_LQ) != 0) {
2091                         printf("LQIRETRY for LQIPHASE_LQ\n");
2092                         ahd_outb(ahd, LQCTL2, LQIRETRY);
2093                 } else if ((lqistat1 & LQIPHASE_NLQ) != 0) {
2094                         printf("LQIRETRY for LQIPHASE_NLQ\n");
2095                         ahd_outb(ahd, LQCTL2, LQIRETRY);
2096                 } else
2097                         panic("ahd_handle_lqiphase_error: No phase errors\n");
2098                 ahd_dump_card_state(ahd);
2099                 ahd_outb(ahd, CLRINT, CLRSCSIINT);
2100                 ahd_unpause(ahd);
2101         } else {
2102                 printf("Reseting Channel for LQI Phase error\n");
2103                 ahd_dump_card_state(ahd);
2104                 ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
2105         }
2106 }
2107
2108 /*
2109  * Packetized unexpected or expected busfree.
2110  * Entered in mode based on busfreetime.
2111  */
2112 static int
2113 ahd_handle_pkt_busfree(struct ahd_softc *ahd, u_int busfreetime)
2114 {
2115         u_int lqostat1;
2116
2117         AHD_ASSERT_MODES(ahd, ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK),
2118                          ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK));
2119         lqostat1 = ahd_inb(ahd, LQOSTAT1);
2120         if ((lqostat1 & LQOBUSFREE) != 0) {
2121                 struct scb *scb;
2122                 u_int scbid;
2123                 u_int saved_scbptr;
2124                 u_int waiting_h;
2125                 u_int waiting_t;
2126                 u_int next;
2127
2128                 /*
2129                  * The LQO manager detected an unexpected busfree
2130                  * either:
2131                  *
2132                  * 1) During an outgoing LQ.
2133                  * 2) After an outgoing LQ but before the first
2134                  *    REQ of the command packet.
2135                  * 3) During an outgoing command packet.
2136                  *
2137                  * In all cases, CURRSCB is pointing to the
2138                  * SCB that encountered the failure.  Clean
2139                  * up the queue, clear SELDO and LQOBUSFREE,
2140                  * and allow the sequencer to restart the select
2141                  * out at its lesure.
2142                  */
2143                 ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
2144                 scbid = ahd_inw(ahd, CURRSCB);
2145                 scb = ahd_lookup_scb(ahd, scbid);
2146                 if (scb == NULL)
2147                        panic("SCB not valid during LQOBUSFREE");
2148                 /*
2149                  * Clear the status.
2150                  */
2151                 ahd_outb(ahd, CLRLQOINT1, CLRLQOBUSFREE);
2152                 if ((ahd->bugs & AHD_CLRLQO_AUTOCLR_BUG) != 0)
2153                         ahd_outb(ahd, CLRLQOINT1, 0);
2154                 ahd_outb(ahd, SCSISEQ0, ahd_inb(ahd, SCSISEQ0) & ~ENSELO);
2155                 ahd_flush_device_writes(ahd);
2156                 ahd_outb(ahd, CLRSINT0, CLRSELDO);
2157
2158                 /*
2159                  * Return the LQO manager to its idle loop.  It will
2160                  * not do this automatically if the busfree occurs
2161                  * after the first REQ of either the LQ or command
2162                  * packet or between the LQ and command packet.
2163                  */
2164                 ahd_outb(ahd, LQCTL2, ahd_inb(ahd, LQCTL2) | LQOTOIDLE);
2165
2166                 /*
2167                  * Update the waiting for selection queue so
2168                  * we restart on the correct SCB.
2169                  */
2170                 waiting_h = ahd_inw(ahd, WAITING_TID_HEAD);
2171                 saved_scbptr = ahd_get_scbptr(ahd);
2172                 if (waiting_h != scbid) {
2173
2174                         ahd_outw(ahd, WAITING_TID_HEAD, scbid);
2175                         waiting_t = ahd_inw(ahd, WAITING_TID_TAIL);
2176                         if (waiting_t == waiting_h) {
2177                                 ahd_outw(ahd, WAITING_TID_TAIL, scbid);
2178                                 next = SCB_LIST_NULL;
2179                         } else {
2180                                 ahd_set_scbptr(ahd, waiting_h);
2181                                 next = ahd_inw_scbram(ahd, SCB_NEXT2);
2182                         }
2183                         ahd_set_scbptr(ahd, scbid);
2184                         ahd_outw(ahd, SCB_NEXT2, next);
2185                 }
2186                 ahd_set_scbptr(ahd, saved_scbptr);
2187                 if (scb->crc_retry_count < AHD_MAX_LQ_CRC_ERRORS) {
2188                         if (SCB_IS_SILENT(scb) == FALSE) {
2189                                 ahd_print_path(ahd, scb);
2190                                 printf("Probable outgoing LQ CRC error.  "
2191                                        "Retrying command\n");
2192                         }
2193                         scb->crc_retry_count++;
2194                 } else {
2195                         ahd_set_transaction_status(scb, CAM_UNCOR_PARITY);
2196                         ahd_freeze_scb(scb);
2197                         ahd_freeze_devq(ahd, scb);
2198                 }
2199                 /* Return unpausing the sequencer. */
2200                 return (0);
2201         } else if ((ahd_inb(ahd, PERRDIAG) & PARITYERR) != 0) {
2202                 /*
2203                  * Ignore what are really parity errors that
2204                  * occur on the last REQ of a free running
2205                  * clock prior to going busfree.  Some drives
2206                  * do not properly active negate just before
2207                  * going busfree resulting in a parity glitch.
2208                  */
2209                 ahd_outb(ahd, CLRSINT1, CLRSCSIPERR|CLRBUSFREE);
2210 #ifdef AHD_DEBUG
2211                 if ((ahd_debug & AHD_SHOW_MASKED_ERRORS) != 0)
2212                         printf("%s: Parity on last REQ detected "
2213                                "during busfree phase.\n",
2214                                ahd_name(ahd));
2215 #endif
2216                 /* Return unpausing the sequencer. */
2217                 return (0);
2218         }
2219         if (ahd->src_mode != AHD_MODE_SCSI) {
2220                 u_int   scbid;
2221                 struct  scb *scb;
2222
2223                 scbid = ahd_get_scbptr(ahd);
2224                 scb = ahd_lookup_scb(ahd, scbid);
2225                 ahd_print_path(ahd, scb);
2226                 printf("Unexpected PKT busfree condition\n");
2227                 ahd_dump_card_state(ahd);
2228                 ahd_abort_scbs(ahd, SCB_GET_TARGET(ahd, scb), 'A',
2229                                SCB_GET_LUN(scb), SCB_GET_TAG(scb),
2230                                ROLE_INITIATOR, CAM_UNEXP_BUSFREE);
2231
2232                 /* Return restarting the sequencer. */
2233                 return (1);
2234         }
2235         printf("%s: Unexpected PKT busfree condition\n", ahd_name(ahd));
2236         ahd_dump_card_state(ahd);
2237         /* Restart the sequencer. */
2238         return (1);
2239 }
2240
2241 /*
2242  * Non-packetized unexpected or expected busfree.
2243  */
2244 static int
2245 ahd_handle_nonpkt_busfree(struct ahd_softc *ahd)
2246 {
2247         struct  ahd_devinfo devinfo;
2248         struct  scb *scb;
2249         u_int   lastphase;
2250         u_int   saved_scsiid;
2251         u_int   saved_lun;
2252         u_int   target;
2253         u_int   initiator_role_id;
2254         u_int   scbid;
2255         u_int   ppr_busfree;
2256         int     printerror;
2257
2258         /*
2259          * Look at what phase we were last in.  If its message out,
2260          * chances are pretty good that the busfree was in response
2261          * to one of our abort requests.
2262          */
2263         lastphase = ahd_inb(ahd, LASTPHASE);
2264         saved_scsiid = ahd_inb(ahd, SAVED_SCSIID);
2265         saved_lun = ahd_inb(ahd, SAVED_LUN);
2266         target = SCSIID_TARGET(ahd, saved_scsiid);
2267         initiator_role_id = SCSIID_OUR_ID(saved_scsiid);
2268         ahd_compile_devinfo(&devinfo, initiator_role_id,
2269                             target, saved_lun, 'A', ROLE_INITIATOR);
2270         printerror = 1;
2271
2272         scbid = ahd_get_scbptr(ahd);
2273         scb = ahd_lookup_scb(ahd, scbid);
2274         if (scb != NULL
2275          && (ahd_inb(ahd, SEQ_FLAGS) & NOT_IDENTIFIED) != 0)
2276                 scb = NULL;
2277
2278         ppr_busfree = (ahd->msg_flags & MSG_FLAG_EXPECT_PPR_BUSFREE) != 0;
2279         if (lastphase == P_MESGOUT) {
2280                 u_int tag;
2281
2282                 tag = SCB_LIST_NULL;
2283                 if (ahd_sent_msg(ahd, AHDMSG_1B, MSG_ABORT_TAG, TRUE)
2284                  || ahd_sent_msg(ahd, AHDMSG_1B, MSG_ABORT, TRUE)) {
2285                         int found;
2286                         int sent_msg;
2287
2288                         if (scb == NULL) {
2289                                 ahd_print_devinfo(ahd, &devinfo);
2290                                 printf("Abort for unidentified "
2291                                        "connection completed.\n");
2292                                 /* restart the sequencer. */
2293                                 return (1);
2294                         }
2295                         sent_msg = ahd->msgout_buf[ahd->msgout_index - 1];
2296                         ahd_print_path(ahd, scb);
2297                         printf("SCB %d - Abort%s Completed.\n",
2298                                SCB_GET_TAG(scb),
2299                                sent_msg == MSG_ABORT_TAG ? "" : " Tag");
2300
2301                         if (sent_msg == MSG_ABORT_TAG)
2302                                 tag = SCB_GET_TAG(scb);
2303
2304                         found = ahd_abort_scbs(ahd, target, 'A', saved_lun,
2305                                                tag, ROLE_INITIATOR,
2306                                                CAM_REQ_ABORTED);
2307                         printf("found == 0x%x\n", found);
2308                         printerror = 0;
2309                 } else if (ahd_sent_msg(ahd, AHDMSG_1B,
2310                                         MSG_BUS_DEV_RESET, TRUE)) {
2311 #ifdef __FreeBSD__
2312                         /*
2313                          * Don't mark the user's request for this BDR
2314                          * as completing with CAM_BDR_SENT.  CAM3
2315                          * specifies CAM_REQ_CMP.
2316                          */
2317                         if (scb != NULL
2318                          && scb->io_ctx->ccb_h.func_code== XPT_RESET_DEV
2319                          && ahd_match_scb(ahd, scb, target, 'A',
2320                                           CAM_LUN_WILDCARD, SCB_LIST_NULL,
2321                                           ROLE_INITIATOR))
2322                                 ahd_set_transaction_status(scb, CAM_REQ_CMP);
2323 #endif
2324                         ahd_handle_devreset(ahd, &devinfo, CAM_LUN_WILDCARD,
2325                                             CAM_BDR_SENT, "Bus Device Reset",
2326                                             /*verbose_level*/0);
2327                         printerror = 0;
2328                 } else if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_PPR, FALSE)
2329                         && ppr_busfree == 0) {
2330                         struct ahd_initiator_tinfo *tinfo;
2331                         struct ahd_tmode_tstate *tstate;
2332
2333                         /*
2334                          * PPR Rejected.
2335                          *
2336                          * If the previous negotiation was packetized,
2337                          * this could be because the device has been
2338                          * reset without our knowledge.  Force our
2339                          * current negotiation to async and retry the
2340                          * negotiation.  Otherwise retry the command
2341                          * with non-ppr negotiation.
2342                          */
2343 #ifdef AHD_DEBUG
2344                         if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
2345                                 printf("PPR negotiation rejected busfree.\n");
2346 #endif
2347                         tinfo = ahd_fetch_transinfo(ahd, devinfo.channel,
2348                                                     devinfo.our_scsiid,
2349                                                     devinfo.target, &tstate);
2350                         if ((tinfo->curr.ppr_options & MSG_EXT_PPR_IU_REQ)!=0) {
2351                                 ahd_set_width(ahd, &devinfo,
2352                                               MSG_EXT_WDTR_BUS_8_BIT,
2353                                               AHD_TRANS_CUR,
2354                                               /*paused*/TRUE);
2355                                 ahd_set_syncrate(ahd, &devinfo,
2356                                                 /*period*/0, /*offset*/0,
2357                                                 /*ppr_options*/0,
2358                                                 AHD_TRANS_CUR,
2359                                                 /*paused*/TRUE);
2360                                 /*
2361                                  * The expect PPR busfree handler below
2362                                  * will effect the retry and necessary
2363                                  * abort.
2364                                  */
2365                         } else {
2366                                 tinfo->curr.transport_version = 2;
2367                                 tinfo->goal.transport_version = 2;
2368                                 tinfo->goal.ppr_options = 0;
2369                                 /*
2370                                  * Remove any SCBs in the waiting for selection
2371                                  * queue that may also be for this target so
2372                                  * that command ordering is preserved.
2373                                  */
2374                                 ahd_freeze_devq(ahd, scb);
2375                                 ahd_qinfifo_requeue_tail(ahd, scb);
2376                                 printerror = 0;
2377                         }
2378                 } else if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_WDTR, FALSE)
2379                         && ppr_busfree == 0) {
2380                         /*
2381                          * Negotiation Rejected.  Go-narrow and
2382                          * retry command.
2383                          */
2384 #ifdef AHD_DEBUG
2385                         if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
2386                                 printf("WDTR negotiation rejected busfree.\n");
2387 #endif
2388                         ahd_set_width(ahd, &devinfo,
2389                                       MSG_EXT_WDTR_BUS_8_BIT,
2390                                       AHD_TRANS_CUR|AHD_TRANS_GOAL,
2391                                       /*paused*/TRUE);
2392                         /*
2393                          * Remove any SCBs in the waiting for selection
2394                          * queue that may also be for this target so that
2395                          * command ordering is preserved.
2396                          */
2397                         ahd_freeze_devq(ahd, scb);
2398                         ahd_qinfifo_requeue_tail(ahd, scb);
2399                         printerror = 0;
2400                 } else if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_SDTR, FALSE)
2401                         && ppr_busfree == 0) {
2402                         /*
2403                          * Negotiation Rejected.  Go-async and
2404                          * retry command.
2405                          */
2406 #ifdef AHD_DEBUG
2407                         if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
2408                                 printf("SDTR negotiation rejected busfree.\n");
2409 #endif
2410                         ahd_set_syncrate(ahd, &devinfo,
2411                                         /*period*/0, /*offset*/0,
2412                                         /*ppr_options*/0,
2413                                         AHD_TRANS_CUR|AHD_TRANS_GOAL,
2414                                         /*paused*/TRUE);
2415                         /*
2416                          * Remove any SCBs in the waiting for selection
2417                          * queue that may also be for this target so that
2418                          * command ordering is preserved.
2419                          */
2420                         ahd_freeze_devq(ahd, scb);
2421                         ahd_qinfifo_requeue_tail(ahd, scb);
2422                         printerror = 0;
2423                 } else if ((ahd->msg_flags & MSG_FLAG_EXPECT_IDE_BUSFREE) != 0
2424                         && ahd_sent_msg(ahd, AHDMSG_1B,
2425                                          MSG_INITIATOR_DET_ERR, TRUE)) {
2426
2427 #ifdef AHD_DEBUG
2428                         if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
2429                                 printf("Expected IDE Busfree\n");
2430 #endif
2431                         printerror = 0;
2432                 } else if ((ahd->msg_flags & MSG_FLAG_EXPECT_QASREJ_BUSFREE)
2433                         && ahd_sent_msg(ahd, AHDMSG_1B,
2434                                         MSG_MESSAGE_REJECT, TRUE)) {
2435
2436 #ifdef AHD_DEBUG
2437                         if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
2438                                 printf("Expected QAS Reject Busfree\n");
2439 #endif
2440                         printerror = 0;
2441                 }
2442         }
2443
2444         /*
2445          * The busfree required flag is honored at the end of
2446          * the message phases.  We check it last in case we
2447          * had to send some other message that caused a busfree.
2448          */
2449         if (printerror != 0
2450          && (lastphase == P_MESGIN || lastphase == P_MESGOUT)
2451          && ((ahd->msg_flags & MSG_FLAG_EXPECT_PPR_BUSFREE) != 0)) {
2452
2453                 ahd_freeze_devq(ahd, scb);
2454                 ahd_set_transaction_status(scb, CAM_REQUEUE_REQ);
2455                 ahd_freeze_scb(scb);
2456                 if ((ahd->msg_flags & MSG_FLAG_IU_REQ_CHANGED) != 0) {
2457                         ahd_abort_scbs(ahd, SCB_GET_TARGET(ahd, scb),
2458                                        SCB_GET_CHANNEL(ahd, scb),
2459                                        SCB_GET_LUN(scb), SCB_LIST_NULL,
2460                                        ROLE_INITIATOR, CAM_REQ_ABORTED);
2461                 } else {
2462 #ifdef AHD_DEBUG
2463                         if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
2464                                 printf("PPR Negotiation Busfree.\n");
2465 #endif
2466                         ahd_done(ahd, scb);
2467                 }
2468                 printerror = 0;
2469         }
2470         if (printerror != 0) {
2471                 int aborted;
2472
2473                 aborted = 0;
2474                 if (scb != NULL) {
2475                         u_int tag;
2476
2477                         if ((scb->hscb->control & TAG_ENB) != 0)
2478                                 tag = SCB_GET_TAG(scb);
2479                         else
2480                                 tag = SCB_LIST_NULL;
2481                         ahd_print_path(ahd, scb);
2482                         aborted = ahd_abort_scbs(ahd, target, 'A',
2483                                        SCB_GET_LUN(scb), tag,
2484                                        ROLE_INITIATOR,
2485                                        CAM_UNEXP_BUSFREE);
2486                 } else {
2487                         /*
2488                          * We had not fully identified this connection,
2489                          * so we cannot abort anything.
2490                          */
2491                         printf("%s: ", ahd_name(ahd));
2492                 }
2493                 printf("Unexpected busfree %s, %d SCBs aborted, "
2494                        "PRGMCNT == 0x%x\n",
2495                        ahd_lookup_phase_entry(lastphase)->phasemsg,
2496                        aborted,
2497                        ahd_inw(ahd, PRGMCNT));
2498                 ahd_dump_card_state(ahd);
2499                 if (lastphase != P_BUSFREE)
2500                         ahd_force_renegotiation(ahd, &devinfo);
2501         }
2502         /* Always restart the sequencer. */
2503         return (1);
2504 }
2505
2506 static void
2507 ahd_handle_proto_violation(struct ahd_softc *ahd)
2508 {
2509         struct  ahd_devinfo devinfo;
2510         struct  scb *scb;
2511         u_int   scbid;
2512         u_int   seq_flags;
2513         u_int   curphase;
2514         u_int   lastphase;
2515         int     found;
2516
2517         ahd_fetch_devinfo(ahd, &devinfo);
2518         scbid = ahd_get_scbptr(ahd);
2519         scb = ahd_lookup_scb(ahd, scbid);
2520         seq_flags = ahd_inb(ahd, SEQ_FLAGS);
2521         curphase = ahd_inb(ahd, SCSISIGI) & PHASE_MASK;
2522         lastphase = ahd_inb(ahd, LASTPHASE);
2523         if ((seq_flags & NOT_IDENTIFIED) != 0) {
2524
2525                 /*
2526                  * The reconnecting target either did not send an
2527                  * identify message, or did, but we didn't find an SCB
2528                  * to match.
2529                  */
2530                 ahd_print_devinfo(ahd, &devinfo);
2531                 printf("Target did not send an IDENTIFY message. "
2532                        "LASTPHASE = 0x%x.\n", lastphase);
2533                 scb = NULL;
2534         } else if (scb == NULL) {
2535                 /*
2536                  * We don't seem to have an SCB active for this
2537                  * transaction.  Print an error and reset the bus.
2538                  */
2539                 ahd_print_devinfo(ahd, &devinfo);
2540                 printf("No SCB found during protocol violation\n");
2541                 goto proto_violation_reset;
2542         } else {
2543                 ahd_set_transaction_status(scb, CAM_SEQUENCE_FAIL);
2544                 if ((seq_flags & NO_CDB_SENT) != 0) {
2545                         ahd_print_path(ahd, scb);
2546                         printf("No or incomplete CDB sent to device.\n");
2547                 } else if ((ahd_inb_scbram(ahd, SCB_CONTROL)
2548                           & STATUS_RCVD) == 0) {
2549                         /*
2550                          * The target never bothered to provide status to
2551                          * us prior to completing the command.  Since we don't
2552                          * know the disposition of this command, we must attempt
2553                          * to abort it.  Assert ATN and prepare to send an abort
2554                          * message.
2555                          */
2556                         ahd_print_path(ahd, scb);
2557                         printf("Completed command without status.\n");
2558                 } else {
2559                         ahd_print_path(ahd, scb);
2560                         printf("Unknown protocol violation.\n");
2561                         ahd_dump_card_state(ahd);
2562                 }
2563         }
2564         if ((lastphase & ~P_DATAIN_DT) == 0
2565          || lastphase == P_COMMAND) {
2566 proto_violation_reset:
2567                 /*
2568                  * Target either went directly to data
2569                  * phase or didn't respond to our ATN.
2570                  * The only safe thing to do is to blow
2571                  * it away with a bus reset.
2572                  */
2573                 found = ahd_reset_channel(ahd, 'A', TRUE);
2574                 printf("%s: Issued Channel %c Bus Reset. "
2575                        "%d SCBs aborted\n", ahd_name(ahd), 'A', found);
2576         } else {
2577                 /*
2578                  * Leave the selection hardware off in case
2579                  * this abort attempt will affect yet to
2580                  * be sent commands.
2581                  */
2582                 ahd_outb(ahd, SCSISEQ0,
2583                          ahd_inb(ahd, SCSISEQ0) & ~ENSELO);
2584                 ahd_assert_atn(ahd);
2585                 ahd_outb(ahd, MSG_OUT, HOST_MSG);
2586                 if (scb == NULL) {
2587                         ahd_print_devinfo(ahd, &devinfo);
2588                         ahd->msgout_buf[0] = MSG_ABORT_TASK;
2589                         ahd->msgout_len = 1;
2590                         ahd->msgout_index = 0;
2591                         ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
2592                 } else {
2593                         ahd_print_path(ahd, scb);
2594                         scb->flags |= SCB_ABORT;
2595                 }
2596                 printf("Protocol violation %s.  Attempting to abort.\n",
2597                        ahd_lookup_phase_entry(curphase)->phasemsg);
2598         }
2599 }
2600
2601 /*
2602  * Force renegotiation to occur the next time we initiate
2603  * a command to the current device.
2604  */
2605 static void
2606 ahd_force_renegotiation(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
2607 {
2608         struct  ahd_initiator_tinfo *targ_info;
2609         struct  ahd_tmode_tstate *tstate;
2610
2611 #ifdef AHD_DEBUG
2612         if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
2613                 ahd_print_devinfo(ahd, devinfo);
2614                 printf("Forcing renegotiation\n");
2615         }
2616 #endif
2617         targ_info = ahd_fetch_transinfo(ahd,
2618                                         devinfo->channel,
2619                                         devinfo->our_scsiid,
2620                                         devinfo->target,
2621                                         &tstate);
2622         ahd_update_neg_request(ahd, devinfo, tstate,
2623                                targ_info, AHD_NEG_IF_NON_ASYNC);
2624 }
2625
2626 #define AHD_MAX_STEPS 2000
2627 static void
2628 ahd_clear_critical_section(struct ahd_softc *ahd)
2629 {
2630         ahd_mode_state  saved_modes;
2631         int             stepping;
2632         int             steps;
2633         int             first_instr;
2634         u_int           simode0;
2635         u_int           simode1;
2636         u_int           simode3;
2637         u_int           lqimode0;
2638         u_int           lqimode1;
2639         u_int           lqomode0;
2640         u_int           lqomode1;
2641
2642         if (ahd->num_critical_sections == 0)
2643                 return;
2644
2645         stepping = FALSE;
2646         steps = 0;
2647         first_instr = 0;
2648         simode0 = 0;
2649         simode1 = 0;
2650         simode3 = 0;
2651         lqimode0 = 0;
2652         lqimode1 = 0;
2653         lqomode0 = 0;
2654         lqomode1 = 0;
2655         saved_modes = ahd_save_modes(ahd);
2656         for (;;) {
2657                 struct  cs *cs;
2658                 u_int   seqaddr;
2659                 u_int   i;
2660
2661                 ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
2662                 seqaddr = ahd_inw(ahd, CURADDR);
2663
2664                 cs = ahd->critical_sections;
2665                 for (i = 0; i < ahd->num_critical_sections; i++, cs++) {
2666                         
2667                         if (cs->begin < seqaddr && cs->end >= seqaddr)
2668                                 break;
2669                 }
2670
2671                 if (i == ahd->num_critical_sections)
2672                         break;
2673
2674                 if (steps > AHD_MAX_STEPS) {
2675                         printf("%s: Infinite loop in critical section\n"
2676                                "%s: First Instruction 0x%x now 0x%x\n",
2677                                ahd_name(ahd), ahd_name(ahd), first_instr,
2678                                seqaddr);
2679                         ahd_dump_card_state(ahd);
2680                         panic("critical section loop");
2681                 }
2682
2683                 steps++;
2684 #ifdef AHD_DEBUG
2685                 if ((ahd_debug & AHD_SHOW_MISC) != 0)
2686                         printf("%s: Single stepping at 0x%x\n", ahd_name(ahd),
2687                                seqaddr);
2688 #endif
2689                 if (stepping == FALSE) {
2690
2691                         first_instr = seqaddr;
2692                         ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
2693                         simode0 = ahd_inb(ahd, SIMODE0);
2694                         simode3 = ahd_inb(ahd, SIMODE3);
2695                         lqimode0 = ahd_inb(ahd, LQIMODE0);
2696                         lqimode1 = ahd_inb(ahd, LQIMODE1);
2697                         lqomode0 = ahd_inb(ahd, LQOMODE0);
2698                         lqomode1 = ahd_inb(ahd, LQOMODE1);
2699                         ahd_outb(ahd, SIMODE0, 0);
2700                         ahd_outb(ahd, SIMODE3, 0);
2701                         ahd_outb(ahd, LQIMODE0, 0);
2702                         ahd_outb(ahd, LQIMODE1, 0);
2703                         ahd_outb(ahd, LQOMODE0, 0);
2704                         ahd_outb(ahd, LQOMODE1, 0);
2705                         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
2706                         simode1 = ahd_inb(ahd, SIMODE1);
2707                         /*
2708                          * We don't clear ENBUSFREE.  Unfortunately
2709                          * we cannot re-enable busfree detection within
2710                          * the current connection, so we must leave it
2711                          * on while single stepping.
2712                          */
2713                         ahd_outb(ahd, SIMODE1, simode1 & ENBUSFREE);
2714                         ahd_outb(ahd, SEQCTL0, ahd_inb(ahd, SEQCTL0) | STEP);
2715                         stepping = TRUE;
2716                 }
2717                 ahd_outb(ahd, CLRSINT1, CLRBUSFREE);
2718                 ahd_outb(ahd, CLRINT, CLRSCSIINT);
2719                 ahd_set_modes(ahd, ahd->saved_src_mode, ahd->saved_dst_mode);
2720                 ahd_outb(ahd, HCNTRL, ahd->unpause);
2721                 while (!ahd_is_paused(ahd))
2722                         ahd_delay(200);
2723                 ahd_update_modes(ahd);
2724         }
2725         if (stepping) {
2726                 ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
2727                 ahd_outb(ahd, SIMODE0, simode0);
2728                 ahd_outb(ahd, SIMODE3, simode3);
2729                 ahd_outb(ahd, LQIMODE0, lqimode0);
2730                 ahd_outb(ahd, LQIMODE1, lqimode1);
2731                 ahd_outb(ahd, LQOMODE0, lqomode0);
2732                 ahd_outb(ahd, LQOMODE1, lqomode1);
2733                 ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
2734                 ahd_outb(ahd, SEQCTL0, ahd_inb(ahd, SEQCTL0) & ~STEP);
2735                 ahd_outb(ahd, SIMODE1, simode1);
2736                 /*
2737                  * SCSIINT seems to glitch occassionally when
2738                  * the interrupt masks are restored.  Clear SCSIINT
2739                  * one more time so that only persistent errors
2740                  * are seen as a real interrupt.
2741                  */
2742                 ahd_outb(ahd, CLRINT, CLRSCSIINT);
2743         }
2744         ahd_restore_modes(ahd, saved_modes);
2745 }
2746
2747 /*
2748  * Clear any pending interrupt status.
2749  */
2750 static void
2751 ahd_clear_intstat(struct ahd_softc *ahd)
2752 {
2753         AHD_ASSERT_MODES(ahd, ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK),
2754                          ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK));
2755         /* Clear any interrupt conditions this may have caused */
2756         ahd_outb(ahd, CLRLQIINT0, CLRLQIATNQAS|CLRLQICRCT1|CLRLQICRCT2
2757                                  |CLRLQIBADLQT|CLRLQIATNLQ|CLRLQIATNCMD);
2758         ahd_outb(ahd, CLRLQIINT1, CLRLQIPHASE_LQ|CLRLQIPHASE_NLQ|CLRLIQABORT
2759                                  |CLRLQICRCI_LQ|CLRLQICRCI_NLQ|CLRLQIBADLQI
2760                                  |CLRLQIOVERI_LQ|CLRLQIOVERI_NLQ|CLRNONPACKREQ);
2761         ahd_outb(ahd, CLRLQOINT0, CLRLQOTARGSCBPERR|CLRLQOSTOPT2|CLRLQOATNLQ
2762                                  |CLRLQOATNPKT|CLRLQOTCRC);
2763         ahd_outb(ahd, CLRLQOINT1, CLRLQOINITSCBPERR|CLRLQOSTOPI2|CLRLQOBADQAS
2764                                  |CLRLQOBUSFREE|CLRLQOPHACHGINPKT);
2765         if ((ahd->bugs & AHD_CLRLQO_AUTOCLR_BUG) != 0) {
2766                 ahd_outb(ahd, CLRLQOINT0, 0);
2767                 ahd_outb(ahd, CLRLQOINT1, 0);
2768         }
2769         ahd_outb(ahd, CLRSINT3, CLRNTRAMPERR|CLROSRAMPERR);
2770         ahd_outb(ahd, CLRSINT1, CLRSELTIMEO|CLRATNO|CLRSCSIRSTI
2771                                 |CLRBUSFREE|CLRSCSIPERR|CLRREQINIT);
2772         ahd_outb(ahd, CLRSINT0, CLRSELDO|CLRSELDI|CLRSELINGO
2773                                 |CLRIOERR|CLROVERRUN);
2774         ahd_outb(ahd, CLRINT, CLRSCSIINT);
2775 }
2776
2777 /**************************** Debugging Routines ******************************/
2778 #ifdef AHD_DEBUG
2779 uint32_t ahd_debug = AHD_DEBUG_OPTS;
2780 #endif
2781
2782 #if 0
2783 void
2784 ahd_print_scb(struct scb *scb)
2785 {
2786         struct hardware_scb *hscb;
2787         int i;
2788
2789         hscb = scb->hscb;
2790         printf("scb:%p control:0x%x scsiid:0x%x lun:%d cdb_len:%d\n",
2791                (void *)scb,
2792                hscb->control,
2793                hscb->scsiid,
2794                hscb->lun,
2795                hscb->cdb_len);
2796         printf("Shared Data: ");
2797         for (i = 0; i < sizeof(hscb->shared_data.idata.cdb); i++)
2798                 printf("%#02x", hscb->shared_data.idata.cdb[i]);
2799         printf("        dataptr:%#x%x datacnt:%#x sgptr:%#x tag:%#x\n",
2800                (uint32_t)((ahd_le64toh(hscb->dataptr) >> 32) & 0xFFFFFFFF),
2801                (uint32_t)(ahd_le64toh(hscb->dataptr) & 0xFFFFFFFF),
2802                ahd_le32toh(hscb->datacnt),
2803                ahd_le32toh(hscb->sgptr),
2804                SCB_GET_TAG(scb));
2805         ahd_dump_sglist(scb);
2806 }
2807 #endif  /*  0  */
2808
2809 /************************* Transfer Negotiation *******************************/
2810 /*
2811  * Allocate per target mode instance (ID we respond to as a target)
2812  * transfer negotiation data structures.
2813  */
2814 static struct ahd_tmode_tstate *
2815 ahd_alloc_tstate(struct ahd_softc *ahd, u_int scsi_id, char channel)
2816 {
2817         struct ahd_tmode_tstate *master_tstate;
2818         struct ahd_tmode_tstate *tstate;
2819         int i;
2820
2821         master_tstate = ahd->enabled_targets[ahd->our_id];
2822         if (ahd->enabled_targets[scsi_id] != NULL
2823          && ahd->enabled_targets[scsi_id] != master_tstate)
2824                 panic("%s: ahd_alloc_tstate - Target already allocated",
2825                       ahd_name(ahd));
2826         tstate = malloc(sizeof(*tstate), M_DEVBUF, M_NOWAIT);
2827         if (tstate == NULL)
2828                 return (NULL);
2829
2830         /*
2831          * If we have allocated a master tstate, copy user settings from
2832          * the master tstate (taken from SRAM or the EEPROM) for this
2833          * channel, but reset our current and goal settings to async/narrow
2834          * until an initiator talks to us.
2835          */
2836         if (master_tstate != NULL) {
2837                 memcpy(tstate, master_tstate, sizeof(*tstate));
2838                 memset(tstate->enabled_luns, 0, sizeof(tstate->enabled_luns));
2839                 for (i = 0; i < 16; i++) {
2840                         memset(&tstate->transinfo[i].curr, 0,
2841                               sizeof(tstate->transinfo[i].curr));
2842                         memset(&tstate->transinfo[i].goal, 0,
2843                               sizeof(tstate->transinfo[i].goal));
2844                 }
2845         } else
2846                 memset(tstate, 0, sizeof(*tstate));
2847         ahd->enabled_targets[scsi_id] = tstate;
2848         return (tstate);
2849 }
2850
2851 #ifdef AHD_TARGET_MODE
2852 /*
2853  * Free per target mode instance (ID we respond to as a target)
2854  * transfer negotiation data structures.
2855  */
2856 static void
2857 ahd_free_tstate(struct ahd_softc *ahd, u_int scsi_id, char channel, int force)
2858 {
2859         struct ahd_tmode_tstate *tstate;
2860
2861         /*
2862          * Don't clean up our "master" tstate.
2863          * It has our default user settings.
2864          */
2865         if (scsi_id == ahd->our_id
2866          && force == FALSE)
2867                 return;
2868
2869         tstate = ahd->enabled_targets[scsi_id];
2870         if (tstate != NULL)
2871                 free(tstate, M_DEVBUF);
2872         ahd->enabled_targets[scsi_id] = NULL;
2873 }
2874 #endif
2875
2876 /*
2877  * Called when we have an active connection to a target on the bus,
2878  * this function finds the nearest period to the input period limited
2879  * by the capabilities of the bus connectivity of and sync settings for
2880  * the target.
2881  */
2882 void
2883 ahd_devlimited_syncrate(struct ahd_softc *ahd,
2884                         struct ahd_initiator_tinfo *tinfo,
2885                         u_int *period, u_int *ppr_options, role_t role)
2886 {
2887         struct  ahd_transinfo *transinfo;
2888         u_int   maxsync;
2889
2890         if ((ahd_inb(ahd, SBLKCTL) & ENAB40) != 0
2891          && (ahd_inb(ahd, SSTAT2) & EXP_ACTIVE) == 0) {
2892                 maxsync = AHD_SYNCRATE_PACED;
2893         } else {
2894                 maxsync = AHD_SYNCRATE_ULTRA;
2895                 /* Can't do DT related options on an SE bus */
2896                 *ppr_options &= MSG_EXT_PPR_QAS_REQ;
2897         }
2898         /*
2899          * Never allow a value higher than our current goal
2900          * period otherwise we may allow a target initiated
2901          * negotiation to go above the limit as set by the
2902          * user.  In the case of an initiator initiated
2903          * sync negotiation, we limit based on the user
2904          * setting.  This allows the system to still accept
2905          * incoming negotiations even if target initiated
2906          * negotiation is not performed.
2907          */
2908         if (role == ROLE_TARGET)
2909                 transinfo = &tinfo->user;
2910         else 
2911                 transinfo = &tinfo->goal;
2912         *ppr_options &= (transinfo->ppr_options|MSG_EXT_PPR_PCOMP_EN);
2913         if (transinfo->width == MSG_EXT_WDTR_BUS_8_BIT) {
2914                 maxsync = max(maxsync, (u_int)AHD_SYNCRATE_ULTRA2);
2915                 *ppr_options &= ~MSG_EXT_PPR_DT_REQ;
2916         }
2917         if (transinfo->period == 0) {
2918                 *period = 0;
2919                 *ppr_options = 0;
2920         } else {
2921                 *period = max(*period, (u_int)transinfo->period);
2922                 ahd_find_syncrate(ahd, period, ppr_options, maxsync);
2923         }
2924 }
2925
2926 /*
2927  * Look up the valid period to SCSIRATE conversion in our table.
2928  * Return the period and offset that should be sent to the target
2929  * if this was the beginning of an SDTR.
2930  */
2931 void
2932 ahd_find_syncrate(struct ahd_softc *ahd, u_int *period,
2933                   u_int *ppr_options, u_int maxsync)
2934 {
2935         if (*period < maxsync)
2936                 *period = maxsync;
2937
2938         if ((*ppr_options & MSG_EXT_PPR_DT_REQ) != 0
2939          && *period > AHD_SYNCRATE_MIN_DT)
2940                 *ppr_options &= ~MSG_EXT_PPR_DT_REQ;
2941                 
2942         if (*period > AHD_SYNCRATE_MIN)
2943                 *period = 0;
2944
2945         /* Honor PPR option conformance rules. */
2946         if (*period > AHD_SYNCRATE_PACED)
2947                 *ppr_options &= ~MSG_EXT_PPR_RTI;
2948
2949         if ((*ppr_options & MSG_EXT_PPR_IU_REQ) == 0)
2950                 *ppr_options &= (MSG_EXT_PPR_DT_REQ|MSG_EXT_PPR_QAS_REQ);
2951
2952         if ((*ppr_options & MSG_EXT_PPR_DT_REQ) == 0)
2953                 *ppr_options &= MSG_EXT_PPR_QAS_REQ;
2954
2955         /* Skip all PACED only entries if IU is not available */
2956         if ((*ppr_options & MSG_EXT_PPR_IU_REQ) == 0
2957          && *period < AHD_SYNCRATE_DT)
2958                 *period = AHD_SYNCRATE_DT;
2959
2960         /* Skip all DT only entries if DT is not available */
2961         if ((*ppr_options & MSG_EXT_PPR_DT_REQ) == 0
2962          && *period < AHD_SYNCRATE_ULTRA2)
2963                 *period = AHD_SYNCRATE_ULTRA2;
2964 }
2965
2966 /*
2967  * Truncate the given synchronous offset to a value the
2968  * current adapter type and syncrate are capable of.
2969  */
2970 static void
2971 ahd_validate_offset(struct ahd_softc *ahd,
2972                     struct ahd_initiator_tinfo *tinfo,
2973                     u_int period, u_int *offset, int wide,
2974                     role_t role)
2975 {
2976         u_int maxoffset;
2977
2978         /* Limit offset to what we can do */
2979         if (period == 0)
2980                 maxoffset = 0;
2981         else if (period <= AHD_SYNCRATE_PACED) {
2982                 if ((ahd->bugs & AHD_PACED_NEGTABLE_BUG) != 0)
2983                         maxoffset = MAX_OFFSET_PACED_BUG;
2984                 else
2985                         maxoffset = MAX_OFFSET_PACED;
2986         } else
2987                 maxoffset = MAX_OFFSET_NON_PACED;
2988         *offset = min(*offset, maxoffset);
2989         if (tinfo != NULL) {
2990                 if (role == ROLE_TARGET)
2991                         *offset = min(*offset, (u_int)tinfo->user.offset);
2992                 else
2993                         *offset = min(*offset, (u_int)tinfo->goal.offset);
2994         }
2995 }
2996
2997 /*
2998  * Truncate the given transfer width parameter to a value the
2999  * current adapter type is capable of.
3000  */
3001 static void
3002 ahd_validate_width(struct ahd_softc *ahd, struct ahd_initiator_tinfo *tinfo,
3003                    u_int *bus_width, role_t role)
3004 {
3005         switch (*bus_width) {
3006         default:
3007                 if (ahd->features & AHD_WIDE) {
3008                         /* Respond Wide */
3009                         *bus_width = MSG_EXT_WDTR_BUS_16_BIT;
3010                         break;
3011                 }
3012                 /* FALLTHROUGH */
3013         case MSG_EXT_WDTR_BUS_8_BIT:
3014                 *bus_width = MSG_EXT_WDTR_BUS_8_BIT;
3015                 break;
3016         }
3017         if (tinfo != NULL) {
3018                 if (role == ROLE_TARGET)
3019                         *bus_width = min((u_int)tinfo->user.width, *bus_width);
3020                 else
3021                         *bus_width = min((u_int)tinfo->goal.width, *bus_width);
3022         }
3023 }
3024
3025 /*
3026  * Update the bitmask of targets for which the controller should
3027  * negotiate with at the next convenient oportunity.  This currently
3028  * means the next time we send the initial identify messages for
3029  * a new transaction.
3030  */
3031 int
3032 ahd_update_neg_request(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
3033                        struct ahd_tmode_tstate *tstate,
3034                        struct ahd_initiator_tinfo *tinfo, ahd_neg_type neg_type)
3035 {
3036         u_int auto_negotiate_orig;
3037
3038         auto_negotiate_orig = tstate->auto_negotiate;
3039         if (neg_type == AHD_NEG_ALWAYS) {
3040                 /*
3041                  * Force our "current" settings to be
3042                  * unknown so that unless a bus reset
3043                  * occurs the need to renegotiate is
3044                  * recorded persistently.
3045                  */
3046                 if ((ahd->features & AHD_WIDE) != 0)
3047                         tinfo->curr.width = AHD_WIDTH_UNKNOWN;
3048                 tinfo->curr.period = AHD_PERIOD_UNKNOWN;
3049                 tinfo->curr.offset = AHD_OFFSET_UNKNOWN;
3050         }
3051         if (tinfo->curr.period != tinfo->goal.period
3052          || tinfo->curr.width != tinfo->goal.width
3053          || tinfo->curr.offset != tinfo->goal.offset
3054          || tinfo->curr.ppr_options != tinfo->goal.ppr_options
3055          || (neg_type == AHD_NEG_IF_NON_ASYNC
3056           && (tinfo->goal.offset != 0
3057            || tinfo->goal.width != MSG_EXT_WDTR_BUS_8_BIT
3058            || tinfo->goal.ppr_options != 0)))
3059                 tstate->auto_negotiate |= devinfo->target_mask;
3060         else
3061                 tstate->auto_negotiate &= ~devinfo->target_mask;
3062
3063         return (auto_negotiate_orig != tstate->auto_negotiate);
3064 }
3065
3066 /*
3067  * Update the user/goal/curr tables of synchronous negotiation
3068  * parameters as well as, in the case of a current or active update,
3069  * any data structures on the host controller.  In the case of an
3070  * active update, the specified target is currently talking to us on
3071  * the bus, so the transfer parameter update must take effect
3072  * immediately.
3073  */
3074 void
3075 ahd_set_syncrate(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
3076                  u_int period, u_int offset, u_int ppr_options,
3077                  u_int type, int paused)
3078 {
3079         struct  ahd_initiator_tinfo *tinfo;
3080         struct  ahd_tmode_tstate *tstate;
3081         u_int   old_period;
3082         u_int   old_offset;
3083         u_int   old_ppr;
3084         int     active;
3085         int     update_needed;
3086
3087         active = (type & AHD_TRANS_ACTIVE) == AHD_TRANS_ACTIVE;
3088         update_needed = 0;
3089
3090         if (period == 0 || offset == 0) {
3091                 period = 0;
3092                 offset = 0;
3093         }
3094
3095         tinfo = ahd_fetch_transinfo(ahd, devinfo->channel, devinfo->our_scsiid,
3096                                     devinfo->target, &tstate);
3097
3098         if ((type & AHD_TRANS_USER) != 0) {
3099                 tinfo->user.period = period;
3100                 tinfo->user.offset = offset;
3101                 tinfo->user.ppr_options = ppr_options;
3102         }
3103
3104         if ((type & AHD_TRANS_GOAL) != 0) {
3105                 tinfo->goal.period = period;
3106                 tinfo->goal.offset = offset;
3107                 tinfo->goal.ppr_options = ppr_options;
3108         }
3109
3110         old_period = tinfo->curr.period;
3111         old_offset = tinfo->curr.offset;
3112         old_ppr    = tinfo->curr.ppr_options;
3113
3114         if ((type & AHD_TRANS_CUR) != 0
3115          && (old_period != period
3116           || old_offset != offset
3117           || old_ppr != ppr_options)) {
3118
3119                 update_needed++;
3120
3121                 tinfo->curr.period = period;
3122                 tinfo->curr.offset = offset;
3123                 tinfo->curr.ppr_options = ppr_options;
3124
3125                 ahd_send_async(ahd, devinfo->channel, devinfo->target,
3126                                CAM_LUN_WILDCARD, AC_TRANSFER_NEG);
3127                 if (bootverbose) {
3128                         if (offset != 0) {
3129                                 int options;
3130
3131                                 printf("%s: target %d synchronous with "
3132                                        "period = 0x%x, offset = 0x%x",
3133                                        ahd_name(ahd), devinfo->target,
3134                                        period, offset);
3135                                 options = 0;
3136                                 if ((ppr_options & MSG_EXT_PPR_RD_STRM) != 0) {
3137                                         printf("(RDSTRM");
3138                                         options++;
3139                                 }
3140                                 if ((ppr_options & MSG_EXT_PPR_DT_REQ) != 0) {
3141                                         printf("%s", options ? "|DT" : "(DT");
3142                                         options++;
3143                                 }
3144                                 if ((ppr_options & MSG_EXT_PPR_IU_REQ) != 0) {
3145                                         printf("%s", options ? "|IU" : "(IU");
3146                                         options++;
3147                                 }
3148                                 if ((ppr_options & MSG_EXT_PPR_RTI) != 0) {
3149                                         printf("%s", options ? "|RTI" : "(RTI");
3150                                         options++;
3151                                 }
3152                                 if ((ppr_options & MSG_EXT_PPR_QAS_REQ) != 0) {
3153                                         printf("%s", options ? "|QAS" : "(QAS");
3154                                         options++;
3155                                 }
3156                                 if (options != 0)
3157                                         printf(")\n");
3158                                 else
3159                                         printf("\n");
3160                         } else {
3161                                 printf("%s: target %d using "
3162                                        "asynchronous transfers%s\n",
3163                                        ahd_name(ahd), devinfo->target,
3164                                        (ppr_options & MSG_EXT_PPR_QAS_REQ) != 0
3165                                      ?  "(QAS)" : "");
3166                         }
3167                 }
3168         }
3169         /*
3170          * Always refresh the neg-table to handle the case of the
3171          * sequencer setting the ENATNO bit for a MK_MESSAGE request.
3172          * We will always renegotiate in that case if this is a
3173          * packetized request.  Also manage the busfree expected flag
3174          * from this common routine so that we catch changes due to
3175          * WDTR or SDTR messages.
3176          */
3177         if ((type & AHD_TRANS_CUR) != 0) {
3178                 if (!paused)
3179                         ahd_pause(ahd);
3180                 ahd_update_neg_table(ahd, devinfo, &tinfo->curr);
3181                 if (!paused)
3182                         ahd_unpause(ahd);
3183                 if (ahd->msg_type != MSG_TYPE_NONE) {
3184                         if ((old_ppr & MSG_EXT_PPR_IU_REQ)
3185                          != (ppr_options & MSG_EXT_PPR_IU_REQ)) {
3186 #ifdef AHD_DEBUG
3187                                 if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
3188                                         ahd_print_devinfo(ahd, devinfo);
3189                                         printf("Expecting IU Change busfree\n");
3190                                 }
3191 #endif
3192                                 ahd->msg_flags |= MSG_FLAG_EXPECT_PPR_BUSFREE
3193                                                |  MSG_FLAG_IU_REQ_CHANGED;
3194                         }
3195                         if ((old_ppr & MSG_EXT_PPR_IU_REQ) != 0) {
3196 #ifdef AHD_DEBUG
3197                                 if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
3198                                         printf("PPR with IU_REQ outstanding\n");
3199 #endif
3200                                 ahd->msg_flags |= MSG_FLAG_EXPECT_PPR_BUSFREE;
3201                         }
3202                 }
3203         }
3204
3205         update_needed += ahd_update_neg_request(ahd, devinfo, tstate,
3206                                                 tinfo, AHD_NEG_TO_GOAL);
3207
3208         if (update_needed && active)
3209                 ahd_update_pending_scbs(ahd);
3210 }
3211
3212 /*
3213  * Update the user/goal/curr tables of wide negotiation
3214  * parameters as well as, in the case of a current or active update,
3215  * any data structures on the host controller.  In the case of an
3216  * active update, the specified target is currently talking to us on
3217  * the bus, so the transfer parameter update must take effect
3218  * immediately.
3219  */
3220 void
3221 ahd_set_width(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
3222               u_int width, u_int type, int paused)
3223 {
3224         struct  ahd_initiator_tinfo *tinfo;
3225         struct  ahd_tmode_tstate *tstate;
3226         u_int   oldwidth;
3227         int     active;
3228         int     update_needed;
3229
3230         active = (type & AHD_TRANS_ACTIVE) == AHD_TRANS_ACTIVE;
3231         update_needed = 0;
3232         tinfo = ahd_fetch_transinfo(ahd, devinfo->channel, devinfo->our_scsiid,
3233                                     devinfo->target, &tstate);
3234
3235         if ((type & AHD_TRANS_USER) != 0)
3236                 tinfo->user.width = width;
3237
3238         if ((type & AHD_TRANS_GOAL) != 0)
3239                 tinfo->goal.width = width;
3240
3241         oldwidth = tinfo->curr.width;
3242         if ((type & AHD_TRANS_CUR) != 0 && oldwidth != width) {
3243
3244                 update_needed++;
3245
3246                 tinfo->curr.width = width;
3247                 ahd_send_async(ahd, devinfo->channel, devinfo->target,
3248                                CAM_LUN_WILDCARD, AC_TRANSFER_NEG);
3249                 if (bootverbose) {
3250                         printf("%s: target %d using %dbit transfers\n",
3251                                ahd_name(ahd), devinfo->target,
3252                                8 * (0x01 << width));
3253                 }
3254         }
3255
3256         if ((type & AHD_TRANS_CUR) != 0) {
3257                 if (!paused)
3258                         ahd_pause(ahd);
3259                 ahd_update_neg_table(ahd, devinfo, &tinfo->curr);
3260                 if (!paused)
3261                         ahd_unpause(ahd);
3262         }
3263
3264         update_needed += ahd_update_neg_request(ahd, devinfo, tstate,
3265                                                 tinfo, AHD_NEG_TO_GOAL);
3266         if (update_needed && active)
3267                 ahd_update_pending_scbs(ahd);
3268
3269 }
3270
3271 /*
3272  * Update the current state of tagged queuing for a given target.
3273  */
3274 static void
3275 ahd_set_tags(struct ahd_softc *ahd, struct scsi_cmnd *cmd,
3276              struct ahd_devinfo *devinfo, ahd_queue_alg alg)
3277 {
3278         struct scsi_device *sdev = cmd->device;
3279
3280         ahd_platform_set_tags(ahd, sdev, devinfo, alg);
3281         ahd_send_async(ahd, devinfo->channel, devinfo->target,
3282                        devinfo->lun, AC_TRANSFER_NEG);
3283 }
3284
3285 static void
3286 ahd_update_neg_table(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
3287                      struct ahd_transinfo *tinfo)
3288 {
3289         ahd_mode_state  saved_modes;
3290         u_int           period;
3291         u_int           ppr_opts;
3292         u_int           con_opts;
3293         u_int           offset;
3294         u_int           saved_negoaddr;
3295         uint8_t         iocell_opts[sizeof(ahd->iocell_opts)];
3296
3297         saved_modes = ahd_save_modes(ahd);
3298         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
3299
3300         saved_negoaddr = ahd_inb(ahd, NEGOADDR);
3301         ahd_outb(ahd, NEGOADDR, devinfo->target);
3302         period = tinfo->period;
3303         offset = tinfo->offset;
3304         memcpy(iocell_opts, ahd->iocell_opts, sizeof(ahd->iocell_opts)); 
3305         ppr_opts = tinfo->ppr_options & (MSG_EXT_PPR_QAS_REQ|MSG_EXT_PPR_DT_REQ
3306                                         |MSG_EXT_PPR_IU_REQ|MSG_EXT_PPR_RTI);
3307         con_opts = 0;
3308         if (period == 0)
3309                 period = AHD_SYNCRATE_ASYNC;
3310         if (period == AHD_SYNCRATE_160) {
3311
3312                 if ((ahd->bugs & AHD_PACED_NEGTABLE_BUG) != 0) {
3313                         /*
3314                          * When the SPI4 spec was finalized, PACE transfers
3315                          * was not made a configurable option in the PPR
3316                          * message.  Instead it is assumed to be enabled for
3317                          * any syncrate faster than 80MHz.  Nevertheless,
3318                          * Harpoon2A4 allows this to be configurable.
3319                          *
3320                          * Harpoon2A4 also assumes at most 2 data bytes per
3321                          * negotiated REQ/ACK offset.  Paced transfers take
3322                          * 4, so we must adjust our offset.
3323                          */
3324                         ppr_opts |= PPROPT_PACE;
3325                         offset *= 2;
3326
3327                         /*
3328                          * Harpoon2A assumed that there would be a
3329                          * fallback rate between 160MHz and 80Mhz,
3330                          * so 7 is used as the period factor rather
3331                          * than 8 for 160MHz.
3332                          */
3333                         period = AHD_SYNCRATE_REVA_160;
3334                 }
3335                 if ((tinfo->ppr_options & MSG_EXT_PPR_PCOMP_EN) == 0)
3336                         iocell_opts[AHD_PRECOMP_SLEW_INDEX] &=
3337                             ~AHD_PRECOMP_MASK;
3338         } else {
3339                 /*
3340                  * Precomp should be disabled for non-paced transfers.
3341                  */
3342                 iocell_opts[AHD_PRECOMP_SLEW_INDEX] &= ~AHD_PRECOMP_MASK;
3343
3344                 if ((ahd->features & AHD_NEW_IOCELL_OPTS) != 0
3345                  && (ppr_opts & MSG_EXT_PPR_DT_REQ) != 0
3346                  && (ppr_opts & MSG_EXT_PPR_IU_REQ) == 0) {
3347                         /*
3348                          * Slow down our CRC interval to be
3349                          * compatible with non-packetized
3350                          * U160 devices that can't handle a
3351                          * CRC at full speed.
3352                          */
3353                         con_opts |= ENSLOWCRC;
3354                 }
3355
3356                 if ((ahd->bugs & AHD_PACED_NEGTABLE_BUG) != 0) {
3357                         /*
3358                          * On H2A4, revert to a slower slewrate
3359                          * on non-paced transfers.
3360                          */
3361                         iocell_opts[AHD_PRECOMP_SLEW_INDEX] &=
3362                             ~AHD_SLEWRATE_MASK;
3363                 }
3364         }
3365
3366         ahd_outb(ahd, ANNEXCOL, AHD_ANNEXCOL_PRECOMP_SLEW);
3367         ahd_outb(ahd, ANNEXDAT, iocell_opts[AHD_PRECOMP_SLEW_INDEX]);
3368         ahd_outb(ahd, ANNEXCOL, AHD_ANNEXCOL_AMPLITUDE);
3369         ahd_outb(ahd, ANNEXDAT, iocell_opts[AHD_AMPLITUDE_INDEX]);
3370
3371         ahd_outb(ahd, NEGPERIOD, period);
3372         ahd_outb(ahd, NEGPPROPTS, ppr_opts);
3373         ahd_outb(ahd, NEGOFFSET, offset);
3374
3375         if (tinfo->width == MSG_EXT_WDTR_BUS_16_BIT)
3376                 con_opts |= WIDEXFER;
3377
3378         /*
3379          * Slow down our CRC interval to be
3380          * compatible with packetized U320 devices
3381          * that can't handle a CRC at full speed
3382          */
3383         if (ahd->features & AHD_AIC79XXB_SLOWCRC) {
3384                 con_opts |= ENSLOWCRC;
3385         }
3386
3387         /*
3388          * During packetized transfers, the target will
3389          * give us the oportunity to send command packets
3390          * without us asserting attention.
3391          */
3392         if ((tinfo->ppr_options & MSG_EXT_PPR_IU_REQ) == 0)
3393                 con_opts |= ENAUTOATNO;
3394         ahd_outb(ahd, NEGCONOPTS, con_opts);
3395         ahd_outb(ahd, NEGOADDR, saved_negoaddr);
3396         ahd_restore_modes(ahd, saved_modes);
3397 }
3398
3399 /*
3400  * When the transfer settings for a connection change, setup for
3401  * negotiation in pending SCBs to effect the change as quickly as
3402  * possible.  We also cancel any negotiations that are scheduled
3403  * for inflight SCBs that have not been started yet.
3404  */
3405 static void
3406 ahd_update_pending_scbs(struct ahd_softc *ahd)
3407 {
3408         struct          scb *pending_scb;
3409         int             pending_scb_count;
3410         int             paused;
3411         u_int           saved_scbptr;
3412         ahd_mode_state  saved_modes;
3413
3414         /*
3415          * Traverse the pending SCB list and ensure that all of the
3416          * SCBs there have the proper settings.  We can only safely
3417          * clear the negotiation required flag (setting requires the
3418          * execution queue to be modified) and this is only possible
3419          * if we are not already attempting to select out for this
3420          * SCB.  For this reason, all callers only call this routine
3421          * if we are changing the negotiation settings for the currently
3422          * active transaction on the bus.
3423          */
3424         pending_scb_count = 0;
3425         LIST_FOREACH(pending_scb, &ahd->pending_scbs, pending_links) {
3426                 struct ahd_devinfo devinfo;
3427                 struct ahd_initiator_tinfo *tinfo;
3428                 struct ahd_tmode_tstate *tstate;
3429
3430                 ahd_scb_devinfo(ahd, &devinfo, pending_scb);
3431                 tinfo = ahd_fetch_transinfo(ahd, devinfo.channel,
3432                                             devinfo.our_scsiid,
3433                                             devinfo.target, &tstate);
3434                 if ((tstate->auto_negotiate & devinfo.target_mask) == 0
3435                  && (pending_scb->flags & SCB_AUTO_NEGOTIATE) != 0) {
3436                         pending_scb->flags &= ~SCB_AUTO_NEGOTIATE;
3437                         pending_scb->hscb->control &= ~MK_MESSAGE;
3438                 }
3439                 ahd_sync_scb(ahd, pending_scb,
3440                              BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
3441                 pending_scb_count++;
3442         }
3443
3444         if (pending_scb_count == 0)
3445                 return;
3446
3447         if (ahd_is_paused(ahd)) {
3448                 paused = 1;
3449         } else {
3450                 paused = 0;
3451                 ahd_pause(ahd);
3452         }
3453
3454         /*
3455          * Force the sequencer to reinitialize the selection for
3456          * the command at the head of the execution queue if it
3457          * has already been setup.  The negotiation changes may
3458          * effect whether we select-out with ATN.  It is only
3459          * safe to clear ENSELO when the bus is not free and no
3460          * selection is in progres or completed.
3461          */
3462         saved_modes = ahd_save_modes(ahd);
3463         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
3464         if ((ahd_inb(ahd, SCSISIGI) & BSYI) != 0
3465          && (ahd_inb(ahd, SSTAT0) & (SELDO|SELINGO)) == 0)
3466                 ahd_outb(ahd, SCSISEQ0, ahd_inb(ahd, SCSISEQ0) & ~ENSELO);
3467         saved_scbptr = ahd_get_scbptr(ahd);
3468         /* Ensure that the hscbs down on the card match the new information */
3469         LIST_FOREACH(pending_scb, &ahd->pending_scbs, pending_links) {
3470                 u_int   scb_tag;
3471                 u_int   control;
3472
3473                 scb_tag = SCB_GET_TAG(pending_scb);
3474                 ahd_set_scbptr(ahd, scb_tag);
3475                 control = ahd_inb_scbram(ahd, SCB_CONTROL);
3476                 control &= ~MK_MESSAGE;
3477                 control |= pending_scb->hscb->control & MK_MESSAGE;
3478                 ahd_outb(ahd, SCB_CONTROL, control);
3479         }
3480         ahd_set_scbptr(ahd, saved_scbptr);
3481         ahd_restore_modes(ahd, saved_modes);
3482
3483         if (paused == 0)
3484                 ahd_unpause(ahd);
3485 }
3486
3487 /**************************** Pathing Information *****************************/
3488 static void
3489 ahd_fetch_devinfo(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
3490 {
3491         ahd_mode_state  saved_modes;
3492         u_int           saved_scsiid;
3493         role_t          role;
3494         int             our_id;
3495
3496         saved_modes = ahd_save_modes(ahd);
3497         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
3498
3499         if (ahd_inb(ahd, SSTAT0) & TARGET)
3500                 role = ROLE_TARGET;
3501         else
3502                 role = ROLE_INITIATOR;
3503
3504         if (role == ROLE_TARGET
3505          && (ahd_inb(ahd, SEQ_FLAGS) & CMDPHASE_PENDING) != 0) {
3506                 /* We were selected, so pull our id from TARGIDIN */
3507                 our_id = ahd_inb(ahd, TARGIDIN) & OID;
3508         } else if (role == ROLE_TARGET)
3509                 our_id = ahd_inb(ahd, TOWNID);
3510         else
3511                 our_id = ahd_inb(ahd, IOWNID);
3512
3513         saved_scsiid = ahd_inb(ahd, SAVED_SCSIID);
3514         ahd_compile_devinfo(devinfo,
3515                             our_id,
3516                             SCSIID_TARGET(ahd, saved_scsiid),
3517                             ahd_inb(ahd, SAVED_LUN),
3518                             SCSIID_CHANNEL(ahd, saved_scsiid),
3519                             role);
3520         ahd_restore_modes(ahd, saved_modes);
3521 }
3522
3523 void
3524 ahd_print_devinfo(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
3525 {
3526         printf("%s:%c:%d:%d: ", ahd_name(ahd), 'A',
3527                devinfo->target, devinfo->lun);
3528 }
3529
3530 static struct ahd_phase_table_entry*
3531 ahd_lookup_phase_entry(int phase)
3532 {
3533         struct ahd_phase_table_entry *entry;
3534         struct ahd_phase_table_entry *last_entry;
3535
3536         /*
3537          * num_phases doesn't include the default entry which
3538          * will be returned if the phase doesn't match.
3539          */
3540         last_entry = &ahd_phase_table[num_phases];
3541         for (entry = ahd_phase_table; entry < last_entry; entry++) {
3542                 if (phase == entry->phase)
3543                         break;
3544         }
3545         return (entry);
3546 }
3547
3548 void
3549 ahd_compile_devinfo(struct ahd_devinfo *devinfo, u_int our_id, u_int target,
3550                     u_int lun, char channel, role_t role)
3551 {
3552         devinfo->our_scsiid = our_id;
3553         devinfo->target = target;
3554         devinfo->lun = lun;
3555         devinfo->target_offset = target;
3556         devinfo->channel = channel;
3557         devinfo->role = role;
3558         if (channel == 'B')
3559                 devinfo->target_offset += 8;
3560         devinfo->target_mask = (0x01 << devinfo->target_offset);
3561 }
3562
3563 static void
3564 ahd_scb_devinfo(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
3565                 struct scb *scb)
3566 {
3567         role_t  role;
3568         int     our_id;
3569
3570         our_id = SCSIID_OUR_ID(scb->hscb->scsiid);
3571         role = ROLE_INITIATOR;
3572         if ((scb->hscb->control & TARGET_SCB) != 0)
3573                 role = ROLE_TARGET;
3574         ahd_compile_devinfo(devinfo, our_id, SCB_GET_TARGET(ahd, scb),
3575                             SCB_GET_LUN(scb), SCB_GET_CHANNEL(ahd, scb), role);
3576 }
3577
3578
3579 /************************ Message Phase Processing ****************************/
3580 /*
3581  * When an initiator transaction with the MK_MESSAGE flag either reconnects
3582  * or enters the initial message out phase, we are interrupted.  Fill our
3583  * outgoing message buffer with the appropriate message and beging handing
3584  * the message phase(s) manually.
3585  */
3586 static void
3587 ahd_setup_initiator_msgout(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
3588                            struct scb *scb)
3589 {
3590         /*
3591          * To facilitate adding multiple messages together,
3592          * each routine should increment the index and len
3593          * variables instead of setting them explicitly.
3594          */
3595         ahd->msgout_index = 0;
3596         ahd->msgout_len = 0;
3597
3598         if (ahd_currently_packetized(ahd))
3599                 ahd->msg_flags |= MSG_FLAG_PACKETIZED;
3600
3601         if (ahd->send_msg_perror
3602          && ahd_inb(ahd, MSG_OUT) == HOST_MSG) {
3603                 ahd->msgout_buf[ahd->msgout_index++] = ahd->send_msg_perror;
3604                 ahd->msgout_len++;
3605                 ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
3606 #ifdef AHD_DEBUG
3607                 if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
3608                         printf("Setting up for Parity Error delivery\n");
3609 #endif
3610                 return;
3611         } else if (scb == NULL) {
3612                 printf("%s: WARNING. No pending message for "
3613                        "I_T msgin.  Issuing NO-OP\n", ahd_name(ahd));
3614                 ahd->msgout_buf[ahd->msgout_index++] = MSG_NOOP;
3615                 ahd->msgout_len++;
3616                 ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
3617                 return;
3618         }
3619
3620         if ((scb->flags & SCB_DEVICE_RESET) == 0
3621          && (scb->flags & SCB_PACKETIZED) == 0
3622          && ahd_inb(ahd, MSG_OUT) == MSG_IDENTIFYFLAG) {
3623                 u_int identify_msg;
3624
3625                 identify_msg = MSG_IDENTIFYFLAG | SCB_GET_LUN(scb);
3626                 if ((scb->hscb->control & DISCENB) != 0)
3627                         identify_msg |= MSG_IDENTIFY_DISCFLAG;
3628                 ahd->msgout_buf[ahd->msgout_index++] = identify_msg;
3629                 ahd->msgout_len++;
3630
3631                 if ((scb->hscb->control & TAG_ENB) != 0) {
3632                         ahd->msgout_buf[ahd->msgout_index++] =
3633                             scb->hscb->control & (TAG_ENB|SCB_TAG_TYPE);
3634                         ahd->msgout_buf[ahd->msgout_index++] = SCB_GET_TAG(scb);
3635                         ahd->msgout_len += 2;
3636                 }
3637         }
3638
3639         if (scb->flags & SCB_DEVICE_RESET) {
3640                 ahd->msgout_buf[ahd->msgout_index++] = MSG_BUS_DEV_RESET;
3641                 ahd->msgout_len++;
3642                 ahd_print_path(ahd, scb);
3643                 printf("Bus Device Reset Message Sent\n");
3644                 /*
3645                  * Clear our selection hardware in advance of
3646                  * the busfree.  We may have an entry in the waiting
3647                  * Q for this target, and we don't want to go about
3648                  * selecting while we handle the busfree and blow it
3649                  * away.
3650                  */
3651                 ahd_outb(ahd, SCSISEQ0, 0);
3652         } else if ((scb->flags & SCB_ABORT) != 0) {
3653
3654                 if ((scb->hscb->control & TAG_ENB) != 0) {
3655                         ahd->msgout_buf[ahd->msgout_index++] = MSG_ABORT_TAG;
3656                 } else {
3657                         ahd->msgout_buf[ahd->msgout_index++] = MSG_ABORT;
3658                 }
3659                 ahd->msgout_len++;
3660                 ahd_print_path(ahd, scb);
3661                 printf("Abort%s Message Sent\n",
3662                        (scb->hscb->control & TAG_ENB) != 0 ? " Tag" : "");
3663                 /*
3664                  * Clear our selection hardware in advance of
3665                  * the busfree.  We may have an entry in the waiting
3666                  * Q for this target, and we don't want to go about
3667                  * selecting while we handle the busfree and blow it
3668                  * away.
3669                  */
3670                 ahd_outb(ahd, SCSISEQ0, 0);
3671         } else if ((scb->flags & (SCB_AUTO_NEGOTIATE|SCB_NEGOTIATE)) != 0) {
3672                 ahd_build_transfer_msg(ahd, devinfo);
3673                 /*
3674                  * Clear our selection hardware in advance of potential
3675                  * PPR IU status change busfree.  We may have an entry in
3676                  * the waiting Q for this target, and we don't want to go
3677                  * about selecting while we handle the busfree and blow
3678                  * it away.
3679                  */
3680                 ahd_outb(ahd, SCSISEQ0, 0);
3681         } else {
3682                 printf("ahd_intr: AWAITING_MSG for an SCB that "
3683                        "does not have a waiting message\n");
3684                 printf("SCSIID = %x, target_mask = %x\n", scb->hscb->scsiid,
3685                        devinfo->target_mask);
3686                 panic("SCB = %d, SCB Control = %x:%x, MSG_OUT = %x "
3687                       "SCB flags = %x", SCB_GET_TAG(scb), scb->hscb->control,
3688                       ahd_inb_scbram(ahd, SCB_CONTROL), ahd_inb(ahd, MSG_OUT),
3689                       scb->flags);
3690         }
3691
3692         /*
3693          * Clear the MK_MESSAGE flag from the SCB so we aren't
3694          * asked to send this message again.
3695          */
3696         ahd_outb(ahd, SCB_CONTROL,
3697                  ahd_inb_scbram(ahd, SCB_CONTROL) & ~MK_MESSAGE);
3698         scb->hscb->control &= ~MK_MESSAGE;
3699         ahd->msgout_index = 0;
3700         ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
3701 }
3702
3703 /*
3704  * Build an appropriate transfer negotiation message for the
3705  * currently active target.
3706  */
3707 static void
3708 ahd_build_transfer_msg(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
3709 {
3710         /*
3711          * We need to initiate transfer negotiations.
3712          * If our current and goal settings are identical,
3713          * we want to renegotiate due to a check condition.
3714          */
3715         struct  ahd_initiator_tinfo *tinfo;
3716         struct  ahd_tmode_tstate *tstate;
3717         int     dowide;
3718         int     dosync;
3719         int     doppr;
3720         u_int   period;
3721         u_int   ppr_options;
3722         u_int   offset;
3723
3724         tinfo = ahd_fetch_transinfo(ahd, devinfo->channel, devinfo->our_scsiid,
3725                                     devinfo->target, &tstate);
3726         /*
3727          * Filter our period based on the current connection.
3728          * If we can't perform DT transfers on this segment (not in LVD
3729          * mode for instance), then our decision to issue a PPR message
3730          * may change.
3731          */
3732         period = tinfo->goal.period;
3733         offset = tinfo->goal.offset;
3734         ppr_options = tinfo->goal.ppr_options;
3735         /* Target initiated PPR is not allowed in the SCSI spec */
3736         if (devinfo->role == ROLE_TARGET)
3737                 ppr_options = 0;
3738         ahd_devlimited_syncrate(ahd, tinfo, &period,
3739                                 &ppr_options, devinfo->role);
3740         dowide = tinfo->curr.width != tinfo->goal.width;
3741         dosync = tinfo->curr.offset != offset || tinfo->curr.period != period;
3742         /*
3743          * Only use PPR if we have options that need it, even if the device
3744          * claims to support it.  There might be an expander in the way
3745          * that doesn't.
3746          */
3747         doppr = ppr_options != 0;
3748
3749         if (!dowide && !dosync && !doppr) {
3750                 dowide = tinfo->goal.width != MSG_EXT_WDTR_BUS_8_BIT;
3751                 dosync = tinfo->goal.offset != 0;
3752         }
3753
3754         if (!dowide && !dosync && !doppr) {
3755                 /*
3756                  * Force async with a WDTR message if we have a wide bus,
3757                  * or just issue an SDTR with a 0 offset.
3758                  */
3759                 if ((ahd->features & AHD_WIDE) != 0)
3760                         dowide = 1;
3761                 else
3762                         dosync = 1;
3763
3764                 if (bootverbose) {
3765                         ahd_print_devinfo(ahd, devinfo);
3766                         printf("Ensuring async\n");
3767                 }
3768         }
3769         /* Target initiated PPR is not allowed in the SCSI spec */
3770         if (devinfo->role == ROLE_TARGET)
3771                 doppr = 0;
3772
3773         /*
3774          * Both the PPR message and SDTR message require the
3775          * goal syncrate to be limited to what the target device
3776          * is capable of handling (based on whether an LVD->SE
3777          * expander is on the bus), so combine these two cases.
3778          * Regardless, guarantee that if we are using WDTR and SDTR
3779          * messages that WDTR comes first.
3780          */
3781         if (doppr || (dosync && !dowide)) {
3782
3783                 offset = tinfo->goal.offset;
3784                 ahd_validate_offset(ahd, tinfo, period, &offset,
3785                                     doppr ? tinfo->goal.width
3786                                           : tinfo->curr.width,
3787                                     devinfo->role);
3788                 if (doppr) {
3789                         ahd_construct_ppr(ahd, devinfo, period, offset,
3790                                           tinfo->goal.width, ppr_options);
3791                 } else {
3792                         ahd_construct_sdtr(ahd, devinfo, period, offset);
3793                 }
3794         } else {
3795                 ahd_construct_wdtr(ahd, devinfo, tinfo->goal.width);
3796         }
3797 }
3798
3799 /*
3800  * Build a synchronous negotiation message in our message
3801  * buffer based on the input parameters.
3802  */
3803 static void
3804 ahd_construct_sdtr(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
3805                    u_int period, u_int offset)
3806 {
3807         if (offset == 0)
3808                 period = AHD_ASYNC_XFER_PERIOD;
3809         ahd->msgout_index += spi_populate_sync_msg(
3810                         ahd->msgout_buf + ahd->msgout_index, period, offset);
3811         ahd->msgout_len += 5;
3812         if (bootverbose) {
3813                 printf("(%s:%c:%d:%d): Sending SDTR period %x, offset %x\n",
3814                        ahd_name(ahd), devinfo->channel, devinfo->target,
3815                        devinfo->lun, period, offset);
3816         }
3817 }
3818
3819 /*
3820  * Build a wide negotiateion message in our message
3821  * buffer based on the input parameters.
3822  */
3823 static void
3824 ahd_construct_wdtr(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
3825                    u_int bus_width)
3826 {
3827         ahd->msgout_index += spi_populate_width_msg(
3828                         ahd->msgout_buf + ahd->msgout_index, bus_width);
3829         ahd->msgout_len += 4;
3830         if (bootverbose) {
3831                 printf("(%s:%c:%d:%d): Sending WDTR %x\n",
3832                        ahd_name(ahd), devinfo->channel, devinfo->target,
3833                        devinfo->lun, bus_width);
3834         }
3835 }
3836
3837 /*
3838  * Build a parallel protocol request message in our message
3839  * buffer based on the input parameters.
3840  */
3841 static void
3842 ahd_construct_ppr(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
3843                   u_int period, u_int offset, u_int bus_width,
3844                   u_int ppr_options)
3845 {
3846         /*
3847          * Always request precompensation from
3848          * the other target if we are running
3849          * at paced syncrates.
3850          */
3851         if (period <= AHD_SYNCRATE_PACED)
3852                 ppr_options |= MSG_EXT_PPR_PCOMP_EN;
3853         if (offset == 0)
3854                 period = AHD_ASYNC_XFER_PERIOD;
3855         ahd->msgout_index += spi_populate_ppr_msg(
3856                         ahd->msgout_buf + ahd->msgout_index, period, offset,
3857                         bus_width, ppr_options);
3858         ahd->msgout_len += 8;
3859         if (bootverbose) {
3860                 printf("(%s:%c:%d:%d): Sending PPR bus_width %x, period %x, "
3861                        "offset %x, ppr_options %x\n", ahd_name(ahd),
3862                        devinfo->channel, devinfo->target, devinfo->lun,
3863                        bus_width, period, offset, ppr_options);
3864         }
3865 }
3866
3867 /*
3868  * Clear any active message state.
3869  */
3870 static void
3871 ahd_clear_msg_state(struct ahd_softc *ahd)
3872 {
3873         ahd_mode_state saved_modes;
3874
3875         saved_modes = ahd_save_modes(ahd);
3876         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
3877         ahd->send_msg_perror = 0;
3878         ahd->msg_flags = MSG_FLAG_NONE;
3879         ahd->msgout_len = 0;
3880         ahd->msgin_index = 0;
3881         ahd->msg_type = MSG_TYPE_NONE;
3882         if ((ahd_inb(ahd, SCSISIGO) & ATNO) != 0) {
3883                 /*
3884                  * The target didn't care to respond to our
3885                  * message request, so clear ATN.
3886                  */
3887                 ahd_outb(ahd, CLRSINT1, CLRATNO);
3888         }
3889         ahd_outb(ahd, MSG_OUT, MSG_NOOP);
3890         ahd_outb(ahd, SEQ_FLAGS2,
3891                  ahd_inb(ahd, SEQ_FLAGS2) & ~TARGET_MSG_PENDING);
3892         ahd_restore_modes(ahd, saved_modes);
3893 }
3894
3895 /*
3896  * Manual message loop handler.
3897  */
3898 static void
3899 ahd_handle_message_phase(struct ahd_softc *ahd)
3900
3901         struct  ahd_devinfo devinfo;
3902         u_int   bus_phase;
3903         int     end_session;
3904
3905         ahd_fetch_devinfo(ahd, &devinfo);
3906         end_session = FALSE;
3907         bus_phase = ahd_inb(ahd, LASTPHASE);
3908
3909         if ((ahd_inb(ahd, LQISTAT2) & LQIPHASE_OUTPKT) != 0) {
3910                 printf("LQIRETRY for LQIPHASE_OUTPKT\n");
3911                 ahd_outb(ahd, LQCTL2, LQIRETRY);
3912         }
3913 reswitch:
3914         switch (ahd->msg_type) {
3915         case MSG_TYPE_INITIATOR_MSGOUT:
3916         {
3917                 int lastbyte;
3918                 int phasemis;
3919                 int msgdone;
3920
3921                 if (ahd->msgout_len == 0 && ahd->send_msg_perror == 0)
3922                         panic("HOST_MSG_LOOP interrupt with no active message");
3923
3924 #ifdef AHD_DEBUG
3925                 if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
3926                         ahd_print_devinfo(ahd, &devinfo);
3927                         printf("INITIATOR_MSG_OUT");
3928                 }
3929 #endif
3930                 phasemis = bus_phase != P_MESGOUT;
3931                 if (phasemis) {
3932 #ifdef AHD_DEBUG
3933                         if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
3934                                 printf(" PHASEMIS %s\n",
3935                                        ahd_lookup_phase_entry(bus_phase)
3936                                                              ->phasemsg);
3937                         }
3938 #endif
3939                         if (bus_phase == P_MESGIN) {
3940                                 /*
3941                                  * Change gears and see if
3942                                  * this messages is of interest to
3943                                  * us or should be passed back to
3944                                  * the sequencer.
3945                                  */
3946                                 ahd_outb(ahd, CLRSINT1, CLRATNO);
3947                                 ahd->send_msg_perror = 0;
3948                                 ahd->msg_type = MSG_TYPE_INITIATOR_MSGIN;
3949                                 ahd->msgin_index = 0;
3950                                 goto reswitch;
3951                         }
3952                         end_session = TRUE;
3953                         break;
3954                 }
3955
3956                 if (ahd->send_msg_perror) {
3957                         ahd_outb(ahd, CLRSINT1, CLRATNO);
3958                         ahd_outb(ahd, CLRSINT1, CLRREQINIT);
3959 #ifdef AHD_DEBUG
3960                         if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
3961                                 printf(" byte 0x%x\n", ahd->send_msg_perror);
3962 #endif
3963                         /*
3964                          * If we are notifying the target of a CRC error
3965                          * during packetized operations, the target is
3966                          * within its rights to acknowledge our message
3967                          * with a busfree.
3968                          */
3969                         if ((ahd->msg_flags & MSG_FLAG_PACKETIZED) != 0
3970                          && ahd->send_msg_perror == MSG_INITIATOR_DET_ERR)
3971                                 ahd->msg_flags |= MSG_FLAG_EXPECT_IDE_BUSFREE;
3972
3973                         ahd_outb(ahd, RETURN_2, ahd->send_msg_perror);
3974                         ahd_outb(ahd, RETURN_1, CONT_MSG_LOOP_WRITE);
3975                         break;
3976                 }
3977
3978                 msgdone = ahd->msgout_index == ahd->msgout_len;
3979                 if (msgdone) {
3980                         /*
3981                          * The target has requested a retry.
3982                          * Re-assert ATN, reset our message index to
3983                          * 0, and try again.
3984                          */
3985                         ahd->msgout_index = 0;
3986                         ahd_assert_atn(ahd);
3987                 }
3988
3989                 lastbyte = ahd->msgout_index == (ahd->msgout_len - 1);
3990                 if (lastbyte) {
3991                         /* Last byte is signified by dropping ATN */
3992                         ahd_outb(ahd, CLRSINT1, CLRATNO);
3993                 }
3994
3995                 /*
3996                  * Clear our interrupt status and present
3997                  * the next byte on the bus.
3998                  */
3999                 ahd_outb(ahd, CLRSINT1, CLRREQINIT);
4000 #ifdef AHD_DEBUG
4001                 if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
4002                         printf(" byte 0x%x\n",
4003                                ahd->msgout_buf[ahd->msgout_index]);
4004 #endif
4005                 ahd_outb(ahd, RETURN_2, ahd->msgout_buf[ahd->msgout_index++]);
4006                 ahd_outb(ahd, RETURN_1, CONT_MSG_LOOP_WRITE);
4007                 break;
4008         }
4009         case MSG_TYPE_INITIATOR_MSGIN:
4010         {
4011                 int phasemis;
4012                 int message_done;
4013
4014 #ifdef AHD_DEBUG
4015                 if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
4016                         ahd_print_devinfo(ahd, &devinfo);
4017                         printf("INITIATOR_MSG_IN");
4018                 }
4019 #endif
4020                 phasemis = bus_phase != P_MESGIN;
4021                 if (phasemis) {
4022 #ifdef AHD_DEBUG
4023                         if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
4024                                 printf(" PHASEMIS %s\n",
4025                                        ahd_lookup_phase_entry(bus_phase)
4026                                                              ->phasemsg);
4027                         }
4028 #endif
4029                         ahd->msgin_index = 0;
4030                         if (bus_phase == P_MESGOUT
4031                          && (ahd->send_msg_perror != 0
4032                           || (ahd->msgout_len != 0
4033                            && ahd->msgout_index == 0))) {
4034                                 ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
4035                                 goto reswitch;
4036                         }
4037                         end_session = TRUE;
4038                         break;
4039                 }
4040
4041                 /* Pull the byte in without acking it */
4042                 ahd->msgin_buf[ahd->msgin_index] = ahd_inb(ahd, SCSIBUS);
4043 #ifdef AHD_DEBUG
4044                 if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
4045                         printf(" byte 0x%x\n",
4046                                ahd->msgin_buf[ahd->msgin_index]);
4047 #endif
4048
4049                 message_done = ahd_parse_msg(ahd, &devinfo);
4050
4051                 if (message_done) {
4052                         /*
4053                          * Clear our incoming message buffer in case there
4054                          * is another message following this one.
4055                          */
4056                         ahd->msgin_index = 0;
4057
4058                         /*
4059                          * If this message illicited a response,
4060                          * assert ATN so the target takes us to the
4061                          * message out phase.
4062                          */
4063                         if (ahd->msgout_len != 0) {
4064 #ifdef AHD_DEBUG
4065                                 if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
4066                                         ahd_print_devinfo(ahd, &devinfo);
4067                                         printf("Asserting ATN for response\n");
4068                                 }
4069 #endif
4070                                 ahd_assert_atn(ahd);
4071                         }
4072                 } else 
4073                         ahd->msgin_index++;
4074
4075                 if (message_done == MSGLOOP_TERMINATED) {
4076                         end_session = TRUE;
4077                 } else {
4078                         /* Ack the byte */
4079                         ahd_outb(ahd, CLRSINT1, CLRREQINIT);
4080                         ahd_outb(ahd, RETURN_1, CONT_MSG_LOOP_READ);
4081                 }
4082                 break;
4083         }
4084         case MSG_TYPE_TARGET_MSGIN:
4085         {
4086                 int msgdone;
4087                 int msgout_request;
4088
4089                 /*
4090                  * By default, the message loop will continue.
4091                  */
4092                 ahd_outb(ahd, RETURN_1, CONT_MSG_LOOP_TARG);
4093
4094                 if (ahd->msgout_len == 0)
4095                         panic("Target MSGIN with no active message");
4096
4097                 /*
4098                  * If we interrupted a mesgout session, the initiator
4099                  * will not know this until our first REQ.  So, we
4100                  * only honor mesgout requests after we've sent our
4101                  * first byte.
4102                  */
4103                 if ((ahd_inb(ahd, SCSISIGI) & ATNI) != 0
4104                  && ahd->msgout_index > 0)
4105                         msgout_request = TRUE;
4106                 else
4107                         msgout_request = FALSE;
4108
4109                 if (msgout_request) {
4110
4111                         /*
4112                          * Change gears and see if
4113                          * this messages is of interest to
4114                          * us or should be passed back to
4115                          * the sequencer.
4116                          */
4117                         ahd->msg_type = MSG_TYPE_TARGET_MSGOUT;
4118                         ahd_outb(ahd, SCSISIGO, P_MESGOUT | BSYO);
4119                         ahd->msgin_index = 0;
4120                         /* Dummy read to REQ for first byte */
4121                         ahd_inb(ahd, SCSIDAT);
4122                         ahd_outb(ahd, SXFRCTL0,
4123                                  ahd_inb(ahd, SXFRCTL0) | SPIOEN);
4124                         break;
4125                 }
4126
4127                 msgdone = ahd->msgout_index == ahd->msgout_len;
4128                 if (msgdone) {
4129                         ahd_outb(ahd, SXFRCTL0,
4130                                  ahd_inb(ahd, SXFRCTL0) & ~SPIOEN);
4131                         end_session = TRUE;
4132                         break;
4133                 }
4134
4135                 /*
4136                  * Present the next byte on the bus.
4137                  */
4138                 ahd_outb(ahd, SXFRCTL0, ahd_inb(ahd, SXFRCTL0) | SPIOEN);
4139                 ahd_outb(ahd, SCSIDAT, ahd->msgout_buf[ahd->msgout_index++]);
4140                 break;
4141         }
4142         case MSG_TYPE_TARGET_MSGOUT:
4143         {
4144                 int lastbyte;
4145                 int msgdone;
4146
4147                 /*
4148                  * By default, the message loop will continue.
4149                  */
4150                 ahd_outb(ahd, RETURN_1, CONT_MSG_LOOP_TARG);
4151
4152                 /*
4153                  * The initiator signals that this is
4154                  * the last byte by dropping ATN.
4155                  */
4156                 lastbyte = (ahd_inb(ahd, SCSISIGI) & ATNI) == 0;
4157
4158                 /*
4159                  * Read the latched byte, but turn off SPIOEN first
4160                  * so that we don't inadvertently cause a REQ for the
4161                  * next byte.
4162                  */
4163                 ahd_outb(ahd, SXFRCTL0, ahd_inb(ahd, SXFRCTL0) & ~SPIOEN);
4164                 ahd->msgin_buf[ahd->msgin_index] = ahd_inb(ahd, SCSIDAT);
4165                 msgdone = ahd_parse_msg(ahd, &devinfo);
4166                 if (msgdone == MSGLOOP_TERMINATED) {
4167                         /*
4168                          * The message is *really* done in that it caused
4169                          * us to go to bus free.  The sequencer has already
4170                          * been reset at this point, so pull the ejection
4171                          * handle.
4172                          */
4173                         return;
4174                 }
4175                 
4176                 ahd->msgin_index++;
4177
4178                 /*
4179                  * XXX Read spec about initiator dropping ATN too soon
4180                  *     and use msgdone to detect it.
4181                  */
4182                 if (msgdone == MSGLOOP_MSGCOMPLETE) {
4183                         ahd->msgin_index = 0;
4184
4185                         /*
4186                          * If this message illicited a response, transition
4187                          * to the Message in phase and send it.
4188                          */
4189                         if (ahd->msgout_len != 0) {
4190                                 ahd_outb(ahd, SCSISIGO, P_MESGIN | BSYO);
4191                                 ahd_outb(ahd, SXFRCTL0,
4192                                          ahd_inb(ahd, SXFRCTL0) | SPIOEN);
4193                                 ahd->msg_type = MSG_TYPE_TARGET_MSGIN;
4194                                 ahd->msgin_index = 0;
4195                                 break;
4196                         }
4197                 }
4198
4199                 if (lastbyte)
4200                         end_session = TRUE;
4201                 else {
4202                         /* Ask for the next byte. */
4203                         ahd_outb(ahd, SXFRCTL0,
4204                                  ahd_inb(ahd, SXFRCTL0) | SPIOEN);
4205                 }
4206
4207                 break;
4208         }
4209         default:
4210                 panic("Unknown REQINIT message type");
4211         }
4212
4213         if (end_session) {
4214                 if ((ahd->msg_flags & MSG_FLAG_PACKETIZED) != 0) {
4215                         printf("%s: Returning to Idle Loop\n",
4216                                ahd_name(ahd));
4217                         ahd_clear_msg_state(ahd);
4218
4219                         /*
4220                          * Perform the equivalent of a clear_target_state.
4221                          */
4222                         ahd_outb(ahd, LASTPHASE, P_BUSFREE);
4223                         ahd_outb(ahd, SEQ_FLAGS, NOT_IDENTIFIED|NO_CDB_SENT);
4224                         ahd_outb(ahd, SEQCTL0, FASTMODE|SEQRESET);
4225                 } else {
4226                         ahd_clear_msg_state(ahd);
4227                         ahd_outb(ahd, RETURN_1, EXIT_MSG_LOOP);
4228                 }
4229         }
4230 }
4231
4232 /*
4233  * See if we sent a particular extended message to the target.
4234  * If "full" is true, return true only if the target saw the full
4235  * message.  If "full" is false, return true if the target saw at
4236  * least the first byte of the message.
4237  */
4238 static int
4239 ahd_sent_msg(struct ahd_softc *ahd, ahd_msgtype type, u_int msgval, int full)
4240 {
4241         int found;
4242         u_int index;
4243
4244         found = FALSE;
4245         index = 0;
4246
4247         while (index < ahd->msgout_len) {
4248                 if (ahd->msgout_buf[index] == MSG_EXTENDED) {
4249                         u_int end_index;
4250
4251                         end_index = index + 1 + ahd->msgout_buf[index + 1];
4252                         if (ahd->msgout_buf[index+2] == msgval
4253                          && type == AHDMSG_EXT) {
4254
4255                                 if (full) {
4256                                         if (ahd->msgout_index > end_index)
4257                                                 found = TRUE;
4258                                 } else if (ahd->msgout_index > index)
4259                                         found = TRUE;
4260                         }
4261                         index = end_index;
4262                 } else if (ahd->msgout_buf[index] >= MSG_SIMPLE_TASK
4263                         && ahd->msgout_buf[index] <= MSG_IGN_WIDE_RESIDUE) {
4264
4265                         /* Skip tag type and tag id or residue param*/
4266                         index += 2;
4267                 } else {
4268                         /* Single byte message */
4269                         if (type == AHDMSG_1B
4270                          && ahd->msgout_index > index
4271                          && (ahd->msgout_buf[index] == msgval
4272                           || ((ahd->msgout_buf[index] & MSG_IDENTIFYFLAG) != 0
4273                            && msgval == MSG_IDENTIFYFLAG)))
4274                                 found = TRUE;
4275                         index++;
4276                 }
4277
4278                 if (found)
4279                         break;
4280         }
4281         return (found);
4282 }
4283
4284 /*
4285  * Wait for a complete incoming message, parse it, and respond accordingly.
4286  */
4287 static int
4288 ahd_parse_msg(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
4289 {
4290         struct  ahd_initiator_tinfo *tinfo;
4291         struct  ahd_tmode_tstate *tstate;
4292         int     reject;
4293         int     done;
4294         int     response;
4295
4296         done = MSGLOOP_IN_PROG;
4297         response = FALSE;
4298         reject = FALSE;
4299         tinfo = ahd_fetch_transinfo(ahd, devinfo->channel, devinfo->our_scsiid,
4300                                     devinfo->target, &tstate);
4301
4302         /*
4303          * Parse as much of the message as is available,
4304          * rejecting it if we don't support it.  When
4305          * the entire message is available and has been
4306          * handled, return MSGLOOP_MSGCOMPLETE, indicating
4307          * that we have parsed an entire message.
4308          *
4309          * In the case of extended messages, we accept the length
4310          * byte outright and perform more checking once we know the
4311          * extended message type.
4312          */
4313         switch (ahd->msgin_buf[0]) {
4314         case MSG_DISCONNECT:
4315         case MSG_SAVEDATAPOINTER:
4316         case MSG_CMDCOMPLETE:
4317         case MSG_RESTOREPOINTERS:
4318         case MSG_IGN_WIDE_RESIDUE:
4319                 /*
4320                  * End our message loop as these are messages
4321                  * the sequencer handles on its own.
4322                  */
4323                 done = MSGLOOP_TERMINATED;
4324                 break;
4325         case MSG_MESSAGE_REJECT:
4326                 response = ahd_handle_msg_reject(ahd, devinfo);
4327                 /* FALLTHROUGH */
4328         case MSG_NOOP:
4329                 done = MSGLOOP_MSGCOMPLETE;
4330                 break;
4331         case MSG_EXTENDED:
4332         {
4333                 /* Wait for enough of the message to begin validation */
4334                 if (ahd->msgin_index < 2)
4335                         break;
4336                 switch (ahd->msgin_buf[2]) {
4337                 case MSG_EXT_SDTR:
4338                 {
4339                         u_int    period;
4340                         u_int    ppr_options;
4341                         u_int    offset;
4342                         u_int    saved_offset;
4343                         
4344                         if (ahd->msgin_buf[1] != MSG_EXT_SDTR_LEN) {
4345                                 reject = TRUE;
4346                                 break;
4347                         }
4348
4349                         /*
4350                          * Wait until we have both args before validating
4351                          * and acting on this message.
4352                          *
4353                          * Add one to MSG_EXT_SDTR_LEN to account for
4354                          * the extended message preamble.
4355                          */
4356                         if (ahd->msgin_index < (MSG_EXT_SDTR_LEN + 1))
4357                                 break;
4358
4359                         period = ahd->msgin_buf[3];
4360                         ppr_options = 0;
4361                         saved_offset = offset = ahd->msgin_buf[4];
4362                         ahd_devlimited_syncrate(ahd, tinfo, &period,
4363                                                 &ppr_options, devinfo->role);
4364                         ahd_validate_offset(ahd, tinfo, period, &offset,
4365                                             tinfo->curr.width, devinfo->role);
4366                         if (bootverbose) {
4367                                 printf("(%s:%c:%d:%d): Received "
4368                                        "SDTR period %x, offset %x\n\t"
4369                                        "Filtered to period %x, offset %x\n",
4370                                        ahd_name(ahd), devinfo->channel,
4371                                        devinfo->target, devinfo->lun,
4372                                        ahd->msgin_buf[3], saved_offset,
4373                                        period, offset);
4374                         }
4375                         ahd_set_syncrate(ahd, devinfo, period,
4376                                          offset, ppr_options,
4377                                          AHD_TRANS_ACTIVE|AHD_TRANS_GOAL,
4378                                          /*paused*/TRUE);
4379
4380                         /*
4381                          * See if we initiated Sync Negotiation
4382                          * and didn't have to fall down to async
4383                          * transfers.
4384                          */
4385                         if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_SDTR, TRUE)) {
4386                                 /* We started it */
4387                                 if (saved_offset != offset) {
4388                                         /* Went too low - force async */
4389                                         reject = TRUE;
4390                                 }
4391                         } else {
4392                                 /*
4393                                  * Send our own SDTR in reply
4394                                  */
4395                                 if (bootverbose
4396                                  && devinfo->role == ROLE_INITIATOR) {
4397                                         printf("(%s:%c:%d:%d): Target "
4398                                                "Initiated SDTR\n",
4399                                                ahd_name(ahd), devinfo->channel,
4400                                                devinfo->target, devinfo->lun);
4401                                 }
4402                                 ahd->msgout_index = 0;
4403                                 ahd->msgout_len = 0;
4404                                 ahd_construct_sdtr(ahd, devinfo,
4405                                                    period, offset);
4406                                 ahd->msgout_index = 0;
4407                                 response = TRUE;
4408                         }
4409                         done = MSGLOOP_MSGCOMPLETE;
4410                         break;
4411                 }
4412                 case MSG_EXT_WDTR:
4413                 {
4414                         u_int bus_width;
4415                         u_int saved_width;
4416                         u_int sending_reply;
4417
4418                         sending_reply = FALSE;
4419                         if (ahd->msgin_buf[1] != MSG_EXT_WDTR_LEN) {
4420                                 reject = TRUE;
4421                                 break;
4422                         }
4423
4424                         /*
4425                          * Wait until we have our arg before validating
4426                          * and acting on this message.
4427                          *
4428                          * Add one to MSG_EXT_WDTR_LEN to account for
4429                          * the extended message preamble.
4430                          */
4431                         if (ahd->msgin_index < (MSG_EXT_WDTR_LEN + 1))
4432                                 break;
4433
4434                         bus_width = ahd->msgin_buf[3];
4435                         saved_width = bus_width;
4436                         ahd_validate_width(ahd, tinfo, &bus_width,
4437                                            devinfo->role);
4438                         if (bootverbose) {
4439                                 printf("(%s:%c:%d:%d): Received WDTR "
4440                                        "%x filtered to %x\n",
4441                                        ahd_name(ahd), devinfo->channel,
4442                                        devinfo->target, devinfo->lun,
4443                                        saved_width, bus_width);
4444                         }
4445
4446                         if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_WDTR, TRUE)) {
4447                                 /*
4448                                  * Don't send a WDTR back to the
4449                                  * target, since we asked first.
4450                                  * If the width went higher than our
4451                                  * request, reject it.
4452                                  */
4453                                 if (saved_width > bus_width) {
4454                                         reject = TRUE;
4455                                         printf("(%s:%c:%d:%d): requested %dBit "
4456                                                "transfers.  Rejecting...\n",
4457                                                ahd_name(ahd), devinfo->channel,
4458                                                devinfo->target, devinfo->lun,
4459                                                8 * (0x01 << bus_width));
4460                                         bus_width = 0;
4461                                 }
4462                         } else {
4463                                 /*
4464                                  * Send our own WDTR in reply
4465                                  */
4466                                 if (bootverbose
4467                                  && devinfo->role == ROLE_INITIATOR) {
4468                                         printf("(%s:%c:%d:%d): Target "
4469                                                "Initiated WDTR\n",
4470                                                ahd_name(ahd), devinfo->channel,
4471                                                devinfo->target, devinfo->lun);
4472                                 }
4473                                 ahd->msgout_index = 0;
4474                                 ahd->msgout_len = 0;
4475                                 ahd_construct_wdtr(ahd, devinfo, bus_width);
4476                                 ahd->msgout_index = 0;
4477                                 response = TRUE;
4478                                 sending_reply = TRUE;
4479                         }
4480                         /*
4481                          * After a wide message, we are async, but
4482                          * some devices don't seem to honor this portion
4483                          * of the spec.  Force a renegotiation of the
4484                          * sync component of our transfer agreement even
4485                          * if our goal is async.  By updating our width
4486                          * after forcing the negotiation, we avoid
4487                          * renegotiating for width.
4488                          */
4489                         ahd_update_neg_request(ahd, devinfo, tstate,
4490                                                tinfo, AHD_NEG_ALWAYS);
4491                         ahd_set_width(ahd, devinfo, bus_width,
4492                                       AHD_TRANS_ACTIVE|AHD_TRANS_GOAL,
4493                                       /*paused*/TRUE);
4494                         if (sending_reply == FALSE && reject == FALSE) {
4495
4496                                 /*
4497                                  * We will always have an SDTR to send.
4498                                  */
4499                                 ahd->msgout_index = 0;
4500                                 ahd->msgout_len = 0;
4501                                 ahd_build_transfer_msg(ahd, devinfo);
4502                                 ahd->msgout_index = 0;
4503                                 response = TRUE;
4504                         }
4505                         done = MSGLOOP_MSGCOMPLETE;
4506                         break;
4507                 }
4508                 case MSG_EXT_PPR:
4509                 {
4510                         u_int   period;
4511                         u_int   offset;
4512                         u_int   bus_width;
4513                         u_int   ppr_options;
4514                         u_int   saved_width;
4515                         u_int   saved_offset;
4516                         u_int   saved_ppr_options;
4517
4518                         if (ahd->msgin_buf[1] != MSG_EXT_PPR_LEN) {
4519                                 reject = TRUE;
4520                                 break;
4521                         }
4522
4523                         /*
4524                          * Wait until we have all args before validating
4525                          * and acting on this message.
4526                          *
4527                          * Add one to MSG_EXT_PPR_LEN to account for
4528                          * the extended message preamble.
4529                          */
4530                         if (ahd->msgin_index < (MSG_EXT_PPR_LEN + 1))
4531                                 break;
4532
4533                         period = ahd->msgin_buf[3];
4534                         offset = ahd->msgin_buf[5];
4535                         bus_width = ahd->msgin_buf[6];
4536                         saved_width = bus_width;
4537                         ppr_options = ahd->msgin_buf[7];
4538                         /*
4539                          * According to the spec, a DT only
4540                          * period factor with no DT option
4541                          * set implies async.
4542                          */
4543                         if ((ppr_options & MSG_EXT_PPR_DT_REQ) == 0
4544                          && period <= 9)
4545                                 offset = 0;
4546                         saved_ppr_options = ppr_options;
4547                         saved_offset = offset;
4548
4549                         /*
4550                          * Transfer options are only available if we
4551                          * are negotiating wide.
4552                          */
4553                         if (bus_width == 0)
4554                                 ppr_options &= MSG_EXT_PPR_QAS_REQ;
4555
4556                         ahd_validate_width(ahd, tinfo, &bus_width,
4557                                            devinfo->role);
4558                         ahd_devlimited_syncrate(ahd, tinfo, &period,
4559                                                 &ppr_options, devinfo->role);
4560                         ahd_validate_offset(ahd, tinfo, period, &offset,
4561                                             bus_width, devinfo->role);
4562
4563                         if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_PPR, TRUE)) {
4564                                 /*
4565                                  * If we are unable to do any of the
4566                                  * requested options (we went too low),
4567                                  * then we'll have to reject the message.
4568                                  */
4569                                 if (saved_width > bus_width
4570                                  || saved_offset != offset
4571                                  || saved_ppr_options != ppr_options) {
4572                                         reject = TRUE;
4573                                         period = 0;
4574                                         offset = 0;
4575                                         bus_width = 0;
4576                                         ppr_options = 0;
4577                                 }
4578                         } else {
4579                                 if (devinfo->role != ROLE_TARGET)
4580                                         printf("(%s:%c:%d:%d): Target "
4581                                                "Initiated PPR\n",
4582                                                ahd_name(ahd), devinfo->channel,
4583                                                devinfo->target, devinfo->lun);
4584                                 else
4585                                         printf("(%s:%c:%d:%d): Initiator "
4586                                                "Initiated PPR\n",
4587                                                ahd_name(ahd), devinfo->channel,
4588                                                devinfo->target, devinfo->lun);
4589                                 ahd->msgout_index = 0;
4590                                 ahd->msgout_len = 0;
4591                                 ahd_construct_ppr(ahd, devinfo, period, offset,
4592                                                   bus_width, ppr_options);
4593                                 ahd->msgout_index = 0;
4594                                 response = TRUE;
4595                         }
4596                         if (bootverbose) {
4597                                 printf("(%s:%c:%d:%d): Received PPR width %x, "
4598                                        "period %x, offset %x,options %x\n"
4599                                        "\tFiltered to width %x, period %x, "
4600                                        "offset %x, options %x\n",
4601                                        ahd_name(ahd), devinfo->channel,
4602                                        devinfo->target, devinfo->lun,
4603                                        saved_width, ahd->msgin_buf[3],
4604                                        saved_offset, saved_ppr_options,
4605                                        bus_width, period, offset, ppr_options);
4606                         }
4607                         ahd_set_width(ahd, devinfo, bus_width,
4608                                       AHD_TRANS_ACTIVE|AHD_TRANS_GOAL,
4609                                       /*paused*/TRUE);
4610                         ahd_set_syncrate(ahd, devinfo, period,
4611                                          offset, ppr_options,
4612                                          AHD_TRANS_ACTIVE|AHD_TRANS_GOAL,
4613                                          /*paused*/TRUE);
4614
4615                         done = MSGLOOP_MSGCOMPLETE;
4616                         break;
4617                 }
4618                 default:
4619                         /* Unknown extended message.  Reject it. */
4620                         reject = TRUE;
4621                         break;
4622                 }
4623                 break;
4624         }
4625 #ifdef AHD_TARGET_MODE
4626         case MSG_BUS_DEV_RESET:
4627                 ahd_handle_devreset(ahd, devinfo, CAM_LUN_WILDCARD,
4628                                     CAM_BDR_SENT,
4629                                     "Bus Device Reset Received",
4630                                     /*verbose_level*/0);
4631                 ahd_restart(ahd);
4632                 done = MSGLOOP_TERMINATED;
4633                 break;
4634         case MSG_ABORT_TAG:
4635         case MSG_ABORT:
4636         case MSG_CLEAR_QUEUE:
4637         {
4638                 int tag;
4639
4640                 /* Target mode messages */
4641                 if (devinfo->role != ROLE_TARGET) {
4642                         reject = TRUE;
4643                         break;
4644                 }
4645                 tag = SCB_LIST_NULL;
4646                 if (ahd->msgin_buf[0] == MSG_ABORT_TAG)
4647                         tag = ahd_inb(ahd, INITIATOR_TAG);
4648                 ahd_abort_scbs(ahd, devinfo->target, devinfo->channel,
4649                                devinfo->lun, tag, ROLE_TARGET,
4650                                CAM_REQ_ABORTED);
4651
4652                 tstate = ahd->enabled_targets[devinfo->our_scsiid];
4653                 if (tstate != NULL) {
4654                         struct ahd_tmode_lstate* lstate;
4655
4656                         lstate = tstate->enabled_luns[devinfo->lun];
4657                         if (lstate != NULL) {
4658                                 ahd_queue_lstate_event(ahd, lstate,
4659                                                        devinfo->our_scsiid,
4660                                                        ahd->msgin_buf[0],
4661                                                        /*arg*/tag);
4662                                 ahd_send_lstate_events(ahd, lstate);
4663                         }
4664                 }
4665                 ahd_restart(ahd);
4666                 done = MSGLOOP_TERMINATED;
4667                 break;
4668         }
4669 #endif
4670         case MSG_QAS_REQUEST:
4671 #ifdef AHD_DEBUG
4672                 if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
4673                         printf("%s: QAS request.  SCSISIGI == 0x%x\n",
4674                                ahd_name(ahd), ahd_inb(ahd, SCSISIGI));
4675 #endif
4676                 ahd->msg_flags |= MSG_FLAG_EXPECT_QASREJ_BUSFREE;
4677                 /* FALLTHROUGH */
4678         case MSG_TERM_IO_PROC:
4679         default:
4680                 reject = TRUE;
4681                 break;
4682         }
4683
4684         if (reject) {
4685                 /*
4686                  * Setup to reject the message.
4687                  */
4688                 ahd->msgout_index = 0;
4689                 ahd->msgout_len = 1;
4690                 ahd->msgout_buf[0] = MSG_MESSAGE_REJECT;
4691                 done = MSGLOOP_MSGCOMPLETE;
4692                 response = TRUE;
4693         }
4694
4695         if (done != MSGLOOP_IN_PROG && !response)
4696                 /* Clear the outgoing message buffer */
4697                 ahd->msgout_len = 0;
4698
4699         return (done);
4700 }
4701
4702 /*
4703  * Process a message reject message.
4704  */
4705 static int
4706 ahd_handle_msg_reject(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
4707 {
4708         /*
4709          * What we care about here is if we had an
4710          * outstanding SDTR or WDTR message for this
4711          * target.  If we did, this is a signal that
4712          * the target is refusing negotiation.
4713          */
4714         struct scb *scb;
4715         struct ahd_initiator_tinfo *tinfo;
4716         struct ahd_tmode_tstate *tstate;
4717         u_int scb_index;
4718         u_int last_msg;
4719         int   response = 0;
4720
4721         scb_index = ahd_get_scbptr(ahd);
4722         scb = ahd_lookup_scb(ahd, scb_index);
4723         tinfo = ahd_fetch_transinfo(ahd, devinfo->channel,
4724                                     devinfo->our_scsiid,
4725                                     devinfo->target, &tstate);
4726         /* Might be necessary */
4727         last_msg = ahd_inb(ahd, LAST_MSG);
4728
4729         if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_PPR, /*full*/FALSE)) {
4730                 if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_PPR, /*full*/TRUE)
4731                  && tinfo->goal.period <= AHD_SYNCRATE_PACED) {
4732                         /*
4733                          * Target may not like our SPI-4 PPR Options.
4734                          * Attempt to negotiate 80MHz which will turn
4735                          * off these options.
4736                          */
4737                         if (bootverbose) {
4738                                 printf("(%s:%c:%d:%d): PPR Rejected. "
4739                                        "Trying simple U160 PPR\n",
4740                                        ahd_name(ahd), devinfo->channel,
4741                                        devinfo->target, devinfo->lun);
4742                         }
4743                         tinfo->goal.period = AHD_SYNCRATE_DT;
4744                         tinfo->goal.ppr_options &= MSG_EXT_PPR_IU_REQ
4745                                                 |  MSG_EXT_PPR_QAS_REQ
4746                                                 |  MSG_EXT_PPR_DT_REQ;
4747                 } else {
4748                         /*
4749                          * Target does not support the PPR message.
4750                          * Attempt to negotiate SPI-2 style.
4751                          */
4752                         if (bootverbose) {
4753                                 printf("(%s:%c:%d:%d): PPR Rejected. "
4754                                        "Trying WDTR/SDTR\n",
4755                                        ahd_name(ahd), devinfo->channel,
4756                                        devinfo->target, devinfo->lun);
4757                         }
4758                         tinfo->goal.ppr_options = 0;
4759                         tinfo->curr.transport_version = 2;
4760                         tinfo->goal.transport_version = 2;
4761                 }
4762                 ahd->msgout_index = 0;
4763                 ahd->msgout_len = 0;
4764                 ahd_build_transfer_msg(ahd, devinfo);
4765                 ahd->msgout_index = 0;
4766                 response = 1;
4767         } else if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_WDTR, /*full*/FALSE)) {
4768
4769                 /* note 8bit xfers */
4770                 printf("(%s:%c:%d:%d): refuses WIDE negotiation.  Using "
4771                        "8bit transfers\n", ahd_name(ahd),
4772                        devinfo->channel, devinfo->target, devinfo->lun);
4773                 ahd_set_width(ahd, devinfo, MSG_EXT_WDTR_BUS_8_BIT,
4774                               AHD_TRANS_ACTIVE|AHD_TRANS_GOAL,
4775                               /*paused*/TRUE);
4776                 /*
4777                  * No need to clear the sync rate.  If the target
4778                  * did not accept the command, our syncrate is
4779                  * unaffected.  If the target started the negotiation,
4780                  * but rejected our response, we already cleared the
4781                  * sync rate before sending our WDTR.
4782                  */
4783                 if (tinfo->goal.offset != tinfo->curr.offset) {
4784
4785                         /* Start the sync negotiation */
4786                         ahd->msgout_index = 0;
4787                         ahd->msgout_len = 0;
4788                         ahd_build_transfer_msg(ahd, devinfo);
4789                         ahd->msgout_index = 0;
4790                         response = 1;
4791                 }
4792         } else if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_SDTR, /*full*/FALSE)) {
4793                 /* note asynch xfers and clear flag */
4794                 ahd_set_syncrate(ahd, devinfo, /*period*/0,
4795                                  /*offset*/0, /*ppr_options*/0,
4796                                  AHD_TRANS_ACTIVE|AHD_TRANS_GOAL,
4797                                  /*paused*/TRUE);
4798                 printf("(%s:%c:%d:%d): refuses synchronous negotiation. "
4799                        "Using asynchronous transfers\n",
4800                        ahd_name(ahd), devinfo->channel,
4801                        devinfo->target, devinfo->lun);
4802         } else if ((scb->hscb->control & MSG_SIMPLE_TASK) != 0) {
4803                 int tag_type;
4804                 int mask;
4805
4806                 tag_type = (scb->hscb->control & MSG_SIMPLE_TASK);
4807
4808                 if (tag_type == MSG_SIMPLE_TASK) {
4809                         printf("(%s:%c:%d:%d): refuses tagged commands.  "
4810                                "Performing non-tagged I/O\n", ahd_name(ahd),
4811                                devinfo->channel, devinfo->target, devinfo->lun);
4812                         ahd_set_tags(ahd, scb->io_ctx, devinfo, AHD_QUEUE_NONE);
4813                         mask = ~0x23;
4814                 } else {
4815                         printf("(%s:%c:%d:%d): refuses %s tagged commands.  "
4816                                "Performing simple queue tagged I/O only\n",
4817                                ahd_name(ahd), devinfo->channel, devinfo->target,
4818                                devinfo->lun, tag_type == MSG_ORDERED_TASK
4819                                ? "ordered" : "head of queue");
4820                         ahd_set_tags(ahd, scb->io_ctx, devinfo, AHD_QUEUE_BASIC);
4821                         mask = ~0x03;
4822                 }
4823
4824                 /*
4825                  * Resend the identify for this CCB as the target
4826                  * may believe that the selection is invalid otherwise.
4827                  */
4828                 ahd_outb(ahd, SCB_CONTROL,
4829                          ahd_inb_scbram(ahd, SCB_CONTROL) & mask);
4830                 scb->hscb->control &= mask;
4831                 ahd_set_transaction_tag(scb, /*enabled*/FALSE,
4832                                         /*type*/MSG_SIMPLE_TASK);
4833                 ahd_outb(ahd, MSG_OUT, MSG_IDENTIFYFLAG);
4834                 ahd_assert_atn(ahd);
4835                 ahd_busy_tcl(ahd, BUILD_TCL(scb->hscb->scsiid, devinfo->lun),
4836                              SCB_GET_TAG(scb));
4837
4838                 /*
4839                  * Requeue all tagged commands for this target
4840                  * currently in our posession so they can be
4841                  * converted to untagged commands.
4842                  */
4843                 ahd_search_qinfifo(ahd, SCB_GET_TARGET(ahd, scb),
4844                                    SCB_GET_CHANNEL(ahd, scb),
4845                                    SCB_GET_LUN(scb), /*tag*/SCB_LIST_NULL,
4846                                    ROLE_INITIATOR, CAM_REQUEUE_REQ,
4847                                    SEARCH_COMPLETE);
4848         } else if (ahd_sent_msg(ahd, AHDMSG_1B, MSG_IDENTIFYFLAG, TRUE)) {
4849                 /*
4850                  * Most likely the device believes that we had
4851                  * previously negotiated packetized.
4852                  */
4853                 ahd->msg_flags |= MSG_FLAG_EXPECT_PPR_BUSFREE
4854                                |  MSG_FLAG_IU_REQ_CHANGED;
4855
4856                 ahd_force_renegotiation(ahd, devinfo);
4857                 ahd->msgout_index = 0;
4858                 ahd->msgout_len = 0;
4859                 ahd_build_transfer_msg(ahd, devinfo);
4860                 ahd->msgout_index = 0;
4861                 response = 1;
4862         } else {
4863                 /*
4864                  * Otherwise, we ignore it.
4865                  */
4866                 printf("%s:%c:%d: Message reject for %x -- ignored\n",
4867                        ahd_name(ahd), devinfo->channel, devinfo->target,
4868                        last_msg);
4869         }
4870         return (response);
4871 }
4872
4873 /*
4874  * Process an ingnore wide residue message.
4875  */
4876 static void
4877 ahd_handle_ign_wide_residue(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
4878 {
4879         u_int scb_index;
4880         struct scb *scb;
4881
4882         scb_index = ahd_get_scbptr(ahd);
4883         scb = ahd_lookup_scb(ahd, scb_index);
4884         /*
4885          * XXX Actually check data direction in the sequencer?
4886          * Perhaps add datadir to some spare bits in the hscb?
4887          */
4888         if ((ahd_inb(ahd, SEQ_FLAGS) & DPHASE) == 0
4889          || ahd_get_transfer_dir(scb) != CAM_DIR_IN) {
4890                 /*
4891                  * Ignore the message if we haven't
4892                  * seen an appropriate data phase yet.
4893                  */
4894         } else {
4895                 /*
4896                  * If the residual occurred on the last
4897                  * transfer and the transfer request was
4898                  * expected to end on an odd count, do
4899                  * nothing.  Otherwise, subtract a byte
4900                  * and update the residual count accordingly.
4901                  */
4902                 uint32_t sgptr;
4903
4904                 sgptr = ahd_inb_scbram(ahd, SCB_RESIDUAL_SGPTR);
4905                 if ((sgptr & SG_LIST_NULL) != 0
4906                  && (ahd_inb_scbram(ahd, SCB_TASK_ATTRIBUTE)
4907                      & SCB_XFERLEN_ODD) != 0) {
4908                         /*
4909                          * If the residual occurred on the last
4910                          * transfer and the transfer request was
4911                          * expected to end on an odd count, do
4912                          * nothing.
4913                          */
4914                 } else {
4915                         uint32_t data_cnt;
4916                         uint64_t data_addr;
4917                         uint32_t sglen;
4918
4919                         /* Pull in the rest of the sgptr */
4920                         sgptr = ahd_inl_scbram(ahd, SCB_RESIDUAL_SGPTR);
4921                         data_cnt = ahd_inl_scbram(ahd, SCB_RESIDUAL_DATACNT);
4922                         if ((sgptr & SG_LIST_NULL) != 0) {
4923                                 /*
4924                                  * The residual data count is not updated
4925                                  * for the command run to completion case.
4926                                  * Explicitly zero the count.
4927                                  */
4928                                 data_cnt &= ~AHD_SG_LEN_MASK;
4929                         }
4930                         data_addr = ahd_inq(ahd, SHADDR);
4931                         data_cnt += 1;
4932                         data_addr -= 1;
4933                         sgptr &= SG_PTR_MASK;
4934                         if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0) {
4935                                 struct ahd_dma64_seg *sg;
4936
4937                                 sg = ahd_sg_bus_to_virt(ahd, scb, sgptr);
4938
4939                                 /*
4940                                  * The residual sg ptr points to the next S/G
4941                                  * to load so we must go back one.
4942                                  */
4943                                 sg--;
4944                                 sglen = ahd_le32toh(sg->len) & AHD_SG_LEN_MASK;
4945                                 if (sg != scb->sg_list
4946                                  && sglen < (data_cnt & AHD_SG_LEN_MASK)) {
4947
4948                                         sg--;
4949                                         sglen = ahd_le32toh(sg->len);
4950                                         /*
4951                                          * Preserve High Address and SG_LIST
4952                                          * bits while setting the count to 1.
4953                                          */
4954                                         data_cnt = 1|(sglen&(~AHD_SG_LEN_MASK));
4955                                         data_addr = ahd_le64toh(sg->addr)
4956                                                   + (sglen & AHD_SG_LEN_MASK)
4957                                                   - 1;
4958
4959                                         /*
4960                                          * Increment sg so it points to the
4961                                          * "next" sg.
4962                                          */
4963                                         sg++;
4964                                         sgptr = ahd_sg_virt_to_bus(ahd, scb,
4965                                                                    sg);
4966                                 }
4967                         } else {
4968                                 struct ahd_dma_seg *sg;
4969
4970                                 sg = ahd_sg_bus_to_virt(ahd, scb, sgptr);
4971
4972                                 /*
4973                                  * The residual sg ptr points to the next S/G
4974                                  * to load so we must go back one.
4975                                  */
4976                                 sg--;
4977                                 sglen = ahd_le32toh(sg->len) & AHD_SG_LEN_MASK;
4978                                 if (sg != scb->sg_list
4979                                  && sglen < (data_cnt & AHD_SG_LEN_MASK)) {
4980
4981                                         sg--;
4982                                         sglen = ahd_le32toh(sg->len);
4983                                         /*
4984                                          * Preserve High Address and SG_LIST
4985                                          * bits while setting the count to 1.
4986                                          */
4987                                         data_cnt = 1|(sglen&(~AHD_SG_LEN_MASK));
4988                                         data_addr = ahd_le32toh(sg->addr)
4989                                                   + (sglen & AHD_SG_LEN_MASK)
4990                                                   - 1;
4991
4992                                         /*
4993                                          * Increment sg so it points to the
4994                                          * "next" sg.
4995                                          */
4996                                         sg++;
4997                                         sgptr = ahd_sg_virt_to_bus(ahd, scb,
4998                                                                   sg);
4999                                 }
5000                         }
5001                         /*
5002                          * Toggle the "oddness" of the transfer length
5003                          * to handle this mid-transfer ignore wide
5004                          * residue.  This ensures that the oddness is
5005                          * correct for subsequent data transfers.
5006                          */
5007                         ahd_outb(ahd, SCB_TASK_ATTRIBUTE,
5008                             ahd_inb_scbram(ahd, SCB_TASK_ATTRIBUTE)
5009                             ^ SCB_XFERLEN_ODD);
5010
5011                         ahd_outl(ahd, SCB_RESIDUAL_SGPTR, sgptr);
5012                         ahd_outl(ahd, SCB_RESIDUAL_DATACNT, data_cnt);
5013                         /*
5014                          * The FIFO's pointers will be updated if/when the
5015                          * sequencer re-enters a data phase.
5016                          */
5017                 }
5018         }
5019 }
5020
5021
5022 /*
5023  * Reinitialize the data pointers for the active transfer
5024  * based on its current residual.
5025  */
5026 static void
5027 ahd_reinitialize_dataptrs(struct ahd_softc *ahd)
5028 {
5029         struct           scb *scb;
5030         ahd_mode_state   saved_modes;
5031         u_int            scb_index;
5032         u_int            wait;
5033         uint32_t         sgptr;
5034         uint32_t         resid;
5035         uint64_t         dataptr;
5036
5037         AHD_ASSERT_MODES(ahd, AHD_MODE_DFF0_MSK|AHD_MODE_DFF1_MSK,
5038                          AHD_MODE_DFF0_MSK|AHD_MODE_DFF1_MSK);
5039                          
5040         scb_index = ahd_get_scbptr(ahd);
5041         scb = ahd_lookup_scb(ahd, scb_index);
5042
5043         /*
5044          * Release and reacquire the FIFO so we
5045          * have a clean slate.
5046          */
5047         ahd_outb(ahd, DFFSXFRCTL, CLRCHN);
5048         wait = 1000;
5049         while (--wait && !(ahd_inb(ahd, MDFFSTAT) & FIFOFREE))
5050                 ahd_delay(100);
5051         if (wait == 0) {
5052                 ahd_print_path(ahd, scb);
5053                 printf("ahd_reinitialize_dataptrs: Forcing FIFO free.\n");
5054                 ahd_outb(ahd, DFFSXFRCTL, RSTCHN|CLRSHCNT);
5055         }
5056         saved_modes = ahd_save_modes(ahd);
5057         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
5058         ahd_outb(ahd, DFFSTAT,
5059                  ahd_inb(ahd, DFFSTAT)
5060                 | (saved_modes == 0x11 ? CURRFIFO_1 : CURRFIFO_0));
5061
5062         /*
5063          * Determine initial values for data_addr and data_cnt
5064          * for resuming the data phase.
5065          */
5066         sgptr = ahd_inl_scbram(ahd, SCB_RESIDUAL_SGPTR);
5067         sgptr &= SG_PTR_MASK;
5068
5069         resid = (ahd_inb_scbram(ahd, SCB_RESIDUAL_DATACNT + 2) << 16)
5070               | (ahd_inb_scbram(ahd, SCB_RESIDUAL_DATACNT + 1) << 8)
5071               | ahd_inb_scbram(ahd, SCB_RESIDUAL_DATACNT);
5072
5073         if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0) {
5074                 struct ahd_dma64_seg *sg;
5075
5076                 sg = ahd_sg_bus_to_virt(ahd, scb, sgptr);
5077
5078                 /* The residual sg_ptr always points to the next sg */
5079                 sg--;
5080
5081                 dataptr = ahd_le64toh(sg->addr)
5082                         + (ahd_le32toh(sg->len) & AHD_SG_LEN_MASK)
5083                         - resid;
5084                 ahd_outl(ahd, HADDR + 4, dataptr >> 32);
5085         } else {
5086                 struct   ahd_dma_seg *sg;
5087
5088                 sg = ahd_sg_bus_to_virt(ahd, scb, sgptr);
5089
5090                 /* The residual sg_ptr always points to the next sg */
5091                 sg--;
5092
5093                 dataptr = ahd_le32toh(sg->addr)
5094                         + (ahd_le32toh(sg->len) & AHD_SG_LEN_MASK)
5095                         - resid;
5096                 ahd_outb(ahd, HADDR + 4,
5097                          (ahd_le32toh(sg->len) & ~AHD_SG_LEN_MASK) >> 24);
5098         }
5099         ahd_outl(ahd, HADDR, dataptr);
5100         ahd_outb(ahd, HCNT + 2, resid >> 16);
5101         ahd_outb(ahd, HCNT + 1, resid >> 8);
5102         ahd_outb(ahd, HCNT, resid);
5103 }
5104
5105 /*
5106  * Handle the effects of issuing a bus device reset message.
5107  */
5108 static void
5109 ahd_handle_devreset(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
5110                     u_int lun, cam_status status, char *message,
5111                     int verbose_level)
5112 {
5113 #ifdef AHD_TARGET_MODE
5114         struct ahd_tmode_tstate* tstate;
5115 #endif
5116         int found;
5117
5118         found = ahd_abort_scbs(ahd, devinfo->target, devinfo->channel,
5119                                lun, SCB_LIST_NULL, devinfo->role,
5120                                status);
5121
5122 #ifdef AHD_TARGET_MODE
5123         /*
5124          * Send an immediate notify ccb to all target mord peripheral
5125          * drivers affected by this action.
5126          */
5127         tstate = ahd->enabled_targets[devinfo->our_scsiid];
5128         if (tstate != NULL) {
5129                 u_int cur_lun;
5130                 u_int max_lun;
5131
5132                 if (lun != CAM_LUN_WILDCARD) {
5133                         cur_lun = 0;
5134                         max_lun = AHD_NUM_LUNS - 1;
5135                 } else {
5136                         cur_lun = lun;
5137                         max_lun = lun;
5138                 }
5139                 for (cur_lun <= max_lun; cur_lun++) {
5140                         struct ahd_tmode_lstate* lstate;
5141
5142                         lstate = tstate->enabled_luns[cur_lun];
5143                         if (lstate == NULL)
5144                                 continue;
5145
5146                         ahd_queue_lstate_event(ahd, lstate, devinfo->our_scsiid,
5147                                                MSG_BUS_DEV_RESET, /*arg*/0);
5148                         ahd_send_lstate_events(ahd, lstate);
5149                 }
5150         }
5151 #endif
5152
5153         /*
5154          * Go back to async/narrow transfers and renegotiate.
5155          */
5156         ahd_set_width(ahd, devinfo, MSG_EXT_WDTR_BUS_8_BIT,
5157                       AHD_TRANS_CUR, /*paused*/TRUE);
5158         ahd_set_syncrate(ahd, devinfo, /*period*/0, /*offset*/0,
5159                          /*ppr_options*/0, AHD_TRANS_CUR,
5160                          /*paused*/TRUE);
5161         
5162         if (status != CAM_SEL_TIMEOUT)
5163                 ahd_send_async(ahd, devinfo->channel, devinfo->target,
5164                                CAM_LUN_WILDCARD, AC_SENT_BDR);
5165
5166         if (message != NULL && bootverbose)
5167                 printf("%s: %s on %c:%d. %d SCBs aborted\n", ahd_name(ahd),
5168                        message, devinfo->channel, devinfo->target, found);
5169 }
5170
5171 #ifdef AHD_TARGET_MODE
5172 static void
5173 ahd_setup_target_msgin(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
5174                        struct scb *scb)
5175 {
5176
5177         /*              
5178          * To facilitate adding multiple messages together,
5179          * each routine should increment the index and len
5180          * variables instead of setting them explicitly.
5181          */             
5182         ahd->msgout_index = 0;
5183         ahd->msgout_len = 0;
5184
5185         if (scb != NULL && (scb->flags & SCB_AUTO_NEGOTIATE) != 0)
5186                 ahd_build_transfer_msg(ahd, devinfo);
5187         else
5188                 panic("ahd_intr: AWAITING target message with no message");
5189
5190         ahd->msgout_index = 0;
5191         ahd->msg_type = MSG_TYPE_TARGET_MSGIN;
5192 }
5193 #endif
5194 /**************************** Initialization **********************************/
5195 static u_int
5196 ahd_sglist_size(struct ahd_softc *ahd)
5197 {
5198         bus_size_t list_size;
5199
5200         list_size = sizeof(struct ahd_dma_seg) * AHD_NSEG;
5201         if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0)
5202                 list_size = sizeof(struct ahd_dma64_seg) * AHD_NSEG;
5203         return (list_size);
5204 }
5205
5206 /*
5207  * Calculate the optimum S/G List allocation size.  S/G elements used
5208  * for a given transaction must be physically contiguous.  Assume the
5209  * OS will allocate full pages to us, so it doesn't make sense to request
5210  * less than a page.
5211  */
5212 static u_int
5213 ahd_sglist_allocsize(struct ahd_softc *ahd)
5214 {
5215         bus_size_t sg_list_increment;
5216         bus_size_t sg_list_size;
5217         bus_size_t max_list_size;
5218         bus_size_t best_list_size;
5219
5220         /* Start out with the minimum required for AHD_NSEG. */
5221         sg_list_increment = ahd_sglist_size(ahd);
5222         sg_list_size = sg_list_increment;
5223
5224         /* Get us as close as possible to a page in size. */
5225         while ((sg_list_size + sg_list_increment) <= PAGE_SIZE)
5226                 sg_list_size += sg_list_increment;
5227
5228         /*
5229          * Try to reduce the amount of wastage by allocating
5230          * multiple pages.
5231          */
5232         best_list_size = sg_list_size;
5233         max_list_size = roundup(sg_list_increment, PAGE_SIZE);
5234         if (max_list_size < 4 * PAGE_SIZE)
5235                 max_list_size = 4 * PAGE_SIZE;
5236         if (max_list_size > (AHD_SCB_MAX_ALLOC * sg_list_increment))
5237                 max_list_size = (AHD_SCB_MAX_ALLOC * sg_list_increment);
5238         while ((sg_list_size + sg_list_increment) <= max_list_size
5239            &&  (sg_list_size % PAGE_SIZE) != 0) {
5240                 bus_size_t new_mod;
5241                 bus_size_t best_mod;
5242
5243                 sg_list_size += sg_list_increment;
5244                 new_mod = sg_list_size % PAGE_SIZE;
5245                 best_mod = best_list_size % PAGE_SIZE;
5246                 if (new_mod > best_mod || new_mod == 0) {
5247                         best_list_size = sg_list_size;
5248                 }
5249         }
5250         return (best_list_size);
5251 }
5252
5253 /*
5254  * Allocate a controller structure for a new device
5255  * and perform initial initializion.
5256  */
5257 struct ahd_softc *
5258 ahd_alloc(void *platform_arg, char *name)
5259 {
5260         struct  ahd_softc *ahd;
5261
5262 #ifndef __FreeBSD__
5263         ahd = malloc(sizeof(*ahd), M_DEVBUF, M_NOWAIT);
5264         if (!ahd) {
5265                 printf("aic7xxx: cannot malloc softc!\n");
5266                 free(name, M_DEVBUF);
5267                 return NULL;
5268         }
5269 #else
5270         ahd = device_get_softc((device_t)platform_arg);
5271 #endif
5272         memset(ahd, 0, sizeof(*ahd));
5273         ahd->seep_config = malloc(sizeof(*ahd->seep_config),
5274                                   M_DEVBUF, M_NOWAIT);
5275         if (ahd->seep_config == NULL) {
5276 #ifndef __FreeBSD__
5277                 free(ahd, M_DEVBUF);
5278 #endif
5279                 free(name, M_DEVBUF);
5280                 return (NULL);
5281         }
5282         LIST_INIT(&ahd->pending_scbs);
5283         /* We don't know our unit number until the OSM sets it */
5284         ahd->name = name;
5285         ahd->unit = -1;
5286         ahd->description = NULL;
5287         ahd->bus_description = NULL;
5288         ahd->channel = 'A';
5289         ahd->chip = AHD_NONE;
5290         ahd->features = AHD_FENONE;
5291         ahd->bugs = AHD_BUGNONE;
5292         ahd->flags = AHD_SPCHK_ENB_A|AHD_RESET_BUS_A|AHD_TERM_ENB_A
5293                    | AHD_EXTENDED_TRANS_A|AHD_STPWLEVEL_A;
5294         ahd_timer_init(&ahd->reset_timer);
5295         ahd_timer_init(&ahd->stat_timer);
5296         ahd->int_coalescing_timer = AHD_INT_COALESCING_TIMER_DEFAULT;
5297         ahd->int_coalescing_maxcmds = AHD_INT_COALESCING_MAXCMDS_DEFAULT;
5298         ahd->int_coalescing_mincmds = AHD_INT_COALESCING_MINCMDS_DEFAULT;
5299         ahd->int_coalescing_threshold = AHD_INT_COALESCING_THRESHOLD_DEFAULT;
5300         ahd->int_coalescing_stop_threshold =
5301             AHD_INT_COALESCING_STOP_THRESHOLD_DEFAULT;
5302
5303         if (ahd_platform_alloc(ahd, platform_arg) != 0) {
5304                 ahd_free(ahd);
5305                 ahd = NULL;
5306         }
5307 #ifdef AHD_DEBUG
5308         if ((ahd_debug & AHD_SHOW_MEMORY) != 0) {
5309                 printf("%s: scb size = 0x%x, hscb size = 0x%x\n",
5310                        ahd_name(ahd), (u_int)sizeof(struct scb),
5311                        (u_int)sizeof(struct hardware_scb));
5312         }
5313 #endif
5314         return (ahd);
5315 }
5316
5317 int
5318 ahd_softc_init(struct ahd_softc *ahd)
5319 {
5320
5321         ahd->unpause = 0;
5322         ahd->pause = PAUSE; 
5323         return (0);
5324 }
5325
5326 void
5327 ahd_set_unit(struct ahd_softc *ahd, int unit)
5328 {
5329         ahd->unit = unit;
5330 }
5331
5332 void
5333 ahd_set_name(struct ahd_softc *ahd, char *name)
5334 {
5335         if (ahd->name != NULL)
5336                 free(ahd->name, M_DEVBUF);
5337         ahd->name = name;
5338 }
5339
5340 void
5341 ahd_free(struct ahd_softc *ahd)
5342 {
5343         int i;
5344
5345         switch (ahd->init_level) {
5346         default:
5347         case 5:
5348                 ahd_shutdown(ahd);
5349                 /* FALLTHROUGH */
5350         case 4:
5351                 ahd_dmamap_unload(ahd, ahd->shared_data_dmat,
5352                                   ahd->shared_data_map.dmamap);
5353                 /* FALLTHROUGH */
5354         case 3:
5355                 ahd_dmamem_free(ahd, ahd->shared_data_dmat, ahd->qoutfifo,
5356                                 ahd->shared_data_map.dmamap);
5357                 ahd_dmamap_destroy(ahd, ahd->shared_data_dmat,
5358                                    ahd->shared_data_map.dmamap);
5359                 /* FALLTHROUGH */
5360         case 2:
5361                 ahd_dma_tag_destroy(ahd, ahd->shared_data_dmat);
5362         case 1:
5363 #ifndef __linux__
5364                 ahd_dma_tag_destroy(ahd, ahd->buffer_dmat);
5365 #endif
5366                 break;
5367         case 0:
5368                 break;
5369         }
5370
5371 #ifndef __linux__
5372         ahd_dma_tag_destroy(ahd, ahd->parent_dmat);
5373 #endif
5374         ahd_platform_free(ahd);
5375         ahd_fini_scbdata(ahd);
5376         for (i = 0; i < AHD_NUM_TARGETS; i++) {
5377                 struct ahd_tmode_tstate *tstate;
5378
5379                 tstate = ahd->enabled_targets[i];
5380                 if (tstate != NULL) {
5381 #ifdef AHD_TARGET_MODE
5382                         int j;
5383
5384                         for (j = 0; j < AHD_NUM_LUNS; j++) {
5385                                 struct ahd_tmode_lstate *lstate;
5386
5387                                 lstate = tstate->enabled_luns[j];
5388                                 if (lstate != NULL) {
5389                                         xpt_free_path(lstate->path);
5390                                         free(lstate, M_DEVBUF);
5391                                 }
5392                         }
5393 #endif
5394                         free(tstate, M_DEVBUF);
5395                 }
5396         }
5397 #ifdef AHD_TARGET_MODE
5398         if (ahd->black_hole != NULL) {
5399                 xpt_free_path(ahd->black_hole->path);
5400                 free(ahd->black_hole, M_DEVBUF);
5401         }
5402 #endif
5403         if (ahd->name != NULL)
5404                 free(ahd->name, M_DEVBUF);
5405         if (ahd->seep_config != NULL)
5406                 free(ahd->seep_config, M_DEVBUF);
5407         if (ahd->saved_stack != NULL)
5408                 free(ahd->saved_stack, M_DEVBUF);
5409 #ifndef __FreeBSD__
5410         free(ahd, M_DEVBUF);
5411 #endif
5412         return;
5413 }
5414
5415 static void
5416 ahd_shutdown(void *arg)
5417 {
5418         struct  ahd_softc *ahd;
5419
5420         ahd = (struct ahd_softc *)arg;
5421
5422         /*
5423          * Stop periodic timer callbacks.
5424          */
5425         ahd_timer_stop(&ahd->reset_timer);
5426         ahd_timer_stop(&ahd->stat_timer);
5427
5428         /* This will reset most registers to 0, but not all */
5429         ahd_reset(ahd, /*reinit*/FALSE);
5430 }
5431
5432 /*
5433  * Reset the controller and record some information about it
5434  * that is only available just after a reset.  If "reinit" is
5435  * non-zero, this reset occured after initial configuration
5436  * and the caller requests that the chip be fully reinitialized
5437  * to a runable state.  Chip interrupts are *not* enabled after
5438  * a reinitialization.  The caller must enable interrupts via
5439  * ahd_intr_enable().
5440  */
5441 int
5442 ahd_reset(struct ahd_softc *ahd, int reinit)
5443 {
5444         u_int    sxfrctl1;
5445         int      wait;
5446         uint32_t cmd;
5447         
5448         /*
5449          * Preserve the value of the SXFRCTL1 register for all channels.
5450          * It contains settings that affect termination and we don't want
5451          * to disturb the integrity of the bus.
5452          */
5453         ahd_pause(ahd);
5454         ahd_update_modes(ahd);
5455         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
5456         sxfrctl1 = ahd_inb(ahd, SXFRCTL1);
5457
5458         cmd = ahd_pci_read_config(ahd->dev_softc, PCIR_COMMAND, /*bytes*/2);
5459         if ((ahd->bugs & AHD_PCIX_CHIPRST_BUG) != 0) {
5460                 uint32_t mod_cmd;
5461
5462                 /*
5463                  * A4 Razor #632
5464                  * During the assertion of CHIPRST, the chip
5465                  * does not disable its parity logic prior to
5466                  * the start of the reset.  This may cause a
5467                  * parity error to be detected and thus a
5468                  * spurious SERR or PERR assertion.  Disble
5469                  * PERR and SERR responses during the CHIPRST.
5470                  */
5471                 mod_cmd = cmd & ~(PCIM_CMD_PERRESPEN|PCIM_CMD_SERRESPEN);
5472                 ahd_pci_write_config(ahd->dev_softc, PCIR_COMMAND,
5473                                      mod_cmd, /*bytes*/2);
5474         }
5475         ahd_outb(ahd, HCNTRL, CHIPRST | ahd->pause);
5476
5477         /*
5478          * Ensure that the reset has finished.  We delay 1000us
5479          * prior to reading the register to make sure the chip
5480          * has sufficiently completed its reset to handle register
5481          * accesses.
5482          */
5483         wait = 1000;
5484         do {
5485                 ahd_delay(1000);
5486         } while (--wait && !(ahd_inb(ahd, HCNTRL) & CHIPRSTACK));
5487
5488         if (wait == 0) {
5489                 printf("%s: WARNING - Failed chip reset!  "
5490                        "Trying to initialize anyway.\n", ahd_name(ahd));
5491         }
5492         ahd_outb(ahd, HCNTRL, ahd->pause);
5493
5494         if ((ahd->bugs & AHD_PCIX_CHIPRST_BUG) != 0) {
5495                 /*
5496                  * Clear any latched PCI error status and restore
5497                  * previous SERR and PERR response enables.
5498                  */
5499                 ahd_pci_write_config(ahd->dev_softc, PCIR_STATUS + 1,
5500                                      0xFF, /*bytes*/1);
5501                 ahd_pci_write_config(ahd->dev_softc, PCIR_COMMAND,
5502                                      cmd, /*bytes*/2);
5503         }
5504
5505         /*
5506          * Mode should be SCSI after a chip reset, but lets
5507          * set it just to be safe.  We touch the MODE_PTR
5508          * register directly so as to bypass the lazy update
5509          * code in ahd_set_modes().
5510          */
5511         ahd_known_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
5512         ahd_outb(ahd, MODE_PTR,
5513                  ahd_build_mode_state(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI));
5514
5515         /*
5516          * Restore SXFRCTL1.
5517          *
5518          * We must always initialize STPWEN to 1 before we
5519          * restore the saved values.  STPWEN is initialized
5520          * to a tri-state condition which can only be cleared
5521          * by turning it on.
5522          */
5523         ahd_outb(ahd, SXFRCTL1, sxfrctl1|STPWEN);
5524         ahd_outb(ahd, SXFRCTL1, sxfrctl1);
5525
5526         /* Determine chip configuration */
5527         ahd->features &= ~AHD_WIDE;
5528         if ((ahd_inb(ahd, SBLKCTL) & SELWIDE) != 0)
5529                 ahd->features |= AHD_WIDE;
5530
5531         /*
5532          * If a recovery action has forced a chip reset,
5533          * re-initialize the chip to our liking.
5534          */
5535         if (reinit != 0)
5536                 ahd_chip_init(ahd);
5537
5538         return (0);
5539 }
5540
5541 /*
5542  * Determine the number of SCBs available on the controller
5543  */
5544 static int
5545 ahd_probe_scbs(struct ahd_softc *ahd) {
5546         int i;
5547
5548         AHD_ASSERT_MODES(ahd, ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK),
5549                          ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK));
5550         for (i = 0; i < AHD_SCB_MAX; i++) {
5551                 int j;
5552
5553                 ahd_set_scbptr(ahd, i);
5554                 ahd_outw(ahd, SCB_BASE, i);
5555                 for (j = 2; j < 64; j++)
5556                         ahd_outb(ahd, SCB_BASE+j, 0);
5557                 /* Start out life as unallocated (needing an abort) */
5558                 ahd_outb(ahd, SCB_CONTROL, MK_MESSAGE);
5559                 if (ahd_inw_scbram(ahd, SCB_BASE) != i)
5560                         break;
5561                 ahd_set_scbptr(ahd, 0);
5562                 if (ahd_inw_scbram(ahd, SCB_BASE) != 0)
5563                         break;
5564         }
5565         return (i);
5566 }
5567
5568 static void
5569 ahd_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nseg, int error) 
5570 {
5571         dma_addr_t *baddr;
5572
5573         baddr = (dma_addr_t *)arg;
5574         *baddr = segs->ds_addr;
5575 }
5576
5577 static void
5578 ahd_initialize_hscbs(struct ahd_softc *ahd)
5579 {
5580         int i;
5581
5582         for (i = 0; i < ahd->scb_data.maxhscbs; i++) {
5583                 ahd_set_scbptr(ahd, i);
5584
5585                 /* Clear the control byte. */
5586                 ahd_outb(ahd, SCB_CONTROL, 0);
5587
5588                 /* Set the next pointer */
5589                 ahd_outw(ahd, SCB_NEXT, SCB_LIST_NULL);
5590         }
5591 }
5592
5593 static int
5594 ahd_init_scbdata(struct ahd_softc *ahd)
5595 {
5596         struct  scb_data *scb_data;
5597         int     i;
5598
5599         scb_data = &ahd->scb_data;
5600         TAILQ_INIT(&scb_data->free_scbs);
5601         for (i = 0; i < AHD_NUM_TARGETS * AHD_NUM_LUNS_NONPKT; i++)
5602                 LIST_INIT(&scb_data->free_scb_lists[i]);
5603         LIST_INIT(&scb_data->any_dev_free_scb_list);
5604         SLIST_INIT(&scb_data->hscb_maps);
5605         SLIST_INIT(&scb_data->sg_maps);
5606         SLIST_INIT(&scb_data->sense_maps);
5607
5608         /* Determine the number of hardware SCBs and initialize them */
5609         scb_data->maxhscbs = ahd_probe_scbs(ahd);
5610         if (scb_data->maxhscbs == 0) {
5611                 printf("%s: No SCB space found\n", ahd_name(ahd));
5612                 return (ENXIO);
5613         }
5614
5615         ahd_initialize_hscbs(ahd);
5616
5617         /*
5618          * Create our DMA tags.  These tags define the kinds of device
5619          * accessible memory allocations and memory mappings we will
5620          * need to perform during normal operation.
5621          *
5622          * Unless we need to further restrict the allocation, we rely
5623          * on the restrictions of the parent dmat, hence the common
5624          * use of MAXADDR and MAXSIZE.
5625          */
5626
5627         /* DMA tag for our hardware scb structures */
5628         if (ahd_dma_tag_create(ahd, ahd->parent_dmat, /*alignment*/1,
5629                                /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
5630                                /*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
5631                                /*highaddr*/BUS_SPACE_MAXADDR,
5632                                /*filter*/NULL, /*filterarg*/NULL,
5633                                PAGE_SIZE, /*nsegments*/1,
5634                                /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
5635                                /*flags*/0, &scb_data->hscb_dmat) != 0) {
5636                 goto error_exit;
5637         }
5638
5639         scb_data->init_level++;
5640
5641         /* DMA tag for our S/G structures. */
5642         if (ahd_dma_tag_create(ahd, ahd->parent_dmat, /*alignment*/8,
5643                                /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
5644                                /*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
5645                                /*highaddr*/BUS_SPACE_MAXADDR,
5646                                /*filter*/NULL, /*filterarg*/NULL,
5647                                ahd_sglist_allocsize(ahd), /*nsegments*/1,
5648                                /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
5649                                /*flags*/0, &scb_data->sg_dmat) != 0) {
5650                 goto error_exit;
5651         }
5652 #ifdef AHD_DEBUG
5653         if ((ahd_debug & AHD_SHOW_MEMORY) != 0)
5654                 printf("%s: ahd_sglist_allocsize = 0x%x\n", ahd_name(ahd),
5655                        ahd_sglist_allocsize(ahd));
5656 #endif
5657
5658         scb_data->init_level++;
5659
5660         /* DMA tag for our sense buffers.  We allocate in page sized chunks */
5661         if (ahd_dma_tag_create(ahd, ahd->parent_dmat, /*alignment*/1,
5662                                /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
5663                                /*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
5664                                /*highaddr*/BUS_SPACE_MAXADDR,
5665                                /*filter*/NULL, /*filterarg*/NULL,
5666                                PAGE_SIZE, /*nsegments*/1,
5667                                /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
5668                                /*flags*/0, &scb_data->sense_dmat) != 0) {
5669                 goto error_exit;
5670         }
5671
5672         scb_data->init_level++;
5673
5674         /* Perform initial CCB allocation */
5675         ahd_alloc_scbs(ahd);
5676
5677         if (scb_data->numscbs == 0) {
5678                 printf("%s: ahd_init_scbdata - "
5679                        "Unable to allocate initial scbs\n",
5680                        ahd_name(ahd));
5681                 goto error_exit;
5682         }
5683
5684         /*
5685          * Note that we were successfull
5686          */
5687         return (0); 
5688
5689 error_exit:
5690
5691         return (ENOMEM);
5692 }
5693
5694 static struct scb *
5695 ahd_find_scb_by_tag(struct ahd_softc *ahd, u_int tag)
5696 {
5697         struct scb *scb;
5698
5699         /*
5700          * Look on the pending list.
5701          */
5702         LIST_FOREACH(scb, &ahd->pending_scbs, pending_links) {
5703                 if (SCB_GET_TAG(scb) == tag)
5704                         return (scb);
5705         }
5706
5707         /*
5708          * Then on all of the collision free lists.
5709          */
5710         TAILQ_FOREACH(scb, &ahd->scb_data.free_scbs, links.tqe) {
5711                 struct scb *list_scb;
5712
5713                 list_scb = scb;
5714                 do {
5715                         if (SCB_GET_TAG(list_scb) == tag)
5716                                 return (list_scb);
5717                         list_scb = LIST_NEXT(list_scb, collision_links);
5718                 } while (list_scb);
5719         }
5720
5721         /*
5722          * And finally on the generic free list.
5723          */
5724         LIST_FOREACH(scb, &ahd->scb_data.any_dev_free_scb_list, links.le) {
5725                 if (SCB_GET_TAG(scb) == tag)
5726                         return (scb);
5727         }
5728
5729         return (NULL);
5730 }
5731
5732 static void
5733 ahd_fini_scbdata(struct ahd_softc *ahd)
5734 {
5735         struct scb_data *scb_data;
5736
5737         scb_data = &ahd->scb_data;
5738         if (scb_data == NULL)
5739                 return;
5740
5741         switch (scb_data->init_level) {
5742         default:
5743         case 7:
5744         {
5745                 struct map_node *sns_map;
5746
5747                 while ((sns_map = SLIST_FIRST(&scb_data->sense_maps)) != NULL) {
5748                         SLIST_REMOVE_HEAD(&scb_data->sense_maps, links);
5749                         ahd_dmamap_unload(ahd, scb_data->sense_dmat,
5750                                           sns_map->dmamap);
5751                         ahd_dmamem_free(ahd, scb_data->sense_dmat,
5752                                         sns_map->vaddr, sns_map->dmamap);
5753                         free(sns_map, M_DEVBUF);
5754                 }
5755                 ahd_dma_tag_destroy(ahd, scb_data->sense_dmat);
5756                 /* FALLTHROUGH */
5757         }
5758         case 6:
5759         {
5760                 struct map_node *sg_map;
5761
5762                 while ((sg_map = SLIST_FIRST(&scb_data->sg_maps)) != NULL) {
5763                         SLIST_REMOVE_HEAD(&scb_data->sg_maps, links);
5764                         ahd_dmamap_unload(ahd, scb_data->sg_dmat,
5765                                           sg_map->dmamap);
5766                         ahd_dmamem_free(ahd, scb_data->sg_dmat,
5767                                         sg_map->vaddr, sg_map->dmamap);
5768                         free(sg_map, M_DEVBUF);
5769                 }
5770                 ahd_dma_tag_destroy(ahd, scb_data->sg_dmat);
5771                 /* FALLTHROUGH */
5772         }
5773         case 5:
5774         {
5775                 struct map_node *hscb_map;
5776
5777                 while ((hscb_map = SLIST_FIRST(&scb_data->hscb_maps)) != NULL) {
5778                         SLIST_REMOVE_HEAD(&scb_data->hscb_maps, links);
5779                         ahd_dmamap_unload(ahd, scb_data->hscb_dmat,
5780                                           hscb_map->dmamap);
5781                         ahd_dmamem_free(ahd, scb_data->hscb_dmat,
5782                                         hscb_map->vaddr, hscb_map->dmamap);
5783                         free(hscb_map, M_DEVBUF);
5784                 }
5785                 ahd_dma_tag_destroy(ahd, scb_data->hscb_dmat);
5786                 /* FALLTHROUGH */
5787         }
5788         case 4:
5789         case 3:
5790         case 2:
5791         case 1:
5792         case 0:
5793                 break;
5794         }
5795 }
5796
5797 /*
5798  * DSP filter Bypass must be enabled until the first selection
5799  * after a change in bus mode (Razor #491 and #493).
5800  */
5801 static void
5802 ahd_setup_iocell_workaround(struct ahd_softc *ahd)
5803 {
5804         ahd_mode_state saved_modes;
5805
5806         saved_modes = ahd_save_modes(ahd);
5807         ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
5808         ahd_outb(ahd, DSPDATACTL, ahd_inb(ahd, DSPDATACTL)
5809                | BYPASSENAB | RCVROFFSTDIS | XMITOFFSTDIS);
5810         ahd_outb(ahd, SIMODE0, ahd_inb(ahd, SIMODE0) | (ENSELDO|ENSELDI));
5811 #ifdef AHD_DEBUG
5812         if ((ahd_debug & AHD_SHOW_MISC) != 0)
5813                 printf("%s: Setting up iocell workaround\n", ahd_name(ahd));
5814 #endif
5815         ahd_restore_modes(ahd, saved_modes);
5816         ahd->flags &= ~AHD_HAD_FIRST_SEL;
5817 }
5818
5819 static void
5820 ahd_iocell_first_selection(struct ahd_softc *ahd)
5821 {
5822         ahd_mode_state  saved_modes;
5823         u_int           sblkctl;
5824
5825         if ((ahd->flags & AHD_HAD_FIRST_SEL) != 0)
5826                 return;
5827         saved_modes = ahd_save_modes(ahd);
5828         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
5829         sblkctl = ahd_inb(ahd, SBLKCTL);
5830         ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
5831 #ifdef AHD_DEBUG
5832         if ((ahd_debug & AHD_SHOW_MISC) != 0)
5833                 printf("%s: iocell first selection\n", ahd_name(ahd));
5834 #endif
5835         if ((sblkctl & ENAB40) != 0) {
5836                 ahd_outb(ahd, DSPDATACTL,
5837                          ahd_inb(ahd, DSPDATACTL) & ~BYPASSENAB);
5838 #ifdef AHD_DEBUG
5839                 if ((ahd_debug & AHD_SHOW_MISC) != 0)
5840                         printf("%s: BYPASS now disabled\n", ahd_name(ahd));
5841 #endif
5842         }
5843         ahd_outb(ahd, SIMODE0, ahd_inb(ahd, SIMODE0) & ~(ENSELDO|ENSELDI));
5844         ahd_outb(ahd, CLRINT, CLRSCSIINT);
5845         ahd_restore_modes(ahd, saved_modes);
5846         ahd->flags |= AHD_HAD_FIRST_SEL;
5847 }
5848
5849 /*************************** SCB Management ***********************************/
5850 static void
5851 ahd_add_col_list(struct ahd_softc *ahd, struct scb *scb, u_int col_idx)
5852 {
5853         struct  scb_list *free_list;
5854         struct  scb_tailq *free_tailq;
5855         struct  scb *first_scb;
5856
5857         scb->flags |= SCB_ON_COL_LIST;
5858         AHD_SET_SCB_COL_IDX(scb, col_idx);
5859         free_list = &ahd->scb_data.free_scb_lists[col_idx];
5860         free_tailq = &ahd->scb_data.free_scbs;
5861         first_scb = LIST_FIRST(free_list);
5862         if (first_scb != NULL) {
5863                 LIST_INSERT_AFTER(first_scb, scb, collision_links);
5864         } else {
5865                 LIST_INSERT_HEAD(free_list, scb, collision_links);
5866                 TAILQ_INSERT_TAIL(free_tailq, scb, links.tqe);
5867         }
5868 }
5869
5870 static void
5871 ahd_rem_col_list(struct ahd_softc *ahd, struct scb *scb)
5872 {
5873         struct  scb_list *free_list;
5874         struct  scb_tailq *free_tailq;
5875         struct  scb *first_scb;
5876         u_int   col_idx;
5877
5878         scb->flags &= ~SCB_ON_COL_LIST;
5879         col_idx = AHD_GET_SCB_COL_IDX(ahd, scb);
5880         free_list = &ahd->scb_data.free_scb_lists[col_idx];
5881         free_tailq = &ahd->scb_data.free_scbs;
5882         first_scb = LIST_FIRST(free_list);
5883         if (first_scb == scb) {
5884                 struct scb *next_scb;
5885
5886                 /*
5887                  * Maintain order in the collision free
5888                  * lists for fairness if this device has
5889                  * other colliding tags active.
5890                  */
5891                 next_scb = LIST_NEXT(scb, collision_links);
5892                 if (next_scb != NULL) {
5893                         TAILQ_INSERT_AFTER(free_tailq, scb,
5894                                            next_scb, links.tqe);
5895                 }
5896                 TAILQ_REMOVE(free_tailq, scb, links.tqe);
5897         }
5898         LIST_REMOVE(scb, collision_links);
5899 }
5900
5901 /*
5902  * Get a free scb. If there are none, see if we can allocate a new SCB.
5903  */
5904 struct scb *
5905 ahd_get_scb(struct ahd_softc *ahd, u_int col_idx)
5906 {
5907         struct scb *scb;
5908         int tries;
5909
5910         tries = 0;
5911 look_again:
5912         TAILQ_FOREACH(scb, &ahd->scb_data.free_scbs, links.tqe) {
5913                 if (AHD_GET_SCB_COL_IDX(ahd, scb) != col_idx) {
5914                         ahd_rem_col_list(ahd, scb);
5915                         goto found;
5916                 }
5917         }
5918         if ((scb = LIST_FIRST(&ahd->scb_data.any_dev_free_scb_list)) == NULL) {
5919
5920                 if (tries++ != 0)
5921                         return (NULL);
5922                 ahd_alloc_scbs(ahd);
5923                 goto look_again;
5924         }
5925         LIST_REMOVE(scb, links.le);
5926         if (col_idx != AHD_NEVER_COL_IDX
5927          && (scb->col_scb != NULL)
5928          && (scb->col_scb->flags & SCB_ACTIVE) == 0) {
5929                 LIST_REMOVE(scb->col_scb, links.le);
5930                 ahd_add_col_list(ahd, scb->col_scb, col_idx);
5931         }
5932 found:
5933         scb->flags |= SCB_ACTIVE;
5934         return (scb);
5935 }
5936
5937 /*
5938  * Return an SCB resource to the free list.
5939  */
5940 void
5941 ahd_free_scb(struct ahd_softc *ahd, struct scb *scb)
5942 {       
5943
5944         /* Clean up for the next user */
5945         scb->flags = SCB_FLAG_NONE;
5946         scb->hscb->control = 0;
5947         ahd->scb_data.scbindex[SCB_GET_TAG(scb)] = NULL;
5948
5949         if (scb->col_scb == NULL) {
5950
5951                 /*
5952                  * No collision possible.  Just free normally.
5953                  */
5954                 LIST_INSERT_HEAD(&ahd->scb_data.any_dev_free_scb_list,
5955                                  scb, links.le);
5956         } else if ((scb->col_scb->flags & SCB_ON_COL_LIST) != 0) {
5957
5958                 /*
5959                  * The SCB we might have collided with is on
5960                  * a free collision list.  Put both SCBs on
5961                  * the generic list.
5962                  */
5963                 ahd_rem_col_list(ahd, scb->col_scb);
5964                 LIST_INSERT_HEAD(&ahd->scb_data.any_dev_free_scb_list,
5965                                  scb, links.le);
5966                 LIST_INSERT_HEAD(&ahd->scb_data.any_dev_free_scb_list,
5967                                  scb->col_scb, links.le);
5968         } else if ((scb->col_scb->flags
5969                   & (SCB_PACKETIZED|SCB_ACTIVE)) == SCB_ACTIVE
5970                 && (scb->col_scb->hscb->control & TAG_ENB) != 0) {
5971
5972                 /*
5973                  * The SCB we might collide with on the next allocation
5974                  * is still active in a non-packetized, tagged, context.
5975                  * Put us on the SCB collision list.
5976                  */
5977                 ahd_add_col_list(ahd, scb,
5978                                  AHD_GET_SCB_COL_IDX(ahd, scb->col_scb));
5979         } else {
5980                 /*
5981                  * The SCB we might collide with on the next allocation
5982                  * is either active in a packetized context, or free.
5983                  * Since we can't collide, put this SCB on the generic
5984                  * free list.
5985                  */
5986                 LIST_INSERT_HEAD(&ahd->scb_data.any_dev_free_scb_list,
5987                                  scb, links.le);
5988         }
5989
5990         ahd_platform_scb_free(ahd, scb);
5991 }
5992
5993 static void
5994 ahd_alloc_scbs(struct ahd_softc *ahd)
5995 {
5996         struct scb_data *scb_data;
5997         struct scb      *next_scb;
5998         struct hardware_scb *hscb;
5999         struct map_node *hscb_map;
6000         struct map_node *sg_map;
6001         struct map_node *sense_map;
6002         uint8_t         *segs;
6003         uint8_t         *sense_data;
6004         dma_addr_t       hscb_busaddr;
6005         dma_addr_t       sg_busaddr;
6006         dma_addr_t       sense_busaddr;
6007         int              newcount;
6008         int              i;
6009
6010         scb_data = &ahd->scb_data;
6011         if (scb_data->numscbs >= AHD_SCB_MAX_ALLOC)
6012                 /* Can't allocate any more */
6013                 return;
6014
6015         if (scb_data->scbs_left != 0) {
6016                 int offset;
6017
6018                 offset = (PAGE_SIZE / sizeof(*hscb)) - scb_data->scbs_left;
6019                 hscb_map = SLIST_FIRST(&scb_data->hscb_maps);
6020                 hscb = &((struct hardware_scb *)hscb_map->vaddr)[offset];
6021                 hscb_busaddr = hscb_map->physaddr + (offset * sizeof(*hscb));
6022         } else {
6023                 hscb_map = malloc(sizeof(*hscb_map), M_DEVBUF, M_NOWAIT);
6024
6025                 if (hscb_map == NULL)
6026                         return;
6027
6028                 /* Allocate the next batch of hardware SCBs */
6029                 if (ahd_dmamem_alloc(ahd, scb_data->hscb_dmat,
6030                                      (void **)&hscb_map->vaddr,
6031                                      BUS_DMA_NOWAIT, &hscb_map->dmamap) != 0) {
6032                         free(hscb_map, M_DEVBUF);
6033                         return;
6034                 }
6035
6036                 SLIST_INSERT_HEAD(&scb_data->hscb_maps, hscb_map, links);
6037
6038                 ahd_dmamap_load(ahd, scb_data->hscb_dmat, hscb_map->dmamap,
6039                                 hscb_map->vaddr, PAGE_SIZE, ahd_dmamap_cb,
6040                                 &hscb_map->physaddr, /*flags*/0);
6041
6042                 hscb = (struct hardware_scb *)hscb_map->vaddr;
6043                 hscb_busaddr = hscb_map->physaddr;
6044                 scb_data->scbs_left = PAGE_SIZE / sizeof(*hscb);
6045         }
6046
6047         if (scb_data->sgs_left != 0) {
6048                 int offset;
6049
6050                 offset = ((ahd_sglist_allocsize(ahd) / ahd_sglist_size(ahd))
6051                        - scb_data->sgs_left) * ahd_sglist_size(ahd);
6052                 sg_map = SLIST_FIRST(&scb_data->sg_maps);
6053                 segs = sg_map->vaddr + offset;
6054                 sg_busaddr = sg_map->physaddr + offset;
6055         } else {
6056                 sg_map = malloc(sizeof(*sg_map), M_DEVBUF, M_NOWAIT);
6057
6058                 if (sg_map == NULL)
6059                         return;
6060
6061                 /* Allocate the next batch of S/G lists */
6062                 if (ahd_dmamem_alloc(ahd, scb_data->sg_dmat,
6063                                      (void **)&sg_map->vaddr,
6064                                      BUS_DMA_NOWAIT, &sg_map->dmamap) != 0) {
6065                         free(sg_map, M_DEVBUF);
6066                         return;
6067                 }
6068
6069                 SLIST_INSERT_HEAD(&scb_data->sg_maps, sg_map, links);
6070
6071                 ahd_dmamap_load(ahd, scb_data->sg_dmat, sg_map->dmamap,
6072                                 sg_map->vaddr, ahd_sglist_allocsize(ahd),
6073                                 ahd_dmamap_cb, &sg_map->physaddr, /*flags*/0);
6074
6075                 segs = sg_map->vaddr;
6076                 sg_busaddr = sg_map->physaddr;
6077                 scb_data->sgs_left =
6078                     ahd_sglist_allocsize(ahd) / ahd_sglist_size(ahd);
6079 #ifdef AHD_DEBUG
6080                 if (ahd_debug & AHD_SHOW_MEMORY)
6081                         printf("Mapped SG data\n");
6082 #endif
6083         }
6084
6085         if (scb_data->sense_left != 0) {
6086                 int offset;
6087
6088                 offset = PAGE_SIZE - (AHD_SENSE_BUFSIZE * scb_data->sense_left);
6089                 sense_map = SLIST_FIRST(&scb_data->sense_maps);
6090                 sense_data = sense_map->vaddr + offset;
6091                 sense_busaddr = sense_map->physaddr + offset;
6092         } else {
6093                 sense_map = malloc(sizeof(*sense_map), M_DEVBUF, M_NOWAIT);
6094
6095                 if (sense_map == NULL)
6096                         return;
6097
6098                 /* Allocate the next batch of sense buffers */
6099                 if (ahd_dmamem_alloc(ahd, scb_data->sense_dmat,
6100                                      (void **)&sense_map->vaddr,
6101                                      BUS_DMA_NOWAIT, &sense_map->dmamap) != 0) {
6102                         free(sense_map, M_DEVBUF);
6103                         return;
6104                 }
6105
6106                 SLIST_INSERT_HEAD(&scb_data->sense_maps, sense_map, links);
6107
6108                 ahd_dmamap_load(ahd, scb_data->sense_dmat, sense_map->dmamap,
6109                                 sense_map->vaddr, PAGE_SIZE, ahd_dmamap_cb,
6110                                 &sense_map->physaddr, /*flags*/0);
6111
6112                 sense_data = sense_map->vaddr;
6113                 sense_busaddr = sense_map->physaddr;
6114                 scb_data->sense_left = PAGE_SIZE / AHD_SENSE_BUFSIZE;
6115 #ifdef AHD_DEBUG
6116                 if (ahd_debug & AHD_SHOW_MEMORY)
6117                         printf("Mapped sense data\n");
6118 #endif
6119         }
6120
6121         newcount = min(scb_data->sense_left, scb_data->scbs_left);
6122         newcount = min(newcount, scb_data->sgs_left);
6123         newcount = min(newcount, (AHD_SCB_MAX_ALLOC - scb_data->numscbs));
6124         for (i = 0; i < newcount; i++) {
6125                 struct scb_platform_data *pdata;
6126                 u_int col_tag;
6127 #ifndef __linux__
6128                 int error;
6129 #endif
6130
6131                 next_scb = (struct scb *)malloc(sizeof(*next_scb),
6132                                                 M_DEVBUF, M_NOWAIT);
6133                 if (next_scb == NULL)
6134                         break;
6135
6136                 pdata = (struct scb_platform_data *)malloc(sizeof(*pdata),
6137                                                            M_DEVBUF, M_NOWAIT);
6138                 if (pdata == NULL) {
6139                         free(next_scb, M_DEVBUF);
6140                         break;
6141                 }
6142                 next_scb->platform_data = pdata;
6143                 next_scb->hscb_map = hscb_map;
6144                 next_scb->sg_map = sg_map;
6145                 next_scb->sense_map = sense_map;
6146                 next_scb->sg_list = segs;
6147                 next_scb->sense_data = sense_data;
6148                 next_scb->sense_busaddr = sense_busaddr;
6149                 memset(hscb, 0, sizeof(*hscb));
6150                 next_scb->hscb = hscb;
6151                 hscb->hscb_busaddr = ahd_htole32(hscb_busaddr);
6152
6153                 /*
6154                  * The sequencer always starts with the second entry.
6155                  * The first entry is embedded in the scb.
6156                  */
6157                 next_scb->sg_list_busaddr = sg_busaddr;
6158                 if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0)
6159                         next_scb->sg_list_busaddr
6160                             += sizeof(struct ahd_dma64_seg);
6161                 else
6162                         next_scb->sg_list_busaddr += sizeof(struct ahd_dma_seg);
6163                 next_scb->ahd_softc = ahd;
6164                 next_scb->flags = SCB_FLAG_NONE;
6165 #ifndef __linux__
6166                 error = ahd_dmamap_create(ahd, ahd->buffer_dmat, /*flags*/0,
6167                                           &next_scb->dmamap);
6168                 if (error != 0) {
6169                         free(next_scb, M_DEVBUF);
6170                         free(pdata, M_DEVBUF);
6171                         break;
6172                 }
6173 #endif
6174                 next_scb->hscb->tag = ahd_htole16(scb_data->numscbs);
6175                 col_tag = scb_data->numscbs ^ 0x100;
6176                 next_scb->col_scb = ahd_find_scb_by_tag(ahd, col_tag);
6177                 if (next_scb->col_scb != NULL)
6178                         next_scb->col_scb->col_scb = next_scb;
6179                 ahd_free_scb(ahd, next_scb);
6180                 hscb++;
6181                 hscb_busaddr += sizeof(*hscb);
6182                 segs += ahd_sglist_size(ahd);
6183                 sg_busaddr += ahd_sglist_size(ahd);
6184                 sense_data += AHD_SENSE_BUFSIZE;
6185                 sense_busaddr += AHD_SENSE_BUFSIZE;
6186                 scb_data->numscbs++;
6187                 scb_data->sense_left--;
6188                 scb_data->scbs_left--;
6189                 scb_data->sgs_left--;
6190         }
6191 }
6192
6193 void
6194 ahd_controller_info(struct ahd_softc *ahd, char *buf)
6195 {
6196         const char *speed;
6197         const char *type;
6198         int len;
6199
6200         len = sprintf(buf, "%s: ", ahd_chip_names[ahd->chip & AHD_CHIPID_MASK]);
6201         buf += len;
6202
6203         speed = "Ultra320 ";
6204         if ((ahd->features & AHD_WIDE) != 0) {
6205                 type = "Wide ";
6206         } else {
6207                 type = "Single ";
6208         }
6209         len = sprintf(buf, "%s%sChannel %c, SCSI Id=%d, ",
6210                       speed, type, ahd->channel, ahd->our_id);
6211         buf += len;
6212
6213         sprintf(buf, "%s, %d SCBs", ahd->bus_description,
6214                 ahd->scb_data.maxhscbs);
6215 }
6216
6217 static const char *channel_strings[] = {
6218         "Primary Low",
6219         "Primary High",
6220         "Secondary Low", 
6221         "Secondary High"
6222 };
6223
6224 static const char *termstat_strings[] = {
6225         "Terminated Correctly",
6226         "Over Terminated",
6227         "Under Terminated",
6228         "Not Configured"
6229 };
6230
6231 /*
6232  * Start the board, ready for normal operation
6233  */
6234 int
6235 ahd_init(struct ahd_softc *ahd)
6236 {
6237         uint8_t         *next_vaddr;
6238         dma_addr_t       next_baddr;
6239         size_t           driver_data_size;
6240         int              i;
6241         int              error;
6242         u_int            warn_user;
6243         uint8_t          current_sensing;
6244         uint8_t          fstat;
6245
6246         AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
6247
6248         ahd->stack_size = ahd_probe_stack_size(ahd);
6249         ahd->saved_stack = malloc(ahd->stack_size * sizeof(uint16_t),
6250                                   M_DEVBUF, M_NOWAIT);
6251         if (ahd->saved_stack == NULL)
6252                 return (ENOMEM);
6253
6254         /*
6255          * Verify that the compiler hasn't over-agressively
6256          * padded important structures.
6257          */
6258         if (sizeof(struct hardware_scb) != 64)
6259                 panic("Hardware SCB size is incorrect");
6260
6261 #ifdef AHD_DEBUG
6262         if ((ahd_debug & AHD_DEBUG_SEQUENCER) != 0)
6263                 ahd->flags |= AHD_SEQUENCER_DEBUG;
6264 #endif
6265
6266         /*
6267          * Default to allowing initiator operations.
6268          */
6269         ahd->flags |= AHD_INITIATORROLE;
6270
6271         /*
6272          * Only allow target mode features if this unit has them enabled.
6273          */
6274         if ((AHD_TMODE_ENABLE & (0x1 << ahd->unit)) == 0)
6275                 ahd->features &= ~AHD_TARGETMODE;
6276
6277 #ifndef __linux__
6278         /* DMA tag for mapping buffers into device visible space. */
6279         if (ahd_dma_tag_create(ahd, ahd->parent_dmat, /*alignment*/1,
6280                                /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
6281                                /*lowaddr*/ahd->flags & AHD_39BIT_ADDRESSING
6282                                         ? (dma_addr_t)0x7FFFFFFFFFULL
6283                                         : BUS_SPACE_MAXADDR_32BIT,
6284                                /*highaddr*/BUS_SPACE_MAXADDR,
6285                                /*filter*/NULL, /*filterarg*/NULL,
6286                                /*maxsize*/(AHD_NSEG - 1) * PAGE_SIZE,
6287                                /*nsegments*/AHD_NSEG,
6288                                /*maxsegsz*/AHD_MAXTRANSFER_SIZE,
6289                                /*flags*/BUS_DMA_ALLOCNOW,
6290                                &ahd->buffer_dmat) != 0) {
6291                 return (ENOMEM);
6292         }
6293 #endif
6294
6295         ahd->init_level++;
6296
6297         /*
6298          * DMA tag for our command fifos and other data in system memory
6299          * the card's sequencer must be able to access.  For initiator
6300          * roles, we need to allocate space for the qoutfifo.  When providing
6301          * for the target mode role, we must additionally provide space for
6302          * the incoming target command fifo.
6303          */
6304         driver_data_size = AHD_SCB_MAX * sizeof(*ahd->qoutfifo)
6305                          + sizeof(struct hardware_scb);
6306         if ((ahd->features & AHD_TARGETMODE) != 0)
6307                 driver_data_size += AHD_TMODE_CMDS * sizeof(struct target_cmd);
6308         if ((ahd->bugs & AHD_PKT_BITBUCKET_BUG) != 0)
6309                 driver_data_size += PKT_OVERRUN_BUFSIZE;
6310         if (ahd_dma_tag_create(ahd, ahd->parent_dmat, /*alignment*/1,
6311                                /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
6312                                /*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
6313                                /*highaddr*/BUS_SPACE_MAXADDR,
6314                                /*filter*/NULL, /*filterarg*/NULL,
6315                                driver_data_size,
6316                                /*nsegments*/1,
6317                                /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
6318                                /*flags*/0, &ahd->shared_data_dmat) != 0) {
6319                 return (ENOMEM);
6320         }
6321
6322         ahd->init_level++;
6323
6324         /* Allocation of driver data */
6325         if (ahd_dmamem_alloc(ahd, ahd->shared_data_dmat,
6326                              (void **)&ahd->shared_data_map.vaddr,
6327                              BUS_DMA_NOWAIT,
6328                              &ahd->shared_data_map.dmamap) != 0) {
6329                 return (ENOMEM);
6330         }
6331
6332         ahd->init_level++;
6333
6334         /* And permanently map it in */
6335         ahd_dmamap_load(ahd, ahd->shared_data_dmat, ahd->shared_data_map.dmamap,
6336                         ahd->shared_data_map.vaddr, driver_data_size,
6337                         ahd_dmamap_cb, &ahd->shared_data_map.physaddr,
6338                         /*flags*/0);
6339         ahd->qoutfifo = (struct ahd_completion *)ahd->shared_data_map.vaddr;
6340         next_vaddr = (uint8_t *)&ahd->qoutfifo[AHD_QOUT_SIZE];
6341         next_baddr = ahd->shared_data_map.physaddr
6342                    + AHD_QOUT_SIZE*sizeof(struct ahd_completion);
6343         if ((ahd->features & AHD_TARGETMODE) != 0) {
6344                 ahd->targetcmds = (struct target_cmd *)next_vaddr;
6345                 next_vaddr += AHD_TMODE_CMDS * sizeof(struct target_cmd);
6346                 next_baddr += AHD_TMODE_CMDS * sizeof(struct target_cmd);
6347         }
6348
6349         if ((ahd->bugs & AHD_PKT_BITBUCKET_BUG) != 0) {
6350                 ahd->overrun_buf = next_vaddr;
6351                 next_vaddr += PKT_OVERRUN_BUFSIZE;
6352                 next_baddr += PKT_OVERRUN_BUFSIZE;
6353         }
6354
6355         /*
6356          * We need one SCB to serve as the "next SCB".  Since the
6357          * tag identifier in this SCB will never be used, there is
6358          * no point in using a valid HSCB tag from an SCB pulled from
6359          * the standard free pool.  So, we allocate this "sentinel"
6360          * specially from the DMA safe memory chunk used for the QOUTFIFO.
6361          */
6362         ahd->next_queued_hscb = (struct hardware_scb *)next_vaddr;
6363         ahd->next_queued_hscb_map = &ahd->shared_data_map;
6364         ahd->next_queued_hscb->hscb_busaddr = ahd_htole32(next_baddr);
6365
6366         ahd->init_level++;
6367
6368         /* Allocate SCB data now that buffer_dmat is initialized */
6369         if (ahd_init_scbdata(ahd) != 0)
6370                 return (ENOMEM);
6371
6372         if ((ahd->flags & AHD_INITIATORROLE) == 0)
6373                 ahd->flags &= ~AHD_RESET_BUS_A;
6374
6375         /*
6376          * Before committing these settings to the chip, give
6377          * the OSM one last chance to modify our configuration.
6378          */
6379         ahd_platform_init(ahd);
6380
6381         /* Bring up the chip. */
6382         ahd_chip_init(ahd);
6383
6384         AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
6385
6386         if ((ahd->flags & AHD_CURRENT_SENSING) == 0)
6387                 goto init_done;
6388
6389         /*
6390          * Verify termination based on current draw and
6391          * warn user if the bus is over/under terminated.
6392          */
6393         error = ahd_write_flexport(ahd, FLXADDR_ROMSTAT_CURSENSECTL,
6394                                    CURSENSE_ENB);
6395         if (error != 0) {
6396                 printf("%s: current sensing timeout 1\n", ahd_name(ahd));
6397                 goto init_done;
6398         }
6399         for (i = 20, fstat = FLX_FSTAT_BUSY;
6400              (fstat & FLX_FSTAT_BUSY) != 0 && i; i--) {
6401                 error = ahd_read_flexport(ahd, FLXADDR_FLEXSTAT, &fstat);
6402                 if (error != 0) {
6403                         printf("%s: current sensing timeout 2\n",
6404                                ahd_name(ahd));
6405                         goto init_done;
6406                 }
6407         }
6408         if (i == 0) {
6409                 printf("%s: Timedout during current-sensing test\n",
6410                        ahd_name(ahd));
6411                 goto init_done;
6412         }
6413
6414         /* Latch Current Sensing status. */
6415         error = ahd_read_flexport(ahd, FLXADDR_CURRENT_STAT, &current_sensing);
6416         if (error != 0) {
6417                 printf("%s: current sensing timeout 3\n", ahd_name(ahd));
6418                 goto init_done;
6419         }
6420
6421         /* Diable current sensing. */
6422         ahd_write_flexport(ahd, FLXADDR_ROMSTAT_CURSENSECTL, 0);
6423
6424 #ifdef AHD_DEBUG
6425         if ((ahd_debug & AHD_SHOW_TERMCTL) != 0) {
6426                 printf("%s: current_sensing == 0x%x\n",
6427                        ahd_name(ahd), current_sensing);
6428         }
6429 #endif
6430         warn_user = 0;
6431         for (i = 0; i < 4; i++, current_sensing >>= FLX_CSTAT_SHIFT) {
6432                 u_int term_stat;
6433
6434                 term_stat = (current_sensing & FLX_CSTAT_MASK);
6435                 switch (term_stat) {
6436                 case FLX_CSTAT_OVER:
6437                 case FLX_CSTAT_UNDER:
6438                         warn_user++;
6439                 case FLX_CSTAT_INVALID:
6440                 case FLX_CSTAT_OKAY:
6441                         if (warn_user == 0 && bootverbose == 0)
6442                                 break;
6443                         printf("%s: %s Channel %s\n", ahd_name(ahd),
6444                                channel_strings[i], termstat_strings[term_stat]);
6445                         break;
6446                 }
6447         }
6448         if (warn_user) {
6449                 printf("%s: WARNING. Termination is not configured correctly.\n"
6450                        "%s: WARNING. SCSI bus operations may FAIL.\n",
6451                        ahd_name(ahd), ahd_name(ahd));
6452         }
6453 init_done:
6454         ahd_restart(ahd);
6455         ahd_timer_reset(&ahd->stat_timer, AHD_STAT_UPDATE_US,
6456                         ahd_stat_timer, ahd);
6457         return (0);
6458 }
6459
6460 /*
6461  * (Re)initialize chip state after a chip reset.
6462  */
6463 static void
6464 ahd_chip_init(struct ahd_softc *ahd)
6465 {
6466         uint32_t busaddr;
6467         u_int    sxfrctl1;
6468         u_int    scsiseq_template;
6469         u_int    wait;
6470         u_int    i;
6471         u_int    target;
6472
6473         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
6474         /*
6475          * Take the LED out of diagnostic mode
6476          */
6477         ahd_outb(ahd, SBLKCTL, ahd_inb(ahd, SBLKCTL) & ~(DIAGLEDEN|DIAGLEDON));
6478
6479         /*
6480          * Return HS_MAILBOX to its default value.
6481          */
6482         ahd->hs_mailbox = 0;
6483         ahd_outb(ahd, HS_MAILBOX, 0);
6484
6485         /* Set the SCSI Id, SXFRCTL0, SXFRCTL1, and SIMODE1. */
6486         ahd_outb(ahd, IOWNID, ahd->our_id);
6487         ahd_outb(ahd, TOWNID, ahd->our_id);
6488         sxfrctl1 = (ahd->flags & AHD_TERM_ENB_A) != 0 ? STPWEN : 0;
6489         sxfrctl1 |= (ahd->flags & AHD_SPCHK_ENB_A) != 0 ? ENSPCHK : 0;
6490         if ((ahd->bugs & AHD_LONG_SETIMO_BUG)
6491          && (ahd->seltime != STIMESEL_MIN)) {
6492                 /*
6493                  * The selection timer duration is twice as long
6494                  * as it should be.  Halve it by adding "1" to
6495                  * the user specified setting.
6496                  */
6497                 sxfrctl1 |= ahd->seltime + STIMESEL_BUG_ADJ;
6498         } else {
6499                 sxfrctl1 |= ahd->seltime;
6500         }
6501                 
6502         ahd_outb(ahd, SXFRCTL0, DFON);
6503         ahd_outb(ahd, SXFRCTL1, sxfrctl1|ahd->seltime|ENSTIMER|ACTNEGEN);
6504         ahd_outb(ahd, SIMODE1, ENSELTIMO|ENSCSIRST|ENSCSIPERR);
6505
6506         /*
6507          * Now that termination is set, wait for up
6508          * to 500ms for our transceivers to settle.  If
6509          * the adapter does not have a cable attached,
6510          * the transceivers may never settle, so don't
6511          * complain if we fail here.
6512          */
6513         for (wait = 10000;
6514              (ahd_inb(ahd, SBLKCTL) & (ENAB40|ENAB20)) == 0 && wait;
6515              wait--)
6516                 ahd_delay(100);
6517
6518         /* Clear any false bus resets due to the transceivers settling */
6519         ahd_outb(ahd, CLRSINT1, CLRSCSIRSTI);
6520         ahd_outb(ahd, CLRINT, CLRSCSIINT);
6521
6522         /* Initialize mode specific S/G state. */
6523         for (i = 0; i < 2; i++) {
6524                 ahd_set_modes(ahd, AHD_MODE_DFF0 + i, AHD_MODE_DFF0 + i);
6525                 ahd_outb(ahd, LONGJMP_ADDR + 1, INVALID_ADDR);
6526                 ahd_outb(ahd, SG_STATE, 0);
6527                 ahd_outb(ahd, CLRSEQINTSRC, 0xFF);
6528                 ahd_outb(ahd, SEQIMODE,
6529                          ENSAVEPTRS|ENCFG4DATA|ENCFG4ISTAT
6530                         |ENCFG4TSTAT|ENCFG4ICMD|ENCFG4TCMD);
6531         }
6532
6533         ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
6534         ahd_outb(ahd, DSCOMMAND0, ahd_inb(ahd, DSCOMMAND0)|MPARCKEN|CACHETHEN);
6535         ahd_outb(ahd, DFF_THRSH, RD_DFTHRSH_75|WR_DFTHRSH_75);
6536         ahd_outb(ahd, SIMODE0, ENIOERR|ENOVERRUN);
6537         ahd_outb(ahd, SIMODE3, ENNTRAMPERR|ENOSRAMPERR);
6538         if ((ahd->bugs & AHD_BUSFREEREV_BUG) != 0) {
6539                 ahd_outb(ahd, OPTIONMODE, AUTOACKEN|AUTO_MSGOUT_DE);
6540         } else {
6541                 ahd_outb(ahd, OPTIONMODE, AUTOACKEN|BUSFREEREV|AUTO_MSGOUT_DE);
6542         }
6543         ahd_outb(ahd, SCSCHKN, CURRFIFODEF|WIDERESEN|SHVALIDSTDIS);
6544         if ((ahd->chip & AHD_BUS_MASK) == AHD_PCIX)
6545                 /*
6546                  * Do not issue a target abort when a split completion
6547                  * error occurs.  Let our PCIX interrupt handler deal
6548                  * with it instead. H2A4 Razor #625
6549                  */
6550                 ahd_outb(ahd, PCIXCTL, ahd_inb(ahd, PCIXCTL) | SPLTSTADIS);
6551
6552         if ((ahd->bugs & AHD_LQOOVERRUN_BUG) != 0)
6553                 ahd_outb(ahd, LQOSCSCTL, LQONOCHKOVER);
6554
6555         /*
6556          * Tweak IOCELL settings.
6557          */
6558         if ((ahd->flags & AHD_HP_BOARD) != 0) {
6559                 for (i = 0; i < NUMDSPS; i++) {
6560                         ahd_outb(ahd, DSPSELECT, i);
6561                         ahd_outb(ahd, WRTBIASCTL, WRTBIASCTL_HP_DEFAULT);
6562                 }
6563 #ifdef AHD_DEBUG
6564                 if ((ahd_debug & AHD_SHOW_MISC) != 0)
6565                         printf("%s: WRTBIASCTL now 0x%x\n", ahd_name(ahd),
6566                                WRTBIASCTL_HP_DEFAULT);
6567 #endif
6568         }
6569         ahd_setup_iocell_workaround(ahd);
6570
6571         /*
6572          * Enable LQI Manager interrupts.
6573          */
6574         ahd_outb(ahd, LQIMODE1, ENLQIPHASE_LQ|ENLQIPHASE_NLQ|ENLIQABORT
6575                               | ENLQICRCI_LQ|ENLQICRCI_NLQ|ENLQIBADLQI
6576                               | ENLQIOVERI_LQ|ENLQIOVERI_NLQ);
6577         ahd_outb(ahd, LQOMODE0, ENLQOATNLQ|ENLQOATNPKT|ENLQOTCRC);
6578         /*
6579          * We choose to have the sequencer catch LQOPHCHGINPKT errors
6580          * manually for the command phase at the start of a packetized
6581          * selection case.  ENLQOBUSFREE should be made redundant by
6582          * the BUSFREE interrupt, but it seems that some LQOBUSFREE
6583          * events fail to assert the BUSFREE interrupt so we must
6584          * also enable LQOBUSFREE interrupts.
6585          */
6586         ahd_outb(ahd, LQOMODE1, ENLQOBUSFREE);
6587
6588         /*
6589          * Setup sequencer interrupt handlers.
6590          */
6591         ahd_outw(ahd, INTVEC1_ADDR, ahd_resolve_seqaddr(ahd, LABEL_seq_isr));
6592         ahd_outw(ahd, INTVEC2_ADDR, ahd_resolve_seqaddr(ahd, LABEL_timer_isr));
6593
6594         /*
6595          * Setup SCB Offset registers.
6596          */
6597         if ((ahd->bugs & AHD_PKT_LUN_BUG) != 0) {
6598                 ahd_outb(ahd, LUNPTR, offsetof(struct hardware_scb,
6599                          pkt_long_lun));
6600         } else {
6601                 ahd_outb(ahd, LUNPTR, offsetof(struct hardware_scb, lun));
6602         }
6603         ahd_outb(ahd, CMDLENPTR, offsetof(struct hardware_scb, cdb_len));
6604         ahd_outb(ahd, ATTRPTR, offsetof(struct hardware_scb, task_attribute));
6605         ahd_outb(ahd, FLAGPTR, offsetof(struct hardware_scb, task_management));
6606         ahd_outb(ahd, CMDPTR, offsetof(struct hardware_scb,
6607                                        shared_data.idata.cdb));
6608         ahd_outb(ahd, QNEXTPTR,
6609                  offsetof(struct hardware_scb, next_hscb_busaddr));
6610         ahd_outb(ahd, ABRTBITPTR, MK_MESSAGE_BIT_OFFSET);
6611         ahd_outb(ahd, ABRTBYTEPTR, offsetof(struct hardware_scb, control));
6612         if ((ahd->bugs & AHD_PKT_LUN_BUG) != 0) {
6613                 ahd_outb(ahd, LUNLEN,
6614                          sizeof(ahd->next_queued_hscb->pkt_long_lun) - 1);
6615         } else {
6616                 ahd_outb(ahd, LUNLEN, LUNLEN_SINGLE_LEVEL_LUN);
6617         }
6618         ahd_outb(ahd, CDBLIMIT, SCB_CDB_LEN_PTR - 1);
6619         ahd_outb(ahd, MAXCMD, 0xFF);
6620         ahd_outb(ahd, SCBAUTOPTR,
6621                  AUSCBPTR_EN | offsetof(struct hardware_scb, tag));
6622
6623         /* We haven't been enabled for target mode yet. */
6624         ahd_outb(ahd, MULTARGID, 0);
6625         ahd_outb(ahd, MULTARGID + 1, 0);
6626
6627         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
6628         /* Initialize the negotiation table. */
6629         if ((ahd->features & AHD_NEW_IOCELL_OPTS) == 0) {
6630                 /*
6631                  * Clear the spare bytes in the neg table to avoid
6632                  * spurious parity errors.
6633                  */
6634                 for (target = 0; target < AHD_NUM_TARGETS; target++) {
6635                         ahd_outb(ahd, NEGOADDR, target);
6636                         ahd_outb(ahd, ANNEXCOL, AHD_ANNEXCOL_PER_DEV0);
6637                         for (i = 0; i < AHD_NUM_PER_DEV_ANNEXCOLS; i++)
6638                                 ahd_outb(ahd, ANNEXDAT, 0);
6639                 }
6640         }
6641         for (target = 0; target < AHD_NUM_TARGETS; target++) {
6642                 struct   ahd_devinfo devinfo;
6643                 struct   ahd_initiator_tinfo *tinfo;
6644                 struct   ahd_tmode_tstate *tstate;
6645
6646                 tinfo = ahd_fetch_transinfo(ahd, 'A', ahd->our_id,
6647                                             target, &tstate);
6648                 ahd_compile_devinfo(&devinfo, ahd->our_id,
6649                                     target, CAM_LUN_WILDCARD,
6650                                     'A', ROLE_INITIATOR);
6651                 ahd_update_neg_table(ahd, &devinfo, &tinfo->curr);
6652         }
6653
6654         ahd_outb(ahd, CLRSINT3, NTRAMPERR|OSRAMPERR);
6655         ahd_outb(ahd, CLRINT, CLRSCSIINT);
6656
6657 #ifdef NEEDS_MORE_TESTING
6658         /*
6659          * Always enable abort on incoming L_Qs if this feature is
6660          * supported.  We use this to catch invalid SCB references.
6661          */
6662         if ((ahd->bugs & AHD_ABORT_LQI_BUG) == 0)
6663                 ahd_outb(ahd, LQCTL1, ABORTPENDING);
6664         else
6665 #endif
6666                 ahd_outb(ahd, LQCTL1, 0);
6667
6668         /* All of our queues are empty */
6669         ahd->qoutfifonext = 0;
6670         ahd->qoutfifonext_valid_tag = QOUTFIFO_ENTRY_VALID;
6671         ahd_outb(ahd, QOUTFIFO_ENTRY_VALID_TAG, QOUTFIFO_ENTRY_VALID);
6672         for (i = 0; i < AHD_QOUT_SIZE; i++)
6673                 ahd->qoutfifo[i].valid_tag = 0;
6674         ahd_sync_qoutfifo(ahd, BUS_DMASYNC_PREREAD);
6675
6676         ahd->qinfifonext = 0;
6677         for (i = 0; i < AHD_QIN_SIZE; i++)
6678                 ahd->qinfifo[i] = SCB_LIST_NULL;
6679
6680         if ((ahd->features & AHD_TARGETMODE) != 0) {
6681                 /* All target command blocks start out invalid. */
6682                 for (i = 0; i < AHD_TMODE_CMDS; i++)
6683                         ahd->targetcmds[i].cmd_valid = 0;
6684                 ahd_sync_tqinfifo(ahd, BUS_DMASYNC_PREREAD);
6685                 ahd->tqinfifonext = 1;
6686                 ahd_outb(ahd, KERNEL_TQINPOS, ahd->tqinfifonext - 1);
6687                 ahd_outb(ahd, TQINPOS, ahd->tqinfifonext);
6688         }
6689
6690         /* Initialize Scratch Ram. */
6691         ahd_outb(ahd, SEQ_FLAGS, 0);
6692         ahd_outb(ahd, SEQ_FLAGS2, 0);
6693
6694         /* We don't have any waiting selections */
6695         ahd_outw(ahd, WAITING_TID_HEAD, SCB_LIST_NULL);
6696         ahd_outw(ahd, WAITING_TID_TAIL, SCB_LIST_NULL);
6697         ahd_outw(ahd, MK_MESSAGE_SCB, SCB_LIST_NULL);
6698         ahd_outw(ahd, MK_MESSAGE_SCSIID, 0xFF);
6699         for (i = 0; i < AHD_NUM_TARGETS; i++)
6700                 ahd_outw(ahd, WAITING_SCB_TAILS + (2 * i), SCB_LIST_NULL);
6701
6702         /*
6703          * Nobody is waiting to be DMAed into the QOUTFIFO.
6704          */
6705         ahd_outw(ahd, COMPLETE_SCB_HEAD, SCB_LIST_NULL);
6706         ahd_outw(ahd, COMPLETE_SCB_DMAINPROG_HEAD, SCB_LIST_NULL);
6707         ahd_outw(ahd, COMPLETE_DMA_SCB_HEAD, SCB_LIST_NULL);
6708         ahd_outw(ahd, COMPLETE_DMA_SCB_TAIL, SCB_LIST_NULL);
6709         ahd_outw(ahd, COMPLETE_ON_QFREEZE_HEAD, SCB_LIST_NULL);
6710
6711         /*
6712          * The Freeze Count is 0.
6713          */
6714         ahd->qfreeze_cnt = 0;
6715         ahd_outw(ahd, QFREEZE_COUNT, 0);
6716         ahd_outw(ahd, KERNEL_QFREEZE_COUNT, 0);
6717
6718         /*
6719          * Tell the sequencer where it can find our arrays in memory.
6720          */
6721         busaddr = ahd->shared_data_map.physaddr;
6722         ahd_outl(ahd, SHARED_DATA_ADDR, busaddr);
6723         ahd_outl(ahd, QOUTFIFO_NEXT_ADDR, busaddr);
6724
6725         /*
6726          * Setup the allowed SCSI Sequences based on operational mode.
6727          * If we are a target, we'll enable select in operations once
6728          * we've had a lun enabled.
6729          */
6730         scsiseq_template = ENAUTOATNP;
6731         if ((ahd->flags & AHD_INITIATORROLE) != 0)
6732                 scsiseq_template |= ENRSELI;
6733         ahd_outb(ahd, SCSISEQ_TEMPLATE, scsiseq_template);
6734
6735         /* There are no busy SCBs yet. */
6736         for (target = 0; target < AHD_NUM_TARGETS; target++) {
6737                 int lun;
6738
6739                 for (lun = 0; lun < AHD_NUM_LUNS_NONPKT; lun++)
6740                         ahd_unbusy_tcl(ahd, BUILD_TCL_RAW(target, 'A', lun));
6741         }
6742
6743         /*
6744          * Initialize the group code to command length table.
6745          * Vendor Unique codes are set to 0 so we only capture
6746          * the first byte of the cdb.  These can be overridden
6747          * when target mode is enabled.
6748          */
6749         ahd_outb(ahd, CMDSIZE_TABLE, 5);
6750         ahd_outb(ahd, CMDSIZE_TABLE + 1, 9);
6751         ahd_outb(ahd, CMDSIZE_TABLE + 2, 9);
6752         ahd_outb(ahd, CMDSIZE_TABLE + 3, 0);
6753         ahd_outb(ahd, CMDSIZE_TABLE + 4, 15);
6754         ahd_outb(ahd, CMDSIZE_TABLE + 5, 11);
6755         ahd_outb(ahd, CMDSIZE_TABLE + 6, 0);
6756         ahd_outb(ahd, CMDSIZE_TABLE + 7, 0);
6757                 
6758         /* Tell the sequencer of our initial queue positions */
6759         ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
6760         ahd_outb(ahd, QOFF_CTLSTA, SCB_QSIZE_512);
6761         ahd->qinfifonext = 0;
6762         ahd_set_hnscb_qoff(ahd, ahd->qinfifonext);
6763         ahd_set_hescb_qoff(ahd, 0);
6764         ahd_set_snscb_qoff(ahd, 0);
6765         ahd_set_sescb_qoff(ahd, 0);
6766         ahd_set_sdscb_qoff(ahd, 0);
6767
6768         /*
6769          * Tell the sequencer which SCB will be the next one it receives.
6770          */
6771         busaddr = ahd_le32toh(ahd->next_queued_hscb->hscb_busaddr);
6772         ahd_outl(ahd, NEXT_QUEUED_SCB_ADDR, busaddr);
6773
6774         /*
6775          * Default to coalescing disabled.
6776          */
6777         ahd_outw(ahd, INT_COALESCING_CMDCOUNT, 0);
6778         ahd_outw(ahd, CMDS_PENDING, 0);
6779         ahd_update_coalescing_values(ahd, ahd->int_coalescing_timer,
6780                                      ahd->int_coalescing_maxcmds,
6781                                      ahd->int_coalescing_mincmds);
6782         ahd_enable_coalescing(ahd, FALSE);
6783
6784         ahd_loadseq(ahd);
6785         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
6786
6787         if (ahd->features & AHD_AIC79XXB_SLOWCRC) {
6788                 u_int negodat3 = ahd_inb(ahd, NEGCONOPTS);
6789
6790                 negodat3 |= ENSLOWCRC;
6791                 ahd_outb(ahd, NEGCONOPTS, negodat3);
6792                 negodat3 = ahd_inb(ahd, NEGCONOPTS);
6793                 if (!(negodat3 & ENSLOWCRC))
6794                         printf("aic79xx: failed to set the SLOWCRC bit\n");
6795                 else
6796                         printf("aic79xx: SLOWCRC bit set\n");
6797         }
6798 }
6799
6800 /*
6801  * Setup default device and controller settings.
6802  * This should only be called if our probe has
6803  * determined that no configuration data is available.
6804  */
6805 int
6806 ahd_default_config(struct ahd_softc *ahd)
6807 {
6808         int     targ;
6809
6810         ahd->our_id = 7;
6811
6812         /*
6813          * Allocate a tstate to house information for our
6814          * initiator presence on the bus as well as the user
6815          * data for any target mode initiator.
6816          */
6817         if (ahd_alloc_tstate(ahd, ahd->our_id, 'A') == NULL) {
6818                 printf("%s: unable to allocate ahd_tmode_tstate.  "
6819                        "Failing attach\n", ahd_name(ahd));
6820                 return (ENOMEM);
6821         }
6822
6823         for (targ = 0; targ < AHD_NUM_TARGETS; targ++) {
6824                 struct   ahd_devinfo devinfo;
6825                 struct   ahd_initiator_tinfo *tinfo;
6826                 struct   ahd_tmode_tstate *tstate;
6827                 uint16_t target_mask;
6828
6829                 tinfo = ahd_fetch_transinfo(ahd, 'A', ahd->our_id,
6830                                             targ, &tstate);
6831                 /*
6832                  * We support SPC2 and SPI4.
6833                  */
6834                 tinfo->user.protocol_version = 4;
6835                 tinfo->user.transport_version = 4;
6836
6837                 target_mask = 0x01 << targ;
6838                 ahd->user_discenable |= target_mask;
6839                 tstate->discenable |= target_mask;
6840                 ahd->user_tagenable |= target_mask;
6841 #ifdef AHD_FORCE_160
6842                 tinfo->user.period = AHD_SYNCRATE_DT;
6843 #else
6844                 tinfo->user.period = AHD_SYNCRATE_160;
6845 #endif
6846                 tinfo->user.offset = MAX_OFFSET;
6847                 tinfo->user.ppr_options = MSG_EXT_PPR_RD_STRM
6848                                         | MSG_EXT_PPR_WR_FLOW
6849                                         | MSG_EXT_PPR_HOLD_MCS
6850                                         | MSG_EXT_PPR_IU_REQ
6851                                         | MSG_EXT_PPR_QAS_REQ
6852                                         | MSG_EXT_PPR_DT_REQ;
6853                 if ((ahd->features & AHD_RTI) != 0)
6854                         tinfo->user.ppr_options |= MSG_EXT_PPR_RTI;
6855
6856                 tinfo->user.width = MSG_EXT_WDTR_BUS_16_BIT;
6857
6858                 /*
6859                  * Start out Async/Narrow/Untagged and with
6860                  * conservative protocol support.
6861                  */
6862                 tinfo->goal.protocol_version = 2;
6863                 tinfo->goal.transport_version = 2;
6864                 tinfo->curr.protocol_version = 2;
6865                 tinfo->curr.transport_version = 2;
6866                 ahd_compile_devinfo(&devinfo, ahd->our_id,
6867                                     targ, CAM_LUN_WILDCARD,
6868                                     'A', ROLE_INITIATOR);
6869                 tstate->tagenable &= ~target_mask;
6870                 ahd_set_width(ahd, &devinfo, MSG_EXT_WDTR_BUS_8_BIT,
6871                               AHD_TRANS_CUR|AHD_TRANS_GOAL, /*paused*/TRUE);
6872                 ahd_set_syncrate(ahd, &devinfo, /*period*/0, /*offset*/0,
6873                                  /*ppr_options*/0, AHD_TRANS_CUR|AHD_TRANS_GOAL,
6874                                  /*paused*/TRUE);
6875         }
6876         return (0);
6877 }
6878
6879 /*
6880  * Parse device configuration information.
6881  */
6882 int
6883 ahd_parse_cfgdata(struct ahd_softc *ahd, struct seeprom_config *sc)
6884 {
6885         int targ;
6886         int max_targ;
6887
6888         max_targ = sc->max_targets & CFMAXTARG;
6889         ahd->our_id = sc->brtime_id & CFSCSIID;
6890
6891         /*
6892          * Allocate a tstate to house information for our
6893          * initiator presence on the bus as well as the user
6894          * data for any target mode initiator.
6895          */
6896         if (ahd_alloc_tstate(ahd, ahd->our_id, 'A') == NULL) {
6897                 printf("%s: unable to allocate ahd_tmode_tstate.  "
6898                        "Failing attach\n", ahd_name(ahd));
6899                 return (ENOMEM);
6900         }
6901
6902         for (targ = 0; targ < max_targ; targ++) {
6903                 struct   ahd_devinfo devinfo;
6904                 struct   ahd_initiator_tinfo *tinfo;
6905                 struct   ahd_transinfo *user_tinfo;
6906                 struct   ahd_tmode_tstate *tstate;
6907                 uint16_t target_mask;
6908
6909                 tinfo = ahd_fetch_transinfo(ahd, 'A', ahd->our_id,
6910                                             targ, &tstate);
6911                 user_tinfo = &tinfo->user;
6912
6913                 /*
6914                  * We support SPC2 and SPI4.
6915                  */
6916                 tinfo->user.protocol_version = 4;
6917                 tinfo->user.transport_version = 4;
6918
6919                 target_mask = 0x01 << targ;
6920                 ahd->user_discenable &= ~target_mask;
6921                 tstate->discenable &= ~target_mask;
6922                 ahd->user_tagenable &= ~target_mask;
6923                 if (sc->device_flags[targ] & CFDISC) {
6924                         tstate->discenable |= target_mask;
6925                         ahd->user_discenable |= target_mask;
6926                         ahd->user_tagenable |= target_mask;
6927                 } else {
6928                         /*
6929                          * Cannot be packetized without disconnection.
6930                          */
6931                         sc->device_flags[targ] &= ~CFPACKETIZED;
6932                 }
6933
6934                 user_tinfo->ppr_options = 0;
6935                 user_tinfo->period = (sc->device_flags[targ] & CFXFER);
6936                 if (user_tinfo->period < CFXFER_ASYNC) {
6937                         if (user_tinfo->period <= AHD_PERIOD_10MHz)
6938                                 user_tinfo->ppr_options |= MSG_EXT_PPR_DT_REQ;
6939                         user_tinfo->offset = MAX_OFFSET;
6940                 } else  {
6941                         user_tinfo->offset = 0;
6942                         user_tinfo->period = AHD_ASYNC_XFER_PERIOD;
6943                 }
6944 #ifdef AHD_FORCE_160
6945                 if (user_tinfo->period <= AHD_SYNCRATE_160)
6946                         user_tinfo->period = AHD_SYNCRATE_DT;
6947 #endif
6948
6949                 if ((sc->device_flags[targ] & CFPACKETIZED) != 0) {
6950                         user_tinfo->ppr_options |= MSG_EXT_PPR_RD_STRM
6951                                                 |  MSG_EXT_PPR_WR_FLOW
6952                                                 |  MSG_EXT_PPR_HOLD_MCS
6953                                                 |  MSG_EXT_PPR_IU_REQ;
6954                         if ((ahd->features & AHD_RTI) != 0)
6955                                 user_tinfo->ppr_options |= MSG_EXT_PPR_RTI;
6956                 }
6957
6958                 if ((sc->device_flags[targ] & CFQAS) != 0)
6959                         user_tinfo->ppr_options |= MSG_EXT_PPR_QAS_REQ;
6960
6961                 if ((sc->device_flags[targ] & CFWIDEB) != 0)
6962                         user_tinfo->width = MSG_EXT_WDTR_BUS_16_BIT;
6963                 else
6964                         user_tinfo->width = MSG_EXT_WDTR_BUS_8_BIT;
6965 #ifdef AHD_DEBUG
6966                 if ((ahd_debug & AHD_SHOW_MISC) != 0)
6967                         printf("(%d): %x:%x:%x:%x\n", targ, user_tinfo->width,
6968                                user_tinfo->period, user_tinfo->offset,
6969                                user_tinfo->ppr_options);
6970 #endif
6971                 /*
6972                  * Start out Async/Narrow/Untagged and with
6973                  * conservative protocol support.
6974                  */
6975                 tstate->tagenable &= ~target_mask;
6976                 tinfo->goal.protocol_version = 2;
6977                 tinfo->goal.transport_version = 2;
6978                 tinfo->curr.protocol_version = 2;
6979                 tinfo->curr.transport_version = 2;
6980                 ahd_compile_devinfo(&devinfo, ahd->our_id,
6981                                     targ, CAM_LUN_WILDCARD,
6982                                     'A', ROLE_INITIATOR);
6983                 ahd_set_width(ahd, &devinfo, MSG_EXT_WDTR_BUS_8_BIT,
6984                               AHD_TRANS_CUR|AHD_TRANS_GOAL, /*paused*/TRUE);
6985                 ahd_set_syncrate(ahd, &devinfo, /*period*/0, /*offset*/0,
6986                                  /*ppr_options*/0, AHD_TRANS_CUR|AHD_TRANS_GOAL,
6987                                  /*paused*/TRUE);
6988         }
6989
6990         ahd->flags &= ~AHD_SPCHK_ENB_A;
6991         if (sc->bios_control & CFSPARITY)
6992                 ahd->flags |= AHD_SPCHK_ENB_A;
6993
6994         ahd->flags &= ~AHD_RESET_BUS_A;
6995         if (sc->bios_control & CFRESETB)
6996                 ahd->flags |= AHD_RESET_BUS_A;
6997
6998         ahd->flags &= ~AHD_EXTENDED_TRANS_A;
6999         if (sc->bios_control & CFEXTEND)
7000                 ahd->flags |= AHD_EXTENDED_TRANS_A;
7001
7002         ahd->flags &= ~AHD_BIOS_ENABLED;
7003         if ((sc->bios_control & CFBIOSSTATE) == CFBS_ENABLED)
7004                 ahd->flags |= AHD_BIOS_ENABLED;
7005
7006         ahd->flags &= ~AHD_STPWLEVEL_A;
7007         if ((sc->adapter_control & CFSTPWLEVEL) != 0)
7008                 ahd->flags |= AHD_STPWLEVEL_A;
7009
7010         return (0);
7011 }
7012
7013 /*
7014  * Parse device configuration information.
7015  */
7016 int
7017 ahd_parse_vpddata(struct ahd_softc *ahd, struct vpd_config *vpd)
7018 {
7019         int error;
7020
7021         error = ahd_verify_vpd_cksum(vpd);
7022         if (error == 0)
7023                 return (EINVAL);
7024         if ((vpd->bios_flags & VPDBOOTHOST) != 0)
7025                 ahd->flags |= AHD_BOOT_CHANNEL;
7026         return (0);
7027 }
7028
7029 void
7030 ahd_intr_enable(struct ahd_softc *ahd, int enable)
7031 {
7032         u_int hcntrl;
7033
7034         hcntrl = ahd_inb(ahd, HCNTRL);
7035         hcntrl &= ~INTEN;
7036         ahd->pause &= ~INTEN;
7037         ahd->unpause &= ~INTEN;
7038         if (enable) {
7039                 hcntrl |= INTEN;
7040                 ahd->pause |= INTEN;
7041                 ahd->unpause |= INTEN;
7042         }
7043         ahd_outb(ahd, HCNTRL, hcntrl);
7044 }
7045
7046 static void
7047 ahd_update_coalescing_values(struct ahd_softc *ahd, u_int timer, u_int maxcmds,
7048                              u_int mincmds)
7049 {
7050         if (timer > AHD_TIMER_MAX_US)
7051                 timer = AHD_TIMER_MAX_US;
7052         ahd->int_coalescing_timer = timer;
7053
7054         if (maxcmds > AHD_INT_COALESCING_MAXCMDS_MAX)
7055                 maxcmds = AHD_INT_COALESCING_MAXCMDS_MAX;
7056         if (mincmds > AHD_INT_COALESCING_MINCMDS_MAX)
7057                 mincmds = AHD_INT_COALESCING_MINCMDS_MAX;
7058         ahd->int_coalescing_maxcmds = maxcmds;
7059         ahd_outw(ahd, INT_COALESCING_TIMER, timer / AHD_TIMER_US_PER_TICK);
7060         ahd_outb(ahd, INT_COALESCING_MAXCMDS, -maxcmds);
7061         ahd_outb(ahd, INT_COALESCING_MINCMDS, -mincmds);
7062 }
7063
7064 static void
7065 ahd_enable_coalescing(struct ahd_softc *ahd, int enable)
7066 {
7067
7068         ahd->hs_mailbox &= ~ENINT_COALESCE;
7069         if (enable)
7070                 ahd->hs_mailbox |= ENINT_COALESCE;
7071         ahd_outb(ahd, HS_MAILBOX, ahd->hs_mailbox);
7072         ahd_flush_device_writes(ahd);
7073         ahd_run_qoutfifo(ahd);
7074 }
7075
7076 /*
7077  * Ensure that the card is paused in a location
7078  * outside of all critical sections and that all
7079  * pending work is completed prior to returning.
7080  * This routine should only be called from outside
7081  * an interrupt context.
7082  */
7083 void
7084 ahd_pause_and_flushwork(struct ahd_softc *ahd)
7085 {
7086         u_int intstat;
7087         u_int maxloops;
7088
7089         maxloops = 1000;
7090         ahd->flags |= AHD_ALL_INTERRUPTS;
7091         ahd_pause(ahd);
7092         /*
7093          * Freeze the outgoing selections.  We do this only
7094          * until we are safely paused without further selections
7095          * pending.
7096          */
7097         ahd->qfreeze_cnt--;
7098         ahd_outw(ahd, KERNEL_QFREEZE_COUNT, ahd->qfreeze_cnt);
7099         ahd_outb(ahd, SEQ_FLAGS2, ahd_inb(ahd, SEQ_FLAGS2) | SELECTOUT_QFROZEN);
7100         do {
7101
7102                 ahd_unpause(ahd);
7103                 /*
7104                  * Give the sequencer some time to service
7105                  * any active selections.
7106                  */
7107                 ahd_delay(500);
7108
7109                 ahd_intr(ahd);
7110                 ahd_pause(ahd);
7111                 intstat = ahd_inb(ahd, INTSTAT);
7112                 if ((intstat & INT_PEND) == 0) {
7113                         ahd_clear_critical_section(ahd);
7114                         intstat = ahd_inb(ahd, INTSTAT);
7115                 }
7116         } while (--maxloops
7117               && (intstat != 0xFF || (ahd->features & AHD_REMOVABLE) == 0)
7118               && ((intstat & INT_PEND) != 0
7119                || (ahd_inb(ahd, SCSISEQ0) & ENSELO) != 0
7120                || (ahd_inb(ahd, SSTAT0) & (SELDO|SELINGO)) != 0));
7121
7122         if (maxloops == 0) {
7123                 printf("Infinite interrupt loop, INTSTAT = %x",
7124                       ahd_inb(ahd, INTSTAT));
7125         }
7126         ahd->qfreeze_cnt++;
7127         ahd_outw(ahd, KERNEL_QFREEZE_COUNT, ahd->qfreeze_cnt);
7128
7129         ahd_flush_qoutfifo(ahd);
7130
7131         ahd->flags &= ~AHD_ALL_INTERRUPTS;
7132 }
7133
7134 #if 0
7135 int
7136 ahd_suspend(struct ahd_softc *ahd)
7137 {
7138
7139         ahd_pause_and_flushwork(ahd);
7140
7141         if (LIST_FIRST(&ahd->pending_scbs) != NULL) {
7142                 ahd_unpause(ahd);
7143                 return (EBUSY);
7144         }
7145         ahd_shutdown(ahd);
7146         return (0);
7147 }
7148 #endif  /*  0  */
7149
7150 #if 0
7151 int
7152 ahd_resume(struct ahd_softc *ahd)
7153 {
7154
7155         ahd_reset(ahd, /*reinit*/TRUE);
7156         ahd_intr_enable(ahd, TRUE); 
7157         ahd_restart(ahd);
7158         return (0);
7159 }
7160 #endif  /*  0  */
7161
7162 /************************** Busy Target Table *********************************/
7163 /*
7164  * Set SCBPTR to the SCB that contains the busy
7165  * table entry for TCL.  Return the offset into
7166  * the SCB that contains the entry for TCL.
7167  * saved_scbid is dereferenced and set to the
7168  * scbid that should be restored once manipualtion
7169  * of the TCL entry is complete.
7170  */
7171 static __inline u_int
7172 ahd_index_busy_tcl(struct ahd_softc *ahd, u_int *saved_scbid, u_int tcl)
7173 {
7174         /*
7175          * Index to the SCB that contains the busy entry.
7176          */
7177         AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
7178         *saved_scbid = ahd_get_scbptr(ahd);
7179         ahd_set_scbptr(ahd, TCL_LUN(tcl)
7180                      | ((TCL_TARGET_OFFSET(tcl) & 0xC) << 4));
7181
7182         /*
7183          * And now calculate the SCB offset to the entry.
7184          * Each entry is 2 bytes wide, hence the
7185          * multiplication by 2.
7186          */
7187         return (((TCL_TARGET_OFFSET(tcl) & 0x3) << 1) + SCB_DISCONNECTED_LISTS);
7188 }
7189
7190 /*
7191  * Return the untagged transaction id for a given target/channel lun.
7192  */
7193 static u_int
7194 ahd_find_busy_tcl(struct ahd_softc *ahd, u_int tcl)
7195 {
7196         u_int scbid;
7197         u_int scb_offset;
7198         u_int saved_scbptr;
7199                 
7200         scb_offset = ahd_index_busy_tcl(ahd, &saved_scbptr, tcl);
7201         scbid = ahd_inw_scbram(ahd, scb_offset);
7202         ahd_set_scbptr(ahd, saved_scbptr);
7203         return (scbid);
7204 }
7205
7206 static void
7207 ahd_busy_tcl(struct ahd_softc *ahd, u_int tcl, u_int scbid)
7208 {
7209         u_int scb_offset;
7210         u_int saved_scbptr;
7211                 
7212         scb_offset = ahd_index_busy_tcl(ahd, &saved_scbptr, tcl);
7213         ahd_outw(ahd, scb_offset, scbid);
7214         ahd_set_scbptr(ahd, saved_scbptr);
7215 }
7216
7217 /************************** SCB and SCB queue management **********************/
7218 int
7219 ahd_match_scb(struct ahd_softc *ahd, struct scb *scb, int target,
7220               char channel, int lun, u_int tag, role_t role)
7221 {
7222         int targ = SCB_GET_TARGET(ahd, scb);
7223         char chan = SCB_GET_CHANNEL(ahd, scb);
7224         int slun = SCB_GET_LUN(scb);
7225         int match;
7226
7227         match = ((chan == channel) || (channel == ALL_CHANNELS));
7228         if (match != 0)
7229                 match = ((targ == target) || (target == CAM_TARGET_WILDCARD));
7230         if (match != 0)
7231                 match = ((lun == slun) || (lun == CAM_LUN_WILDCARD));
7232         if (match != 0) {
7233 #ifdef AHD_TARGET_MODE
7234                 int group;
7235
7236                 group = XPT_FC_GROUP(scb->io_ctx->ccb_h.func_code);
7237                 if (role == ROLE_INITIATOR) {
7238                         match = (group != XPT_FC_GROUP_TMODE)
7239                               && ((tag == SCB_GET_TAG(scb))
7240                                || (tag == SCB_LIST_NULL));
7241                 } else if (role == ROLE_TARGET) {
7242                         match = (group == XPT_FC_GROUP_TMODE)
7243                               && ((tag == scb->io_ctx->csio.tag_id)
7244                                || (tag == SCB_LIST_NULL));
7245                 }
7246 #else /* !AHD_TARGET_MODE */
7247                 match = ((tag == SCB_GET_TAG(scb)) || (tag == SCB_LIST_NULL));
7248 #endif /* AHD_TARGET_MODE */
7249         }
7250
7251         return match;
7252 }
7253
7254 static void
7255 ahd_freeze_devq(struct ahd_softc *ahd, struct scb *scb)
7256 {
7257         int     target;
7258         char    channel;
7259         int     lun;
7260
7261         target = SCB_GET_TARGET(ahd, scb);
7262         lun = SCB_GET_LUN(scb);
7263         channel = SCB_GET_CHANNEL(ahd, scb);
7264         
7265         ahd_search_qinfifo(ahd, target, channel, lun,
7266                            /*tag*/SCB_LIST_NULL, ROLE_UNKNOWN,
7267                            CAM_REQUEUE_REQ, SEARCH_COMPLETE);
7268
7269         ahd_platform_freeze_devq(ahd, scb);
7270 }
7271
7272 void
7273 ahd_qinfifo_requeue_tail(struct ahd_softc *ahd, struct scb *scb)
7274 {
7275         struct scb      *prev_scb;
7276         ahd_mode_state   saved_modes;
7277
7278         saved_modes = ahd_save_modes(ahd);
7279         ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
7280         prev_scb = NULL;
7281         if (ahd_qinfifo_count(ahd) != 0) {
7282                 u_int prev_tag;
7283                 u_int prev_pos;
7284
7285                 prev_pos = AHD_QIN_WRAP(ahd->qinfifonext - 1);
7286                 prev_tag = ahd->qinfifo[prev_pos];
7287                 prev_scb = ahd_lookup_scb(ahd, prev_tag);
7288         }
7289         ahd_qinfifo_requeue(ahd, prev_scb, scb);
7290         ahd_set_hnscb_qoff(ahd, ahd->qinfifonext);
7291         ahd_restore_modes(ahd, saved_modes);
7292 }
7293
7294 static void
7295 ahd_qinfifo_requeue(struct ahd_softc *ahd, struct scb *prev_scb,
7296                     struct scb *scb)
7297 {
7298         if (prev_scb == NULL) {
7299                 uint32_t busaddr;
7300
7301                 busaddr = ahd_le32toh(scb->hscb->hscb_busaddr);
7302                 ahd_outl(ahd, NEXT_QUEUED_SCB_ADDR, busaddr);
7303         } else {
7304                 prev_scb->hscb->next_hscb_busaddr = scb->hscb->hscb_busaddr;
7305                 ahd_sync_scb(ahd, prev_scb, 
7306                              BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
7307         }
7308         ahd->qinfifo[AHD_QIN_WRAP(ahd->qinfifonext)] = SCB_GET_TAG(scb);
7309         ahd->qinfifonext++;
7310         scb->hscb->next_hscb_busaddr = ahd->next_queued_hscb->hscb_busaddr;
7311         ahd_sync_scb(ahd, scb, BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
7312 }
7313
7314 static int
7315 ahd_qinfifo_count(struct ahd_softc *ahd)
7316 {
7317         u_int qinpos;
7318         u_int wrap_qinpos;
7319         u_int wrap_qinfifonext;
7320
7321         AHD_ASSERT_MODES(ahd, AHD_MODE_CCHAN_MSK, AHD_MODE_CCHAN_MSK);
7322         qinpos = ahd_get_snscb_qoff(ahd);
7323         wrap_qinpos = AHD_QIN_WRAP(qinpos);
7324         wrap_qinfifonext = AHD_QIN_WRAP(ahd->qinfifonext);
7325         if (wrap_qinfifonext >= wrap_qinpos)
7326                 return (wrap_qinfifonext - wrap_qinpos);
7327         else
7328                 return (wrap_qinfifonext
7329                       + ARRAY_SIZE(ahd->qinfifo) - wrap_qinpos);
7330 }
7331
7332 void
7333 ahd_reset_cmds_pending(struct ahd_softc *ahd)
7334 {
7335         struct          scb *scb;
7336         ahd_mode_state  saved_modes;
7337         u_int           pending_cmds;
7338
7339         saved_modes = ahd_save_modes(ahd);
7340         ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
7341
7342         /*
7343          * Don't count any commands as outstanding that the
7344          * sequencer has already marked for completion.
7345          */
7346         ahd_flush_qoutfifo(ahd);
7347
7348         pending_cmds = 0;
7349         LIST_FOREACH(scb, &ahd->pending_scbs, pending_links) {
7350                 pending_cmds++;
7351         }
7352         ahd_outw(ahd, CMDS_PENDING, pending_cmds - ahd_qinfifo_count(ahd));
7353         ahd_restore_modes(ahd, saved_modes);
7354         ahd->flags &= ~AHD_UPDATE_PEND_CMDS;
7355 }
7356
7357 static void
7358 ahd_done_with_status(struct ahd_softc *ahd, struct scb *scb, uint32_t status)
7359 {
7360         cam_status ostat;
7361         cam_status cstat;
7362
7363         ostat = ahd_get_transaction_status(scb);
7364         if (ostat == CAM_REQ_INPROG)
7365                 ahd_set_transaction_status(scb, status);
7366         cstat = ahd_get_transaction_status(scb);
7367         if (cstat != CAM_REQ_CMP)
7368                 ahd_freeze_scb(scb);
7369         ahd_done(ahd, scb);
7370 }
7371
7372 int
7373 ahd_search_qinfifo(struct ahd_softc *ahd, int target, char channel,
7374                    int lun, u_int tag, role_t role, uint32_t status,
7375                    ahd_search_action action)
7376 {
7377         struct scb      *scb;
7378         struct scb      *mk_msg_scb;
7379         struct scb      *prev_scb;
7380         ahd_mode_state   saved_modes;
7381         u_int            qinstart;
7382         u_int            qinpos;
7383         u_int            qintail;
7384         u_int            tid_next;
7385         u_int            tid_prev;
7386         u_int            scbid;
7387         u_int            seq_flags2;
7388         u_int            savedscbptr;
7389         uint32_t         busaddr;
7390         int              found;
7391         int              targets;
7392
7393         /* Must be in CCHAN mode */
7394         saved_modes = ahd_save_modes(ahd);
7395         ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
7396
7397         /*
7398          * Halt any pending SCB DMA.  The sequencer will reinitiate
7399          * this dma if the qinfifo is not empty once we unpause.
7400          */
7401         if ((ahd_inb(ahd, CCSCBCTL) & (CCARREN|CCSCBEN|CCSCBDIR))
7402          == (CCARREN|CCSCBEN|CCSCBDIR)) {
7403                 ahd_outb(ahd, CCSCBCTL,
7404                          ahd_inb(ahd, CCSCBCTL) & ~(CCARREN|CCSCBEN));
7405                 while ((ahd_inb(ahd, CCSCBCTL) & (CCARREN|CCSCBEN)) != 0)
7406                         ;
7407         }
7408         /* Determine sequencer's position in the qinfifo. */
7409         qintail = AHD_QIN_WRAP(ahd->qinfifonext);
7410         qinstart = ahd_get_snscb_qoff(ahd);
7411         qinpos = AHD_QIN_WRAP(qinstart);
7412         found = 0;
7413         prev_scb = NULL;
7414
7415         if (action == SEARCH_PRINT) {
7416                 printf("qinstart = %d qinfifonext = %d\nQINFIFO:",
7417                        qinstart, ahd->qinfifonext);
7418         }
7419
7420         /*
7421          * Start with an empty queue.  Entries that are not chosen
7422          * for removal will be re-added to the queue as we go.
7423          */
7424         ahd->qinfifonext = qinstart;
7425         busaddr = ahd_le32toh(ahd->next_queued_hscb->hscb_busaddr);
7426         ahd_outl(ahd, NEXT_QUEUED_SCB_ADDR, busaddr);
7427
7428         while (qinpos != qintail) {
7429                 scb = ahd_lookup_scb(ahd, ahd->qinfifo[qinpos]);
7430                 if (scb == NULL) {
7431                         printf("qinpos = %d, SCB index = %d\n",
7432                                 qinpos, ahd->qinfifo[qinpos]);
7433                         panic("Loop 1\n");
7434                 }
7435
7436                 if (ahd_match_scb(ahd, scb, target, channel, lun, tag, role)) {
7437                         /*
7438                          * We found an scb that needs to be acted on.
7439                          */
7440                         found++;
7441                         switch (action) {
7442                         case SEARCH_COMPLETE:
7443                                 if ((scb->flags & SCB_ACTIVE) == 0)
7444                                         printf("Inactive SCB in qinfifo\n");
7445                                 ahd_done_with_status(ahd, scb, status);
7446                                 /* FALLTHROUGH */
7447                         case SEARCH_REMOVE:
7448                                 break;
7449                         case SEARCH_PRINT:
7450                                 printf(" 0x%x", ahd->qinfifo[qinpos]);
7451                                 /* FALLTHROUGH */
7452                         case SEARCH_COUNT:
7453                                 ahd_qinfifo_requeue(ahd, prev_scb, scb);
7454                                 prev_scb = scb;
7455                                 break;
7456                         }
7457                 } else {
7458                         ahd_qinfifo_requeue(ahd, prev_scb, scb);
7459                         prev_scb = scb;
7460                 }
7461                 qinpos = AHD_QIN_WRAP(qinpos+1);
7462         }
7463
7464         ahd_set_hnscb_qoff(ahd, ahd->qinfifonext);
7465
7466         if (action == SEARCH_PRINT)
7467                 printf("\nWAITING_TID_QUEUES:\n");
7468
7469         /*
7470          * Search waiting for selection lists.  We traverse the
7471          * list of "their ids" waiting for selection and, if
7472          * appropriate, traverse the SCBs of each "their id"
7473          * looking for matches.
7474          */
7475         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
7476         seq_flags2 = ahd_inb(ahd, SEQ_FLAGS2);
7477         if ((seq_flags2 & PENDING_MK_MESSAGE) != 0) {
7478                 scbid = ahd_inw(ahd, MK_MESSAGE_SCB);
7479                 mk_msg_scb = ahd_lookup_scb(ahd, scbid);
7480         } else
7481                 mk_msg_scb = NULL;
7482         savedscbptr = ahd_get_scbptr(ahd);
7483         tid_next = ahd_inw(ahd, WAITING_TID_HEAD);
7484         tid_prev = SCB_LIST_NULL;
7485         targets = 0;
7486         for (scbid = tid_next; !SCBID_IS_NULL(scbid); scbid = tid_next) {
7487                 u_int tid_head;
7488                 u_int tid_tail;
7489
7490                 targets++;
7491                 if (targets > AHD_NUM_TARGETS)
7492                         panic("TID LIST LOOP");
7493
7494                 if (scbid >= ahd->scb_data.numscbs) {
7495                         printf("%s: Waiting TID List inconsistency. "
7496                                "SCB index == 0x%x, yet numscbs == 0x%x.",
7497                                ahd_name(ahd), scbid, ahd->scb_data.numscbs);
7498                         ahd_dump_card_state(ahd);
7499                         panic("for safety");
7500                 }
7501                 scb = ahd_lookup_scb(ahd, scbid);
7502                 if (scb == NULL) {
7503                         printf("%s: SCB = 0x%x Not Active!\n",
7504                                ahd_name(ahd), scbid);
7505                         panic("Waiting TID List traversal\n");
7506                 }
7507                 ahd_set_scbptr(ahd, scbid);
7508                 tid_next = ahd_inw_scbram(ahd, SCB_NEXT2);
7509                 if (ahd_match_scb(ahd, scb, target, channel, CAM_LUN_WILDCARD,
7510                                   SCB_LIST_NULL, ROLE_UNKNOWN) == 0) {
7511                         tid_prev = scbid;
7512                         continue;
7513                 }
7514
7515                 /*
7516                  * We found a list of scbs that needs to be searched.
7517                  */
7518                 if (action == SEARCH_PRINT)
7519                         printf("       %d ( ", SCB_GET_TARGET(ahd, scb));
7520                 tid_head = scbid;
7521                 found += ahd_search_scb_list(ahd, target, channel,
7522                                              lun, tag, role, status,
7523                                              action, &tid_head, &tid_tail,
7524                                              SCB_GET_TARGET(ahd, scb));
7525                 /*
7526                  * Check any MK_MESSAGE SCB that is still waiting to
7527                  * enter this target's waiting for selection queue.
7528                  */
7529                 if (mk_msg_scb != NULL
7530                  && ahd_match_scb(ahd, mk_msg_scb, target, channel,
7531                                   lun, tag, role)) {
7532
7533                         /*
7534                          * We found an scb that needs to be acted on.
7535                          */
7536                         found++;
7537                         switch (action) {
7538                         case SEARCH_COMPLETE:
7539                                 if ((mk_msg_scb->flags & SCB_ACTIVE) == 0)
7540                                         printf("Inactive SCB pending MK_MSG\n");
7541                                 ahd_done_with_status(ahd, mk_msg_scb, status);
7542                                 /* FALLTHROUGH */
7543                         case SEARCH_REMOVE:
7544                         {
7545                                 u_int tail_offset;
7546
7547                                 printf("Removing MK_MSG scb\n");
7548
7549                                 /*
7550                                  * Reset our tail to the tail of the
7551                                  * main per-target list.
7552                                  */
7553                                 tail_offset = WAITING_SCB_TAILS
7554                                     + (2 * SCB_GET_TARGET(ahd, mk_msg_scb));
7555                                 ahd_outw(ahd, tail_offset, tid_tail);
7556
7557                                 seq_flags2 &= ~PENDING_MK_MESSAGE;
7558                                 ahd_outb(ahd, SEQ_FLAGS2, seq_flags2);
7559                                 ahd_outw(ahd, CMDS_PENDING,
7560                                          ahd_inw(ahd, CMDS_PENDING)-1);
7561                                 mk_msg_scb = NULL;
7562                                 break;
7563                         }
7564                         case SEARCH_PRINT:
7565                                 printf(" 0x%x", SCB_GET_TAG(scb));
7566                                 /* FALLTHROUGH */
7567                         case SEARCH_COUNT:
7568                                 break;
7569                         }
7570                 }
7571
7572                 if (mk_msg_scb != NULL
7573                  && SCBID_IS_NULL(tid_head)
7574                  && ahd_match_scb(ahd, scb, target, channel, CAM_LUN_WILDCARD,
7575                                   SCB_LIST_NULL, ROLE_UNKNOWN)) {
7576
7577                         /*
7578                          * When removing the last SCB for a target
7579                          * queue with a pending MK_MESSAGE scb, we
7580                          * must queue the MK_MESSAGE scb.
7581                          */
7582                         printf("Queueing mk_msg_scb\n");
7583                         tid_head = ahd_inw(ahd, MK_MESSAGE_SCB);
7584                         seq_flags2 &= ~PENDING_MK_MESSAGE;
7585                         ahd_outb(ahd, SEQ_FLAGS2, seq_flags2);
7586                         mk_msg_scb = NULL;
7587                 }
7588                 if (tid_head != scbid)
7589                         ahd_stitch_tid_list(ahd, tid_prev, tid_head, tid_next);
7590                 if (!SCBID_IS_NULL(tid_head))
7591                         tid_prev = tid_head;
7592                 if (action == SEARCH_PRINT)
7593                         printf(")\n");
7594         }
7595
7596         /* Restore saved state. */
7597         ahd_set_scbptr(ahd, savedscbptr);
7598         ahd_restore_modes(ahd, saved_modes);
7599         return (found);
7600 }
7601
7602 static int
7603 ahd_search_scb_list(struct ahd_softc *ahd, int target, char channel,
7604                     int lun, u_int tag, role_t role, uint32_t status,
7605                     ahd_search_action action, u_int *list_head, 
7606                     u_int *list_tail, u_int tid)
7607 {
7608         struct  scb *scb;
7609         u_int   scbid;
7610         u_int   next;
7611         u_int   prev;
7612         int     found;
7613
7614         AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
7615         found = 0;
7616         prev = SCB_LIST_NULL;
7617         next = *list_head;
7618         *list_tail = SCB_LIST_NULL;
7619         for (scbid = next; !SCBID_IS_NULL(scbid); scbid = next) {
7620                 if (scbid >= ahd->scb_data.numscbs) {
7621                         printf("%s:SCB List inconsistency. "
7622                                "SCB == 0x%x, yet numscbs == 0x%x.",
7623                                ahd_name(ahd), scbid, ahd->scb_data.numscbs);
7624                         ahd_dump_card_state(ahd);
7625                         panic("for safety");
7626                 }
7627                 scb = ahd_lookup_scb(ahd, scbid);
7628                 if (scb == NULL) {
7629                         printf("%s: SCB = %d Not Active!\n",
7630                                ahd_name(ahd), scbid);
7631                         panic("Waiting List traversal\n");
7632                 }
7633                 ahd_set_scbptr(ahd, scbid);
7634                 *list_tail = scbid;
7635                 next = ahd_inw_scbram(ahd, SCB_NEXT);
7636                 if (ahd_match_scb(ahd, scb, target, channel,
7637                                   lun, SCB_LIST_NULL, role) == 0) {
7638                         prev = scbid;
7639                         continue;
7640                 }
7641                 found++;
7642                 switch (action) {
7643                 case SEARCH_COMPLETE:
7644                         if ((scb->flags & SCB_ACTIVE) == 0)
7645                                 printf("Inactive SCB in Waiting List\n");
7646                         ahd_done_with_status(ahd, scb, status);
7647                         /* FALLTHROUGH */
7648                 case SEARCH_REMOVE:
7649                         ahd_rem_wscb(ahd, scbid, prev, next, tid);
7650                         *list_tail = prev;
7651                         if (SCBID_IS_NULL(prev))
7652                                 *list_head = next;
7653                         break;
7654                 case SEARCH_PRINT:
7655                         printf("0x%x ", scbid);
7656                 case SEARCH_COUNT:
7657                         prev = scbid;
7658                         break;
7659                 }
7660                 if (found > AHD_SCB_MAX)
7661                         panic("SCB LIST LOOP");
7662         }
7663         if (action == SEARCH_COMPLETE
7664          || action == SEARCH_REMOVE)
7665                 ahd_outw(ahd, CMDS_PENDING, ahd_inw(ahd, CMDS_PENDING) - found);
7666         return (found);
7667 }
7668
7669 static void
7670 ahd_stitch_tid_list(struct ahd_softc *ahd, u_int tid_prev,
7671                     u_int tid_cur, u_int tid_next)
7672 {
7673         AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
7674
7675         if (SCBID_IS_NULL(tid_cur)) {
7676
7677                 /* Bypass current TID list */
7678                 if (SCBID_IS_NULL(tid_prev)) {
7679                         ahd_outw(ahd, WAITING_TID_HEAD, tid_next);
7680                 } else {
7681                         ahd_set_scbptr(ahd, tid_prev);
7682                         ahd_outw(ahd, SCB_NEXT2, tid_next);
7683                 }
7684                 if (SCBID_IS_NULL(tid_next))
7685                         ahd_outw(ahd, WAITING_TID_TAIL, tid_prev);
7686         } else {
7687
7688                 /* Stitch through tid_cur */
7689                 if (SCBID_IS_NULL(tid_prev)) {
7690                         ahd_outw(ahd, WAITING_TID_HEAD, tid_cur);
7691                 } else {
7692                         ahd_set_scbptr(ahd, tid_prev);
7693                         ahd_outw(ahd, SCB_NEXT2, tid_cur);
7694                 }
7695                 ahd_set_scbptr(ahd, tid_cur);
7696                 ahd_outw(ahd, SCB_NEXT2, tid_next);
7697
7698                 if (SCBID_IS_NULL(tid_next))
7699                         ahd_outw(ahd, WAITING_TID_TAIL, tid_cur);
7700         }
7701 }
7702
7703 /*
7704  * Manipulate the waiting for selection list and return the
7705  * scb that follows the one that we remove.
7706  */
7707 static u_int
7708 ahd_rem_wscb(struct ahd_softc *ahd, u_int scbid,
7709              u_int prev, u_int next, u_int tid)
7710 {
7711         u_int tail_offset;
7712
7713         AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
7714         if (!SCBID_IS_NULL(prev)) {
7715                 ahd_set_scbptr(ahd, prev);
7716                 ahd_outw(ahd, SCB_NEXT, next);
7717         }
7718
7719         /*
7720          * SCBs that have MK_MESSAGE set in them may
7721          * cause the tail pointer to be updated without
7722          * setting the next pointer of the previous tail.
7723          * Only clear the tail if the removed SCB was
7724          * the tail.
7725          */
7726         tail_offset = WAITING_SCB_TAILS + (2 * tid);
7727         if (SCBID_IS_NULL(next)
7728          && ahd_inw(ahd, tail_offset) == scbid)
7729                 ahd_outw(ahd, tail_offset, prev);
7730
7731         ahd_add_scb_to_free_list(ahd, scbid);
7732         return (next);
7733 }
7734
7735 /*
7736  * Add the SCB as selected by SCBPTR onto the on chip list of
7737  * free hardware SCBs.  This list is empty/unused if we are not
7738  * performing SCB paging.
7739  */
7740 static void
7741 ahd_add_scb_to_free_list(struct ahd_softc *ahd, u_int scbid)
7742 {
7743 /* XXX Need some other mechanism to designate "free". */
7744         /*
7745          * Invalidate the tag so that our abort
7746          * routines don't think it's active.
7747         ahd_outb(ahd, SCB_TAG, SCB_LIST_NULL);
7748          */
7749 }
7750
7751 /******************************** Error Handling ******************************/
7752 /*
7753  * Abort all SCBs that match the given description (target/channel/lun/tag),
7754  * setting their status to the passed in status if the status has not already
7755  * been modified from CAM_REQ_INPROG.  This routine assumes that the sequencer
7756  * is paused before it is called.
7757  */
7758 static int
7759 ahd_abort_scbs(struct ahd_softc *ahd, int target, char channel,
7760                int lun, u_int tag, role_t role, uint32_t status)
7761 {
7762         struct          scb *scbp;
7763         struct          scb *scbp_next;
7764         u_int           i, j;
7765         u_int           maxtarget;
7766         u_int           minlun;
7767         u_int           maxlun;
7768         int             found;
7769         ahd_mode_state  saved_modes;
7770
7771         /* restore this when we're done */
7772         saved_modes = ahd_save_modes(ahd);
7773         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
7774
7775         found = ahd_search_qinfifo(ahd, target, channel, lun, SCB_LIST_NULL,
7776                                    role, CAM_REQUEUE_REQ, SEARCH_COMPLETE);
7777
7778         /*
7779          * Clean out the busy target table for any untagged commands.
7780          */
7781         i = 0;
7782         maxtarget = 16;
7783         if (target != CAM_TARGET_WILDCARD) {
7784                 i = target;
7785                 if (channel == 'B')
7786                         i += 8;
7787                 maxtarget = i + 1;
7788         }
7789
7790         if (lun == CAM_LUN_WILDCARD) {
7791                 minlun = 0;
7792                 maxlun = AHD_NUM_LUNS_NONPKT;
7793         } else if (lun >= AHD_NUM_LUNS_NONPKT) {
7794                 minlun = maxlun = 0;
7795         } else {
7796                 minlun = lun;
7797                 maxlun = lun + 1;
7798         }
7799
7800         if (role != ROLE_TARGET) {
7801                 for (;i < maxtarget; i++) {
7802                         for (j = minlun;j < maxlun; j++) {
7803                                 u_int scbid;
7804                                 u_int tcl;
7805
7806                                 tcl = BUILD_TCL_RAW(i, 'A', j);
7807                                 scbid = ahd_find_busy_tcl(ahd, tcl);
7808                                 scbp = ahd_lookup_scb(ahd, scbid);
7809                                 if (scbp == NULL
7810                                  || ahd_match_scb(ahd, scbp, target, channel,
7811                                                   lun, tag, role) == 0)
7812                                         continue;
7813                                 ahd_unbusy_tcl(ahd, BUILD_TCL_RAW(i, 'A', j));
7814                         }
7815                 }
7816         }
7817
7818         /*
7819          * Don't abort commands that have already completed,
7820          * but haven't quite made it up to the host yet.
7821          */
7822         ahd_flush_qoutfifo(ahd);
7823
7824         /*
7825          * Go through the pending CCB list and look for
7826          * commands for this target that are still active.
7827          * These are other tagged commands that were
7828          * disconnected when the reset occurred.
7829          */
7830         scbp_next = LIST_FIRST(&ahd->pending_scbs);
7831         while (scbp_next != NULL) {
7832                 scbp = scbp_next;
7833                 scbp_next = LIST_NEXT(scbp, pending_links);
7834                 if (ahd_match_scb(ahd, scbp, target, channel, lun, tag, role)) {
7835                         cam_status ostat;
7836
7837                         ostat = ahd_get_transaction_status(scbp);
7838                         if (ostat == CAM_REQ_INPROG)
7839                                 ahd_set_transaction_status(scbp, status);
7840                         if (ahd_get_transaction_status(scbp) != CAM_REQ_CMP)
7841                                 ahd_freeze_scb(scbp);
7842                         if ((scbp->flags & SCB_ACTIVE) == 0)
7843                                 printf("Inactive SCB on pending list\n");
7844                         ahd_done(ahd, scbp);
7845                         found++;
7846                 }
7847         }
7848         ahd_restore_modes(ahd, saved_modes);
7849         ahd_platform_abort_scbs(ahd, target, channel, lun, tag, role, status);
7850         ahd->flags |= AHD_UPDATE_PEND_CMDS;
7851         return found;
7852 }
7853
7854 static void
7855 ahd_reset_current_bus(struct ahd_softc *ahd)
7856 {
7857         uint8_t scsiseq;
7858
7859         AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
7860         ahd_outb(ahd, SIMODE1, ahd_inb(ahd, SIMODE1) & ~ENSCSIRST);
7861         scsiseq = ahd_inb(ahd, SCSISEQ0) & ~(ENSELO|ENARBO|SCSIRSTO);
7862         ahd_outb(ahd, SCSISEQ0, scsiseq | SCSIRSTO);
7863         ahd_flush_device_writes(ahd);
7864         ahd_delay(AHD_BUSRESET_DELAY);
7865         /* Turn off the bus reset */
7866         ahd_outb(ahd, SCSISEQ0, scsiseq);
7867         ahd_flush_device_writes(ahd);
7868         ahd_delay(AHD_BUSRESET_DELAY);
7869         if ((ahd->bugs & AHD_SCSIRST_BUG) != 0) {
7870                 /*
7871                  * 2A Razor #474
7872                  * Certain chip state is not cleared for
7873                  * SCSI bus resets that we initiate, so
7874                  * we must reset the chip.
7875                  */
7876                 ahd_reset(ahd, /*reinit*/TRUE);
7877                 ahd_intr_enable(ahd, /*enable*/TRUE);
7878                 AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
7879         }
7880
7881         ahd_clear_intstat(ahd);
7882 }
7883
7884 int
7885 ahd_reset_channel(struct ahd_softc *ahd, char channel, int initiate_reset)
7886 {
7887         struct  ahd_devinfo devinfo;
7888         u_int   initiator;
7889         u_int   target;
7890         u_int   max_scsiid;
7891         int     found;
7892         u_int   fifo;
7893         u_int   next_fifo;
7894         uint8_t scsiseq;
7895
7896         /*
7897          * Check if the last bus reset is cleared
7898          */
7899         if (ahd->flags & AHD_BUS_RESET_ACTIVE) {
7900                 printf("%s: bus reset still active\n",
7901                        ahd_name(ahd));
7902                 return 0;
7903         }
7904         ahd->flags |= AHD_BUS_RESET_ACTIVE;
7905
7906         ahd->pending_device = NULL;
7907
7908         ahd_compile_devinfo(&devinfo,
7909                             CAM_TARGET_WILDCARD,
7910                             CAM_TARGET_WILDCARD,
7911                             CAM_LUN_WILDCARD,
7912                             channel, ROLE_UNKNOWN);
7913         ahd_pause(ahd);
7914
7915         /* Make sure the sequencer is in a safe location. */
7916         ahd_clear_critical_section(ahd);
7917
7918         /*
7919          * Run our command complete fifos to ensure that we perform
7920          * completion processing on any commands that 'completed'
7921          * before the reset occurred.
7922          */
7923         ahd_run_qoutfifo(ahd);
7924 #ifdef AHD_TARGET_MODE
7925         if ((ahd->flags & AHD_TARGETROLE) != 0) {
7926                 ahd_run_tqinfifo(ahd, /*paused*/TRUE);
7927         }
7928 #endif
7929         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
7930
7931         /*
7932          * Disable selections so no automatic hardware
7933          * functions will modify chip state.
7934          */
7935         ahd_outb(ahd, SCSISEQ0, 0);
7936         ahd_outb(ahd, SCSISEQ1, 0);
7937
7938         /*
7939          * Safely shut down our DMA engines.  Always start with
7940          * the FIFO that is not currently active (if any are
7941          * actively connected).
7942          */
7943         next_fifo = fifo = ahd_inb(ahd, DFFSTAT) & CURRFIFO;
7944         if (next_fifo > CURRFIFO_1)
7945                 /* If disconneced, arbitrarily start with FIFO1. */
7946                 next_fifo = fifo = 0;
7947         do {
7948                 next_fifo ^= CURRFIFO_1;
7949                 ahd_set_modes(ahd, next_fifo, next_fifo);
7950                 ahd_outb(ahd, DFCNTRL,
7951                          ahd_inb(ahd, DFCNTRL) & ~(SCSIEN|HDMAEN));
7952                 while ((ahd_inb(ahd, DFCNTRL) & HDMAENACK) != 0)
7953                         ahd_delay(10);
7954                 /*
7955                  * Set CURRFIFO to the now inactive channel.
7956                  */
7957                 ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
7958                 ahd_outb(ahd, DFFSTAT, next_fifo);
7959         } while (next_fifo != fifo);
7960
7961         /*
7962          * Reset the bus if we are initiating this reset
7963          */
7964         ahd_clear_msg_state(ahd);
7965         ahd_outb(ahd, SIMODE1,
7966                  ahd_inb(ahd, SIMODE1) & ~(ENBUSFREE|ENSCSIRST));
7967
7968         if (initiate_reset)
7969                 ahd_reset_current_bus(ahd);
7970
7971         ahd_clear_intstat(ahd);
7972
7973         /*
7974          * Clean up all the state information for the
7975          * pending transactions on this bus.
7976          */
7977         found = ahd_abort_scbs(ahd, CAM_TARGET_WILDCARD, channel,
7978                                CAM_LUN_WILDCARD, SCB_LIST_NULL,
7979                                ROLE_UNKNOWN, CAM_SCSI_BUS_RESET);
7980
7981         /*
7982          * Cleanup anything left in the FIFOs.
7983          */
7984         ahd_clear_fifo(ahd, 0);
7985         ahd_clear_fifo(ahd, 1);
7986
7987         /*
7988          * Reenable selections
7989          */
7990         ahd_outb(ahd, SIMODE1, ahd_inb(ahd, SIMODE1) | ENSCSIRST);
7991         scsiseq = ahd_inb(ahd, SCSISEQ_TEMPLATE);
7992         ahd_outb(ahd, SCSISEQ1, scsiseq & (ENSELI|ENRSELI|ENAUTOATNP));
7993
7994         max_scsiid = (ahd->features & AHD_WIDE) ? 15 : 7;
7995 #ifdef AHD_TARGET_MODE
7996         /*
7997          * Send an immediate notify ccb to all target more peripheral
7998          * drivers affected by this action.
7999          */
8000         for (target = 0; target <= max_scsiid; target++) {
8001                 struct ahd_tmode_tstate* tstate;
8002                 u_int lun;
8003
8004                 tstate = ahd->enabled_targets[target];
8005                 if (tstate == NULL)
8006                         continue;
8007                 for (lun = 0; lun < AHD_NUM_LUNS; lun++) {
8008                         struct ahd_tmode_lstate* lstate;
8009
8010                         lstate = tstate->enabled_luns[lun];
8011                         if (lstate == NULL)
8012                                 continue;
8013
8014                         ahd_queue_lstate_event(ahd, lstate, CAM_TARGET_WILDCARD,
8015                                                EVENT_TYPE_BUS_RESET, /*arg*/0);
8016                         ahd_send_lstate_events(ahd, lstate);
8017                 }
8018         }
8019 #endif
8020         /* Notify the XPT that a bus reset occurred */
8021         ahd_send_async(ahd, devinfo.channel, CAM_TARGET_WILDCARD,
8022                        CAM_LUN_WILDCARD, AC_BUS_RESET);
8023
8024         /*
8025          * Revert to async/narrow transfers until we renegotiate.
8026          */
8027         for (target = 0; target <= max_scsiid; target++) {
8028
8029                 if (ahd->enabled_targets[target] == NULL)
8030                         continue;
8031                 for (initiator = 0; initiator <= max_scsiid; initiator++) {
8032                         struct ahd_devinfo devinfo;
8033
8034                         ahd_compile_devinfo(&devinfo, target, initiator,
8035                                             CAM_LUN_WILDCARD,
8036                                             'A', ROLE_UNKNOWN);
8037                         ahd_set_width(ahd, &devinfo, MSG_EXT_WDTR_BUS_8_BIT,
8038                                       AHD_TRANS_CUR, /*paused*/TRUE);
8039                         ahd_set_syncrate(ahd, &devinfo, /*period*/0,
8040                                          /*offset*/0, /*ppr_options*/0,
8041                                          AHD_TRANS_CUR, /*paused*/TRUE);
8042                 }
8043         }
8044
8045         ahd_restart(ahd);
8046
8047         return (found);
8048 }
8049
8050 /**************************** Statistics Processing ***************************/
8051 static void
8052 ahd_stat_timer(void *arg)
8053 {
8054         struct  ahd_softc *ahd = arg;
8055         u_long  s;
8056         int     enint_coal;
8057         
8058         ahd_lock(ahd, &s);
8059
8060         enint_coal = ahd->hs_mailbox & ENINT_COALESCE;
8061         if (ahd->cmdcmplt_total > ahd->int_coalescing_threshold)
8062                 enint_coal |= ENINT_COALESCE;
8063         else if (ahd->cmdcmplt_total < ahd->int_coalescing_stop_threshold)
8064                 enint_coal &= ~ENINT_COALESCE;
8065
8066         if (enint_coal != (ahd->hs_mailbox & ENINT_COALESCE)) {
8067                 ahd_enable_coalescing(ahd, enint_coal);
8068 #ifdef AHD_DEBUG
8069                 if ((ahd_debug & AHD_SHOW_INT_COALESCING) != 0)
8070                         printf("%s: Interrupt coalescing "
8071                                "now %sabled. Cmds %d\n",
8072                                ahd_name(ahd),
8073                                (enint_coal & ENINT_COALESCE) ? "en" : "dis",
8074                                ahd->cmdcmplt_total);
8075 #endif
8076         }
8077
8078         ahd->cmdcmplt_bucket = (ahd->cmdcmplt_bucket+1) & (AHD_STAT_BUCKETS-1);
8079         ahd->cmdcmplt_total -= ahd->cmdcmplt_counts[ahd->cmdcmplt_bucket];
8080         ahd->cmdcmplt_counts[ahd->cmdcmplt_bucket] = 0;
8081         ahd_timer_reset(&ahd->stat_timer, AHD_STAT_UPDATE_US,
8082                         ahd_stat_timer, ahd);
8083         ahd_unlock(ahd, &s);
8084 }
8085
8086 /****************************** Status Processing *****************************/
8087
8088 static void
8089 ahd_handle_scsi_status(struct ahd_softc *ahd, struct scb *scb)
8090 {
8091         struct  hardware_scb *hscb;
8092         int     paused;
8093
8094         /*
8095          * The sequencer freezes its select-out queue
8096          * anytime a SCSI status error occurs.  We must
8097          * handle the error and increment our qfreeze count
8098          * to allow the sequencer to continue.  We don't
8099          * bother clearing critical sections here since all
8100          * operations are on data structures that the sequencer
8101          * is not touching once the queue is frozen.
8102          */
8103         hscb = scb->hscb; 
8104
8105         if (ahd_is_paused(ahd)) {
8106                 paused = 1;
8107         } else {
8108                 paused = 0;
8109                 ahd_pause(ahd);
8110         }
8111
8112         /* Freeze the queue until the client sees the error. */
8113         ahd_freeze_devq(ahd, scb);
8114         ahd_freeze_scb(scb);
8115         ahd->qfreeze_cnt++;
8116         ahd_outw(ahd, KERNEL_QFREEZE_COUNT, ahd->qfreeze_cnt);
8117
8118         if (paused == 0)
8119                 ahd_unpause(ahd);
8120
8121         /* Don't want to clobber the original sense code */
8122         if ((scb->flags & SCB_SENSE) != 0) {
8123                 /*
8124                  * Clear the SCB_SENSE Flag and perform
8125                  * a normal command completion.
8126                  */
8127                 scb->flags &= ~SCB_SENSE;
8128                 ahd_set_transaction_status(scb, CAM_AUTOSENSE_FAIL);
8129                 ahd_done(ahd, scb);
8130                 return;
8131         }
8132         ahd_set_transaction_status(scb, CAM_SCSI_STATUS_ERROR);
8133         ahd_set_scsi_status(scb, hscb->shared_data.istatus.scsi_status);
8134         switch (hscb->shared_data.istatus.scsi_status) {
8135         case STATUS_PKT_SENSE:
8136         {
8137                 struct scsi_status_iu_header *siu;
8138
8139                 ahd_sync_sense(ahd, scb, BUS_DMASYNC_POSTREAD);
8140                 siu = (struct scsi_status_iu_header *)scb->sense_data;
8141                 ahd_set_scsi_status(scb, siu->status);
8142 #ifdef AHD_DEBUG
8143                 if ((ahd_debug & AHD_SHOW_SENSE) != 0) {
8144                         ahd_print_path(ahd, scb);
8145                         printf("SCB 0x%x Received PKT Status of 0x%x\n",
8146                                SCB_GET_TAG(scb), siu->status);
8147                         printf("\tflags = 0x%x, sense len = 0x%x, "
8148                                "pktfail = 0x%x\n",
8149                                siu->flags, scsi_4btoul(siu->sense_length),
8150                                scsi_4btoul(siu->pkt_failures_length));
8151                 }
8152 #endif
8153                 if ((siu->flags & SIU_RSPVALID) != 0) {
8154                         ahd_print_path(ahd, scb);
8155                         if (scsi_4btoul(siu->pkt_failures_length) < 4) {
8156                                 printf("Unable to parse pkt_failures\n");
8157                         } else {
8158
8159                                 switch (SIU_PKTFAIL_CODE(siu)) {
8160                                 case SIU_PFC_NONE:
8161                                         printf("No packet failure found\n");
8162                                         break;
8163                                 case SIU_PFC_CIU_FIELDS_INVALID:
8164                                         printf("Invalid Command IU Field\n");
8165                                         break;
8166                                 case SIU_PFC_TMF_NOT_SUPPORTED:
8167                                         printf("TMF not supportd\n");
8168                                         break;
8169                                 case SIU_PFC_TMF_FAILED:
8170                                         printf("TMF failed\n");
8171                                         break;
8172                                 case SIU_PFC_INVALID_TYPE_CODE:
8173                                         printf("Invalid L_Q Type code\n");
8174                                         break;
8175                                 case SIU_PFC_ILLEGAL_REQUEST:
8176                                         printf("Illegal request\n");
8177                                 default:
8178                                         break;
8179                                 }
8180                         }
8181                         if (siu->status == SCSI_STATUS_OK)
8182                                 ahd_set_transaction_status(scb,
8183                                                            CAM_REQ_CMP_ERR);
8184                 }
8185                 if ((siu->flags & SIU_SNSVALID) != 0) {
8186                         scb->flags |= SCB_PKT_SENSE;
8187 #ifdef AHD_DEBUG
8188                         if ((ahd_debug & AHD_SHOW_SENSE) != 0)
8189                                 printf("Sense data available\n");
8190 #endif
8191                 }
8192                 ahd_done(ahd, scb);
8193                 break;
8194         }
8195         case SCSI_STATUS_CMD_TERMINATED:
8196         case SCSI_STATUS_CHECK_COND:
8197         {
8198                 struct ahd_devinfo devinfo;
8199                 struct ahd_dma_seg *sg;
8200                 struct scsi_sense *sc;
8201                 struct ahd_initiator_tinfo *targ_info;
8202                 struct ahd_tmode_tstate *tstate;
8203                 struct ahd_transinfo *tinfo;
8204 #ifdef AHD_DEBUG
8205                 if (ahd_debug & AHD_SHOW_SENSE) {
8206                         ahd_print_path(ahd, scb);
8207                         printf("SCB %d: requests Check Status\n",
8208                                SCB_GET_TAG(scb));
8209                 }
8210 #endif
8211
8212                 if (ahd_perform_autosense(scb) == 0)
8213                         break;
8214
8215                 ahd_compile_devinfo(&devinfo, SCB_GET_OUR_ID(scb),
8216                                     SCB_GET_TARGET(ahd, scb),
8217                                     SCB_GET_LUN(scb),
8218                                     SCB_GET_CHANNEL(ahd, scb),
8219                                     ROLE_INITIATOR);
8220                 targ_info = ahd_fetch_transinfo(ahd,
8221                                                 devinfo.channel,
8222                                                 devinfo.our_scsiid,
8223                                                 devinfo.target,
8224                                                 &tstate);
8225                 tinfo = &targ_info->curr;
8226                 sg = scb->sg_list;
8227                 sc = (struct scsi_sense *)hscb->shared_data.idata.cdb;
8228                 /*
8229                  * Save off the residual if there is one.
8230                  */
8231                 ahd_update_residual(ahd, scb);
8232 #ifdef AHD_DEBUG
8233                 if (ahd_debug & AHD_SHOW_SENSE) {
8234                         ahd_print_path(ahd, scb);
8235                         printf("Sending Sense\n");
8236                 }
8237 #endif
8238                 scb->sg_count = 0;
8239                 sg = ahd_sg_setup(ahd, scb, sg, ahd_get_sense_bufaddr(ahd, scb),
8240                                   ahd_get_sense_bufsize(ahd, scb),
8241                                   /*last*/TRUE);
8242                 sc->opcode = REQUEST_SENSE;
8243                 sc->byte2 = 0;
8244                 if (tinfo->protocol_version <= SCSI_REV_2
8245                  && SCB_GET_LUN(scb) < 8)
8246                         sc->byte2 = SCB_GET_LUN(scb) << 5;
8247                 sc->unused[0] = 0;
8248                 sc->unused[1] = 0;
8249                 sc->length = ahd_get_sense_bufsize(ahd, scb);
8250                 sc->control = 0;
8251
8252                 /*
8253                  * We can't allow the target to disconnect.
8254                  * This will be an untagged transaction and
8255                  * having the target disconnect will make this
8256                  * transaction indestinguishable from outstanding
8257                  * tagged transactions.
8258                  */
8259                 hscb->control = 0;
8260
8261                 /*
8262                  * This request sense could be because the
8263                  * the device lost power or in some other
8264                  * way has lost our transfer negotiations.
8265                  * Renegotiate if appropriate.  Unit attention
8266                  * errors will be reported before any data
8267                  * phases occur.
8268                  */
8269                 if (ahd_get_residual(scb) == ahd_get_transfer_length(scb)) {
8270                         ahd_update_neg_request(ahd, &devinfo,
8271                                                tstate, targ_info,
8272                                                AHD_NEG_IF_NON_ASYNC);
8273                 }
8274                 if (tstate->auto_negotiate & devinfo.target_mask) {
8275                         hscb->control |= MK_MESSAGE;
8276                         scb->flags &=
8277                             ~(SCB_NEGOTIATE|SCB_ABORT|SCB_DEVICE_RESET);
8278                         scb->flags |= SCB_AUTO_NEGOTIATE;
8279                 }
8280                 hscb->cdb_len = sizeof(*sc);
8281                 ahd_setup_data_scb(ahd, scb);
8282                 scb->flags |= SCB_SENSE;
8283                 ahd_queue_scb(ahd, scb);
8284                 break;
8285         }
8286         case SCSI_STATUS_OK:
8287                 printf("%s: Interrupted for staus of 0???\n",
8288                        ahd_name(ahd));
8289                 /* FALLTHROUGH */
8290         default:
8291                 ahd_done(ahd, scb);
8292                 break;
8293         }
8294 }
8295
8296 static void
8297 ahd_handle_scb_status(struct ahd_softc *ahd, struct scb *scb)
8298 {
8299         if (scb->hscb->shared_data.istatus.scsi_status != 0) {
8300                 ahd_handle_scsi_status(ahd, scb);
8301         } else {
8302                 ahd_calc_residual(ahd, scb);
8303                 ahd_done(ahd, scb);
8304         }
8305 }
8306
8307 /*
8308  * Calculate the residual for a just completed SCB.
8309  */
8310 static void
8311 ahd_calc_residual(struct ahd_softc *ahd, struct scb *scb)
8312 {
8313         struct hardware_scb *hscb;
8314         struct initiator_status *spkt;
8315         uint32_t sgptr;
8316         uint32_t resid_sgptr;
8317         uint32_t resid;
8318
8319         /*
8320          * 5 cases.
8321          * 1) No residual.
8322          *    SG_STATUS_VALID clear in sgptr.
8323          * 2) Transferless command
8324          * 3) Never performed any transfers.
8325          *    sgptr has SG_FULL_RESID set.
8326          * 4) No residual but target did not
8327          *    save data pointers after the
8328          *    last transfer, so sgptr was
8329          *    never updated.
8330          * 5) We have a partial residual.
8331          *    Use residual_sgptr to determine
8332          *    where we are.
8333          */
8334
8335         hscb = scb->hscb;
8336         sgptr = ahd_le32toh(hscb->sgptr);
8337         if ((sgptr & SG_STATUS_VALID) == 0)
8338                 /* Case 1 */
8339                 return;
8340         sgptr &= ~SG_STATUS_VALID;
8341
8342         if ((sgptr & SG_LIST_NULL) != 0)
8343                 /* Case 2 */
8344                 return;
8345
8346         /*
8347          * Residual fields are the same in both
8348          * target and initiator status packets,
8349          * so we can always use the initiator fields
8350          * regardless of the role for this SCB.
8351          */
8352         spkt = &hscb->shared_data.istatus;
8353         resid_sgptr = ahd_le32toh(spkt->residual_sgptr);
8354         if ((sgptr & SG_FULL_RESID) != 0) {
8355                 /* Case 3 */
8356                 resid = ahd_get_transfer_length(scb);
8357         } else if ((resid_sgptr & SG_LIST_NULL) != 0) {
8358                 /* Case 4 */
8359                 return;
8360         } else if ((resid_sgptr & SG_OVERRUN_RESID) != 0) {
8361                 ahd_print_path(ahd, scb);
8362                 printf("data overrun detected Tag == 0x%x.\n",
8363                        SCB_GET_TAG(scb));
8364                 ahd_freeze_devq(ahd, scb);
8365                 ahd_set_transaction_status(scb, CAM_DATA_RUN_ERR);
8366                 ahd_freeze_scb(scb);
8367                 return;
8368         } else if ((resid_sgptr & ~SG_PTR_MASK) != 0) {
8369                 panic("Bogus resid sgptr value 0x%x\n", resid_sgptr);
8370                 /* NOTREACHED */
8371         } else {
8372                 struct ahd_dma_seg *sg;
8373
8374                 /*
8375                  * Remainder of the SG where the transfer
8376                  * stopped.  
8377                  */
8378                 resid = ahd_le32toh(spkt->residual_datacnt) & AHD_SG_LEN_MASK;
8379                 sg = ahd_sg_bus_to_virt(ahd, scb, resid_sgptr & SG_PTR_MASK);
8380
8381                 /* The residual sg_ptr always points to the next sg */
8382                 sg--;
8383
8384                 /*
8385                  * Add up the contents of all residual
8386                  * SG segments that are after the SG where
8387                  * the transfer stopped.
8388                  */
8389                 while ((ahd_le32toh(sg->len) & AHD_DMA_LAST_SEG) == 0) {
8390                         sg++;
8391                         resid += ahd_le32toh(sg->len) & AHD_SG_LEN_MASK;
8392                 }
8393         }
8394         if ((scb->flags & SCB_SENSE) == 0)
8395                 ahd_set_residual(scb, resid);
8396         else
8397                 ahd_set_sense_residual(scb, resid);
8398
8399 #ifdef AHD_DEBUG
8400         if ((ahd_debug & AHD_SHOW_MISC) != 0) {
8401                 ahd_print_path(ahd, scb);
8402                 printf("Handled %sResidual of %d bytes\n",
8403                        (scb->flags & SCB_SENSE) ? "Sense " : "", resid);
8404         }
8405 #endif
8406 }
8407
8408 /******************************* Target Mode **********************************/
8409 #ifdef AHD_TARGET_MODE
8410 /*
8411  * Add a target mode event to this lun's queue
8412  */
8413 static void
8414 ahd_queue_lstate_event(struct ahd_softc *ahd, struct ahd_tmode_lstate *lstate,
8415                        u_int initiator_id, u_int event_type, u_int event_arg)
8416 {
8417         struct ahd_tmode_event *event;
8418         int pending;
8419
8420         xpt_freeze_devq(lstate->path, /*count*/1);
8421         if (lstate->event_w_idx >= lstate->event_r_idx)
8422                 pending = lstate->event_w_idx - lstate->event_r_idx;
8423         else
8424                 pending = AHD_TMODE_EVENT_BUFFER_SIZE + 1
8425                         - (lstate->event_r_idx - lstate->event_w_idx);
8426
8427         if (event_type == EVENT_TYPE_BUS_RESET
8428          || event_type == MSG_BUS_DEV_RESET) {
8429                 /*
8430                  * Any earlier events are irrelevant, so reset our buffer.
8431                  * This has the effect of allowing us to deal with reset
8432                  * floods (an external device holding down the reset line)
8433                  * without losing the event that is really interesting.
8434                  */
8435                 lstate->event_r_idx = 0;
8436                 lstate->event_w_idx = 0;
8437                 xpt_release_devq(lstate->path, pending, /*runqueue*/FALSE);
8438         }
8439
8440         if (pending == AHD_TMODE_EVENT_BUFFER_SIZE) {
8441                 xpt_print_path(lstate->path);
8442                 printf("immediate event %x:%x lost\n",
8443                        lstate->event_buffer[lstate->event_r_idx].event_type,
8444                        lstate->event_buffer[lstate->event_r_idx].event_arg);
8445                 lstate->event_r_idx++;
8446                 if (lstate->event_r_idx == AHD_TMODE_EVENT_BUFFER_SIZE)
8447                         lstate->event_r_idx = 0;
8448                 xpt_release_devq(lstate->path, /*count*/1, /*runqueue*/FALSE);
8449         }
8450
8451         event = &lstate->event_buffer[lstate->event_w_idx];
8452         event->initiator_id = initiator_id;
8453         event->event_type = event_type;
8454         event->event_arg = event_arg;
8455         lstate->event_w_idx++;
8456         if (lstate->event_w_idx == AHD_TMODE_EVENT_BUFFER_SIZE)
8457                 lstate->event_w_idx = 0;
8458 }
8459
8460 /*
8461  * Send any target mode events queued up waiting
8462  * for immediate notify resources.
8463  */
8464 void
8465 ahd_send_lstate_events(struct ahd_softc *ahd, struct ahd_tmode_lstate *lstate)
8466 {
8467         struct ccb_hdr *ccbh;
8468         struct ccb_immed_notify *inot;
8469
8470         while (lstate->event_r_idx != lstate->event_w_idx
8471             && (ccbh = SLIST_FIRST(&lstate->immed_notifies)) != NULL) {
8472                 struct ahd_tmode_event *event;
8473
8474                 event = &lstate->event_buffer[lstate->event_r_idx];
8475                 SLIST_REMOVE_HEAD(&lstate->immed_notifies, sim_links.sle);
8476                 inot = (struct ccb_immed_notify *)ccbh;
8477                 switch (event->event_type) {
8478                 case EVENT_TYPE_BUS_RESET:
8479                         ccbh->status = CAM_SCSI_BUS_RESET|CAM_DEV_QFRZN;
8480                         break;
8481                 default:
8482                         ccbh->status = CAM_MESSAGE_RECV|CAM_DEV_QFRZN;
8483                         inot->message_args[0] = event->event_type;
8484                         inot->message_args[1] = event->event_arg;
8485                         break;
8486                 }
8487                 inot->initiator_id = event->initiator_id;
8488                 inot->sense_len = 0;
8489                 xpt_done((union ccb *)inot);
8490                 lstate->event_r_idx++;
8491                 if (lstate->event_r_idx == AHD_TMODE_EVENT_BUFFER_SIZE)
8492                         lstate->event_r_idx = 0;
8493         }
8494 }
8495 #endif
8496
8497 /******************** Sequencer Program Patching/Download *********************/
8498
8499 #ifdef AHD_DUMP_SEQ
8500 void
8501 ahd_dumpseq(struct ahd_softc* ahd)
8502 {
8503         int i;
8504         int max_prog;
8505
8506         max_prog = 2048;
8507
8508         ahd_outb(ahd, SEQCTL0, PERRORDIS|FAILDIS|FASTMODE|LOADRAM);
8509         ahd_outw(ahd, PRGMCNT, 0);
8510         for (i = 0; i < max_prog; i++) {
8511                 uint8_t ins_bytes[4];
8512
8513                 ahd_insb(ahd, SEQRAM, ins_bytes, 4);
8514                 printf("0x%08x\n", ins_bytes[0] << 24
8515                                  | ins_bytes[1] << 16
8516                                  | ins_bytes[2] << 8
8517                                  | ins_bytes[3]);
8518         }
8519 }
8520 #endif
8521
8522 static void
8523 ahd_loadseq(struct ahd_softc *ahd)
8524 {
8525         struct  cs cs_table[num_critical_sections];
8526         u_int   begin_set[num_critical_sections];
8527         u_int   end_set[num_critical_sections];
8528         struct  patch *cur_patch;
8529         u_int   cs_count;
8530         u_int   cur_cs;
8531         u_int   i;
8532         int     downloaded;
8533         u_int   skip_addr;
8534         u_int   sg_prefetch_cnt;
8535         u_int   sg_prefetch_cnt_limit;
8536         u_int   sg_prefetch_align;
8537         u_int   sg_size;
8538         u_int   cacheline_mask;
8539         uint8_t download_consts[DOWNLOAD_CONST_COUNT];
8540
8541         if (bootverbose)
8542                 printf("%s: Downloading Sequencer Program...",
8543                        ahd_name(ahd));
8544
8545 #if DOWNLOAD_CONST_COUNT != 8
8546 #error "Download Const Mismatch"
8547 #endif
8548         /*
8549          * Start out with 0 critical sections
8550          * that apply to this firmware load.
8551          */
8552         cs_count = 0;
8553         cur_cs = 0;
8554         memset(begin_set, 0, sizeof(begin_set));
8555         memset(end_set, 0, sizeof(end_set));
8556
8557         /*
8558          * Setup downloadable constant table.
8559          * 
8560          * The computation for the S/G prefetch variables is
8561          * a bit complicated.  We would like to always fetch
8562          * in terms of cachelined sized increments.  However,
8563          * if the cacheline is not an even multiple of the
8564          * SG element size or is larger than our SG RAM, using
8565          * just the cache size might leave us with only a portion
8566          * of an SG element at the tail of a prefetch.  If the
8567          * cacheline is larger than our S/G prefetch buffer less
8568          * the size of an SG element, we may round down to a cacheline
8569          * that doesn't contain any or all of the S/G of interest
8570          * within the bounds of our S/G ram.  Provide variables to
8571          * the sequencer that will allow it to handle these edge
8572          * cases.
8573          */
8574         /* Start by aligning to the nearest cacheline. */
8575         sg_prefetch_align = ahd->pci_cachesize;
8576         if (sg_prefetch_align == 0)
8577                 sg_prefetch_align = 8;
8578         /* Round down to the nearest power of 2. */
8579         while (powerof2(sg_prefetch_align) == 0)
8580                 sg_prefetch_align--;
8581
8582         cacheline_mask = sg_prefetch_align - 1;
8583
8584         /*
8585          * If the cacheline boundary is greater than half our prefetch RAM
8586          * we risk not being able to fetch even a single complete S/G
8587          * segment if we align to that boundary.
8588          */
8589         if (sg_prefetch_align > CCSGADDR_MAX/2)
8590                 sg_prefetch_align = CCSGADDR_MAX/2;
8591         /* Start by fetching a single cacheline. */
8592         sg_prefetch_cnt = sg_prefetch_align;
8593         /*
8594          * Increment the prefetch count by cachelines until
8595          * at least one S/G element will fit.
8596          */
8597         sg_size = sizeof(struct ahd_dma_seg);
8598         if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0)
8599                 sg_size = sizeof(struct ahd_dma64_seg);
8600         while (sg_prefetch_cnt < sg_size)
8601                 sg_prefetch_cnt += sg_prefetch_align;
8602         /*
8603          * If the cacheline is not an even multiple of
8604          * the S/G size, we may only get a partial S/G when
8605          * we align. Add a cacheline if this is the case.
8606          */
8607         if ((sg_prefetch_align % sg_size) != 0
8608          && (sg_prefetch_cnt < CCSGADDR_MAX))
8609                 sg_prefetch_cnt += sg_prefetch_align;
8610         /*
8611          * Lastly, compute a value that the sequencer can use
8612          * to determine if the remainder of the CCSGRAM buffer
8613          * has a full S/G element in it.
8614          */
8615         sg_prefetch_cnt_limit = -(sg_prefetch_cnt - sg_size + 1);
8616         download_consts[SG_PREFETCH_CNT] = sg_prefetch_cnt;
8617         download_consts[SG_PREFETCH_CNT_LIMIT] = sg_prefetch_cnt_limit;
8618         download_consts[SG_PREFETCH_ALIGN_MASK] = ~(sg_prefetch_align - 1);
8619         download_consts[SG_PREFETCH_ADDR_MASK] = (sg_prefetch_align - 1);
8620         download_consts[SG_SIZEOF] = sg_size;
8621         download_consts[PKT_OVERRUN_BUFOFFSET] =
8622                 (ahd->overrun_buf - (uint8_t *)ahd->qoutfifo) / 256;
8623         download_consts[SCB_TRANSFER_SIZE] = SCB_TRANSFER_SIZE_1BYTE_LUN;
8624         download_consts[CACHELINE_MASK] = cacheline_mask;
8625         cur_patch = patches;
8626         downloaded = 0;
8627         skip_addr = 0;
8628         ahd_outb(ahd, SEQCTL0, PERRORDIS|FAILDIS|FASTMODE|LOADRAM);
8629         ahd_outw(ahd, PRGMCNT, 0);
8630
8631         for (i = 0; i < sizeof(seqprog)/4; i++) {
8632                 if (ahd_check_patch(ahd, &cur_patch, i, &skip_addr) == 0) {
8633                         /*
8634                          * Don't download this instruction as it
8635                          * is in a patch that was removed.
8636                          */
8637                         continue;
8638                 }
8639                 /*
8640                  * Move through the CS table until we find a CS
8641                  * that might apply to this instruction.
8642                  */
8643                 for (; cur_cs < num_critical_sections; cur_cs++) {
8644                         if (critical_sections[cur_cs].end <= i) {
8645                                 if (begin_set[cs_count] == TRUE
8646                                  && end_set[cs_count] == FALSE) {
8647                                         cs_table[cs_count].end = downloaded;
8648                                         end_set[cs_count] = TRUE;
8649                                         cs_count++;
8650                                 }
8651                                 continue;
8652                         }
8653                         if (critical_sections[cur_cs].begin <= i
8654                          && begin_set[cs_count] == FALSE) {
8655                                 cs_table[cs_count].begin = downloaded;
8656                                 begin_set[cs_count] = TRUE;
8657                         }
8658                         break;
8659                 }
8660                 ahd_download_instr(ahd, i, download_consts);
8661                 downloaded++;
8662         }
8663
8664         ahd->num_critical_sections = cs_count;
8665         if (cs_count != 0) {
8666
8667                 cs_count *= sizeof(struct cs);
8668                 ahd->critical_sections = malloc(cs_count, M_DEVBUF, M_NOWAIT);
8669                 if (ahd->critical_sections == NULL)
8670                         panic("ahd_loadseq: Could not malloc");
8671                 memcpy(ahd->critical_sections, cs_table, cs_count);
8672         }
8673         ahd_outb(ahd, SEQCTL0, PERRORDIS|FAILDIS|FASTMODE);
8674
8675         if (bootverbose) {
8676                 printf(" %d instructions downloaded\n", downloaded);
8677                 printf("%s: Features 0x%x, Bugs 0x%x, Flags 0x%x\n",
8678                        ahd_name(ahd), ahd->features, ahd->bugs, ahd->flags);
8679         }
8680 }
8681
8682 static int
8683 ahd_check_patch(struct ahd_softc *ahd, struct patch **start_patch,
8684                 u_int start_instr, u_int *skip_addr)
8685 {
8686         struct  patch *cur_patch;
8687         struct  patch *last_patch;
8688         u_int   num_patches;
8689
8690         num_patches = ARRAY_SIZE(patches);
8691         last_patch = &patches[num_patches];
8692         cur_patch = *start_patch;
8693
8694         while (cur_patch < last_patch && start_instr == cur_patch->begin) {
8695
8696                 if (cur_patch->patch_func(ahd) == 0) {
8697
8698                         /* Start rejecting code */
8699                         *skip_addr = start_instr + cur_patch->skip_instr;
8700                         cur_patch += cur_patch->skip_patch;
8701                 } else {
8702                         /* Accepted this patch.  Advance to the next
8703                          * one and wait for our intruction pointer to
8704                          * hit this point.
8705                          */
8706                         cur_patch++;
8707                 }
8708         }
8709
8710         *start_patch = cur_patch;
8711         if (start_instr < *skip_addr)
8712                 /* Still skipping */
8713                 return (0);
8714
8715         return (1);
8716 }
8717
8718 static u_int
8719 ahd_resolve_seqaddr(struct ahd_softc *ahd, u_int address)
8720 {
8721         struct patch *cur_patch;
8722         int address_offset;
8723         u_int skip_addr;
8724         u_int i;
8725
8726         address_offset = 0;
8727         cur_patch = patches;
8728         skip_addr = 0;
8729
8730         for (i = 0; i < address;) {
8731
8732                 ahd_check_patch(ahd, &cur_patch, i, &skip_addr);
8733
8734                 if (skip_addr > i) {
8735                         int end_addr;
8736
8737                         end_addr = min(address, skip_addr);
8738                         address_offset += end_addr - i;
8739                         i = skip_addr;
8740                 } else {
8741                         i++;
8742                 }
8743         }
8744         return (address - address_offset);
8745 }
8746
8747 static void
8748 ahd_download_instr(struct ahd_softc *ahd, u_int instrptr, uint8_t *dconsts)
8749 {
8750         union   ins_formats instr;
8751         struct  ins_format1 *fmt1_ins;
8752         struct  ins_format3 *fmt3_ins;
8753         u_int   opcode;
8754
8755         /*
8756          * The firmware is always compiled into a little endian format.
8757          */
8758         instr.integer = ahd_le32toh(*(uint32_t*)&seqprog[instrptr * 4]);
8759
8760         fmt1_ins = &instr.format1;
8761         fmt3_ins = NULL;
8762
8763         /* Pull the opcode */
8764         opcode = instr.format1.opcode;
8765         switch (opcode) {
8766         case AIC_OP_JMP:
8767         case AIC_OP_JC:
8768         case AIC_OP_JNC:
8769         case AIC_OP_CALL:
8770         case AIC_OP_JNE:
8771         case AIC_OP_JNZ:
8772         case AIC_OP_JE:
8773         case AIC_OP_JZ:
8774         {
8775                 fmt3_ins = &instr.format3;
8776                 fmt3_ins->address = ahd_resolve_seqaddr(ahd, fmt3_ins->address);
8777                 /* FALLTHROUGH */
8778         }
8779         case AIC_OP_OR:
8780         case AIC_OP_AND:
8781         case AIC_OP_XOR:
8782         case AIC_OP_ADD:
8783         case AIC_OP_ADC:
8784         case AIC_OP_BMOV:
8785                 if (fmt1_ins->parity != 0) {
8786                         fmt1_ins->immediate = dconsts[fmt1_ins->immediate];
8787                 }
8788                 fmt1_ins->parity = 0;
8789                 /* FALLTHROUGH */
8790         case AIC_OP_ROL:
8791         {
8792                 int i, count;
8793
8794                 /* Calculate odd parity for the instruction */
8795                 for (i = 0, count = 0; i < 31; i++) {
8796                         uint32_t mask;
8797
8798                         mask = 0x01 << i;
8799                         if ((instr.integer & mask) != 0)
8800                                 count++;
8801                 }
8802                 if ((count & 0x01) == 0)
8803                         instr.format1.parity = 1;
8804
8805                 /* The sequencer is a little endian cpu */
8806                 instr.integer = ahd_htole32(instr.integer);
8807                 ahd_outsb(ahd, SEQRAM, instr.bytes, 4);
8808                 break;
8809         }
8810         default:
8811                 panic("Unknown opcode encountered in seq program");
8812                 break;
8813         }
8814 }
8815
8816 static int
8817 ahd_probe_stack_size(struct ahd_softc *ahd)
8818 {
8819         int last_probe;
8820
8821         last_probe = 0;
8822         while (1) {
8823                 int i;
8824
8825                 /*
8826                  * We avoid using 0 as a pattern to avoid
8827                  * confusion if the stack implementation
8828                  * "back-fills" with zeros when "poping'
8829                  * entries.
8830                  */
8831                 for (i = 1; i <= last_probe+1; i++) {
8832                        ahd_outb(ahd, STACK, i & 0xFF);
8833                        ahd_outb(ahd, STACK, (i >> 8) & 0xFF);
8834                 }
8835
8836                 /* Verify */
8837                 for (i = last_probe+1; i > 0; i--) {
8838                         u_int stack_entry;
8839
8840                         stack_entry = ahd_inb(ahd, STACK)
8841                                     |(ahd_inb(ahd, STACK) << 8);
8842                         if (stack_entry != i)
8843                                 goto sized;
8844                 }
8845                 last_probe++;
8846         }
8847 sized:
8848         return (last_probe);
8849 }
8850
8851 int
8852 ahd_print_register(ahd_reg_parse_entry_t *table, u_int num_entries,
8853                    const char *name, u_int address, u_int value,
8854                    u_int *cur_column, u_int wrap_point)
8855 {
8856         int     printed;
8857         u_int   printed_mask;
8858
8859         if (cur_column != NULL && *cur_column >= wrap_point) {
8860                 printf("\n");
8861                 *cur_column = 0;
8862         }
8863         printed = printf("%s[0x%x]", name, value);
8864         if (table == NULL) {
8865                 printed += printf(" ");
8866                 *cur_column += printed;
8867                 return (printed);
8868         }
8869         printed_mask = 0;
8870         while (printed_mask != 0xFF) {
8871                 int entry;
8872
8873                 for (entry = 0; entry < num_entries; entry++) {
8874                         if (((value & table[entry].mask)
8875                           != table[entry].value)
8876                          || ((printed_mask & table[entry].mask)
8877                           == table[entry].mask))
8878                                 continue;
8879
8880                         printed += printf("%s%s",
8881                                           printed_mask == 0 ? ":(" : "|",
8882                                           table[entry].name);
8883                         printed_mask |= table[entry].mask;
8884                         
8885                         break;
8886                 }
8887                 if (entry >= num_entries)
8888                         break;
8889         }
8890         if (printed_mask != 0)
8891                 printed += printf(") ");
8892         else
8893                 printed += printf(" ");
8894         if (cur_column != NULL)
8895                 *cur_column += printed;
8896         return (printed);
8897 }
8898
8899 void
8900 ahd_dump_card_state(struct ahd_softc *ahd)
8901 {
8902         struct scb      *scb;
8903         ahd_mode_state   saved_modes;
8904         u_int            dffstat;
8905         int              paused;
8906         u_int            scb_index;
8907         u_int            saved_scb_index;
8908         u_int            cur_col;
8909         int              i;
8910
8911         if (ahd_is_paused(ahd)) {
8912                 paused = 1;
8913         } else {
8914                 paused = 0;
8915                 ahd_pause(ahd);
8916         }
8917         saved_modes = ahd_save_modes(ahd);
8918         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
8919         printf(">>>>>>>>>>>>>>>>>> Dump Card State Begins <<<<<<<<<<<<<<<<<\n"
8920                "%s: Dumping Card State at program address 0x%x Mode 0x%x\n",
8921                ahd_name(ahd), 
8922                ahd_inw(ahd, CURADDR),
8923                ahd_build_mode_state(ahd, ahd->saved_src_mode,
8924                                     ahd->saved_dst_mode));
8925         if (paused)
8926                 printf("Card was paused\n");
8927
8928         if (ahd_check_cmdcmpltqueues(ahd))
8929                 printf("Completions are pending\n");
8930
8931         /*
8932          * Mode independent registers.
8933          */
8934         cur_col = 0;
8935         ahd_intstat_print(ahd_inb(ahd, INTSTAT), &cur_col, 50);
8936         ahd_seloid_print(ahd_inb(ahd, SELOID), &cur_col, 50);
8937         ahd_selid_print(ahd_inb(ahd, SELID), &cur_col, 50);
8938         ahd_hs_mailbox_print(ahd_inb(ahd, LOCAL_HS_MAILBOX), &cur_col, 50);
8939         ahd_intctl_print(ahd_inb(ahd, INTCTL), &cur_col, 50);
8940         ahd_seqintstat_print(ahd_inb(ahd, SEQINTSTAT), &cur_col, 50);
8941         ahd_saved_mode_print(ahd_inb(ahd, SAVED_MODE), &cur_col, 50);
8942         ahd_dffstat_print(ahd_inb(ahd, DFFSTAT), &cur_col, 50);
8943         ahd_scsisigi_print(ahd_inb(ahd, SCSISIGI), &cur_col, 50);
8944         ahd_scsiphase_print(ahd_inb(ahd, SCSIPHASE), &cur_col, 50);
8945         ahd_scsibus_print(ahd_inb(ahd, SCSIBUS), &cur_col, 50);
8946         ahd_lastphase_print(ahd_inb(ahd, LASTPHASE), &cur_col, 50);
8947         ahd_scsiseq0_print(ahd_inb(ahd, SCSISEQ0), &cur_col, 50);
8948         ahd_scsiseq1_print(ahd_inb(ahd, SCSISEQ1), &cur_col, 50);
8949         ahd_seqctl0_print(ahd_inb(ahd, SEQCTL0), &cur_col, 50);
8950         ahd_seqintctl_print(ahd_inb(ahd, SEQINTCTL), &cur_col, 50);
8951         ahd_seq_flags_print(ahd_inb(ahd, SEQ_FLAGS), &cur_col, 50);
8952         ahd_seq_flags2_print(ahd_inb(ahd, SEQ_FLAGS2), &cur_col, 50);
8953         ahd_qfreeze_count_print(ahd_inw(ahd, QFREEZE_COUNT), &cur_col, 50);
8954         ahd_kernel_qfreeze_count_print(ahd_inw(ahd, KERNEL_QFREEZE_COUNT),
8955                                        &cur_col, 50);
8956         ahd_mk_message_scb_print(ahd_inw(ahd, MK_MESSAGE_SCB), &cur_col, 50);
8957         ahd_mk_message_scsiid_print(ahd_inb(ahd, MK_MESSAGE_SCSIID),
8958                                     &cur_col, 50);
8959         ahd_sstat0_print(ahd_inb(ahd, SSTAT0), &cur_col, 50);
8960         ahd_sstat1_print(ahd_inb(ahd, SSTAT1), &cur_col, 50);
8961         ahd_sstat2_print(ahd_inb(ahd, SSTAT2), &cur_col, 50);
8962         ahd_sstat3_print(ahd_inb(ahd, SSTAT3), &cur_col, 50);
8963         ahd_perrdiag_print(ahd_inb(ahd, PERRDIAG), &cur_col, 50);
8964         ahd_simode1_print(ahd_inb(ahd, SIMODE1), &cur_col, 50);
8965         ahd_lqistat0_print(ahd_inb(ahd, LQISTAT0), &cur_col, 50);
8966         ahd_lqistat1_print(ahd_inb(ahd, LQISTAT1), &cur_col, 50);
8967         ahd_lqistat2_print(ahd_inb(ahd, LQISTAT2), &cur_col, 50);
8968         ahd_lqostat0_print(ahd_inb(ahd, LQOSTAT0), &cur_col, 50);
8969         ahd_lqostat1_print(ahd_inb(ahd, LQOSTAT1), &cur_col, 50);
8970         ahd_lqostat2_print(ahd_inb(ahd, LQOSTAT2), &cur_col, 50);
8971         printf("\n");
8972         printf("\nSCB Count = %d CMDS_PENDING = %d LASTSCB 0x%x "
8973                "CURRSCB 0x%x NEXTSCB 0x%x\n",
8974                ahd->scb_data.numscbs, ahd_inw(ahd, CMDS_PENDING),
8975                ahd_inw(ahd, LASTSCB), ahd_inw(ahd, CURRSCB),
8976                ahd_inw(ahd, NEXTSCB));
8977         cur_col = 0;
8978         /* QINFIFO */
8979         ahd_search_qinfifo(ahd, CAM_TARGET_WILDCARD, ALL_CHANNELS,
8980                            CAM_LUN_WILDCARD, SCB_LIST_NULL,
8981                            ROLE_UNKNOWN, /*status*/0, SEARCH_PRINT);
8982         saved_scb_index = ahd_get_scbptr(ahd);
8983         printf("Pending list:");
8984         i = 0;
8985         LIST_FOREACH(scb, &ahd->pending_scbs, pending_links) {
8986                 if (i++ > AHD_SCB_MAX)
8987                         break;
8988                 cur_col = printf("\n%3d FIFO_USE[0x%x] ", SCB_GET_TAG(scb),
8989                                  ahd_inb_scbram(ahd, SCB_FIFO_USE_COUNT));
8990                 ahd_set_scbptr(ahd, SCB_GET_TAG(scb));
8991                 ahd_scb_control_print(ahd_inb_scbram(ahd, SCB_CONTROL),
8992                                       &cur_col, 60);
8993                 ahd_scb_scsiid_print(ahd_inb_scbram(ahd, SCB_SCSIID),
8994                                      &cur_col, 60);
8995         }
8996         printf("\nTotal %d\n", i);
8997
8998         printf("Kernel Free SCB list: ");
8999         i = 0;
9000         TAILQ_FOREACH(scb, &ahd->scb_data.free_scbs, links.tqe) {
9001                 struct scb *list_scb;
9002
9003                 list_scb = scb;
9004                 do {
9005                         printf("%d ", SCB_GET_TAG(list_scb));
9006                         list_scb = LIST_NEXT(list_scb, collision_links);
9007                 } while (list_scb && i++ < AHD_SCB_MAX);
9008         }
9009
9010         LIST_FOREACH(scb, &ahd->scb_data.any_dev_free_scb_list, links.le) {
9011                 if (i++ > AHD_SCB_MAX)
9012                         break;
9013                 printf("%d ", SCB_GET_TAG(scb));
9014         }
9015         printf("\n");
9016
9017         printf("Sequencer Complete DMA-inprog list: ");
9018         scb_index = ahd_inw(ahd, COMPLETE_SCB_DMAINPROG_HEAD);
9019         i = 0;
9020         while (!SCBID_IS_NULL(scb_index) && i++ < AHD_SCB_MAX) {
9021                 ahd_set_scbptr(ahd, scb_index);
9022                 printf("%d ", scb_index);
9023                 scb_index = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
9024         }
9025         printf("\n");
9026
9027         printf("Sequencer Complete list: ");
9028         scb_index = ahd_inw(ahd, COMPLETE_SCB_HEAD);
9029         i = 0;
9030         while (!SCBID_IS_NULL(scb_index) && i++ < AHD_SCB_MAX) {
9031                 ahd_set_scbptr(ahd, scb_index);
9032                 printf("%d ", scb_index);
9033                 scb_index = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
9034         }
9035         printf("\n");
9036
9037         
9038         printf("Sequencer DMA-Up and Complete list: ");
9039         scb_index = ahd_inw(ahd, COMPLETE_DMA_SCB_HEAD);
9040         i = 0;
9041         while (!SCBID_IS_NULL(scb_index) && i++ < AHD_SCB_MAX) {
9042                 ahd_set_scbptr(ahd, scb_index);
9043                 printf("%d ", scb_index);
9044                 scb_index = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
9045         }
9046         printf("\n");
9047         printf("Sequencer On QFreeze and Complete list: ");
9048         scb_index = ahd_inw(ahd, COMPLETE_ON_QFREEZE_HEAD);
9049         i = 0;
9050         while (!SCBID_IS_NULL(scb_index) && i++ < AHD_SCB_MAX) {
9051                 ahd_set_scbptr(ahd, scb_index);
9052                 printf("%d ", scb_index);
9053                 scb_index = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
9054         }
9055         printf("\n");
9056         ahd_set_scbptr(ahd, saved_scb_index);
9057         dffstat = ahd_inb(ahd, DFFSTAT);
9058         for (i = 0; i < 2; i++) {
9059 #ifdef AHD_DEBUG
9060                 struct scb *fifo_scb;
9061 #endif
9062                 u_int       fifo_scbptr;
9063
9064                 ahd_set_modes(ahd, AHD_MODE_DFF0 + i, AHD_MODE_DFF0 + i);
9065                 fifo_scbptr = ahd_get_scbptr(ahd);
9066                 printf("\n\n%s: FIFO%d %s, LONGJMP == 0x%x, SCB 0x%x\n",
9067                        ahd_name(ahd), i,
9068                        (dffstat & (FIFO0FREE << i)) ? "Free" : "Active",
9069                        ahd_inw(ahd, LONGJMP_ADDR), fifo_scbptr);
9070                 cur_col = 0;
9071                 ahd_seqimode_print(ahd_inb(ahd, SEQIMODE), &cur_col, 50);
9072                 ahd_seqintsrc_print(ahd_inb(ahd, SEQINTSRC), &cur_col, 50);
9073                 ahd_dfcntrl_print(ahd_inb(ahd, DFCNTRL), &cur_col, 50);
9074                 ahd_dfstatus_print(ahd_inb(ahd, DFSTATUS), &cur_col, 50);
9075                 ahd_sg_cache_shadow_print(ahd_inb(ahd, SG_CACHE_SHADOW),
9076                                           &cur_col, 50);
9077                 ahd_sg_state_print(ahd_inb(ahd, SG_STATE), &cur_col, 50);
9078                 ahd_dffsxfrctl_print(ahd_inb(ahd, DFFSXFRCTL), &cur_col, 50);
9079                 ahd_soffcnt_print(ahd_inb(ahd, SOFFCNT), &cur_col, 50);
9080                 ahd_mdffstat_print(ahd_inb(ahd, MDFFSTAT), &cur_col, 50);
9081                 if (cur_col > 50) {
9082                         printf("\n");
9083                         cur_col = 0;
9084                 }
9085                 cur_col += printf("SHADDR = 0x%x%x, SHCNT = 0x%x ",
9086                                   ahd_inl(ahd, SHADDR+4),
9087                                   ahd_inl(ahd, SHADDR),
9088                                   (ahd_inb(ahd, SHCNT)
9089                                 | (ahd_inb(ahd, SHCNT + 1) << 8)
9090                                 | (ahd_inb(ahd, SHCNT + 2) << 16)));
9091                 if (cur_col > 50) {
9092                         printf("\n");
9093                         cur_col = 0;
9094                 }
9095                 cur_col += printf("HADDR = 0x%x%x, HCNT = 0x%x ",
9096                                   ahd_inl(ahd, HADDR+4),
9097                                   ahd_inl(ahd, HADDR),
9098                                   (ahd_inb(ahd, HCNT)
9099                                 | (ahd_inb(ahd, HCNT + 1) << 8)
9100                                 | (ahd_inb(ahd, HCNT + 2) << 16)));
9101                 ahd_ccsgctl_print(ahd_inb(ahd, CCSGCTL), &cur_col, 50);
9102 #ifdef AHD_DEBUG
9103                 if ((ahd_debug & AHD_SHOW_SG) != 0) {
9104                         fifo_scb = ahd_lookup_scb(ahd, fifo_scbptr);
9105                         if (fifo_scb != NULL)
9106                                 ahd_dump_sglist(fifo_scb);
9107                 }
9108 #endif
9109         }
9110         printf("\nLQIN: ");
9111         for (i = 0; i < 20; i++)
9112                 printf("0x%x ", ahd_inb(ahd, LQIN + i));
9113         printf("\n");
9114         ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
9115         printf("%s: LQISTATE = 0x%x, LQOSTATE = 0x%x, OPTIONMODE = 0x%x\n",
9116                ahd_name(ahd), ahd_inb(ahd, LQISTATE), ahd_inb(ahd, LQOSTATE),
9117                ahd_inb(ahd, OPTIONMODE));
9118         printf("%s: OS_SPACE_CNT = 0x%x MAXCMDCNT = 0x%x\n",
9119                ahd_name(ahd), ahd_inb(ahd, OS_SPACE_CNT),
9120                ahd_inb(ahd, MAXCMDCNT));
9121         printf("%s: SAVED_SCSIID = 0x%x SAVED_LUN = 0x%x\n",
9122                ahd_name(ahd), ahd_inb(ahd, SAVED_SCSIID),
9123                ahd_inb(ahd, SAVED_LUN));
9124         ahd_simode0_print(ahd_inb(ahd, SIMODE0), &cur_col, 50);
9125         printf("\n");
9126         ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
9127         cur_col = 0;
9128         ahd_ccscbctl_print(ahd_inb(ahd, CCSCBCTL), &cur_col, 50);
9129         printf("\n");
9130         ahd_set_modes(ahd, ahd->saved_src_mode, ahd->saved_dst_mode);
9131         printf("%s: REG0 == 0x%x, SINDEX = 0x%x, DINDEX = 0x%x\n",
9132                ahd_name(ahd), ahd_inw(ahd, REG0), ahd_inw(ahd, SINDEX),
9133                ahd_inw(ahd, DINDEX));
9134         printf("%s: SCBPTR == 0x%x, SCB_NEXT == 0x%x, SCB_NEXT2 == 0x%x\n",
9135                ahd_name(ahd), ahd_get_scbptr(ahd),
9136                ahd_inw_scbram(ahd, SCB_NEXT),
9137                ahd_inw_scbram(ahd, SCB_NEXT2));
9138         printf("CDB %x %x %x %x %x %x\n",
9139                ahd_inb_scbram(ahd, SCB_CDB_STORE),
9140                ahd_inb_scbram(ahd, SCB_CDB_STORE+1),
9141                ahd_inb_scbram(ahd, SCB_CDB_STORE+2),
9142                ahd_inb_scbram(ahd, SCB_CDB_STORE+3),
9143                ahd_inb_scbram(ahd, SCB_CDB_STORE+4),
9144                ahd_inb_scbram(ahd, SCB_CDB_STORE+5));
9145         printf("STACK:");
9146         for (i = 0; i < ahd->stack_size; i++) {
9147                 ahd->saved_stack[i] =
9148                     ahd_inb(ahd, STACK)|(ahd_inb(ahd, STACK) << 8);
9149                 printf(" 0x%x", ahd->saved_stack[i]);
9150         }
9151         for (i = ahd->stack_size-1; i >= 0; i--) {
9152                 ahd_outb(ahd, STACK, ahd->saved_stack[i] & 0xFF);
9153                 ahd_outb(ahd, STACK, (ahd->saved_stack[i] >> 8) & 0xFF);
9154         }
9155         printf("\n<<<<<<<<<<<<<<<<< Dump Card State Ends >>>>>>>>>>>>>>>>>>\n");
9156         ahd_restore_modes(ahd, saved_modes);
9157         if (paused == 0)
9158                 ahd_unpause(ahd);
9159 }
9160
9161 #if 0
9162 void
9163 ahd_dump_scbs(struct ahd_softc *ahd)
9164 {
9165         ahd_mode_state saved_modes;
9166         u_int          saved_scb_index;
9167         int            i;
9168
9169         saved_modes = ahd_save_modes(ahd);
9170         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
9171         saved_scb_index = ahd_get_scbptr(ahd);
9172         for (i = 0; i < AHD_SCB_MAX; i++) {
9173                 ahd_set_scbptr(ahd, i);
9174                 printf("%3d", i);
9175                 printf("(CTRL 0x%x ID 0x%x N 0x%x N2 0x%x SG 0x%x, RSG 0x%x)\n",
9176                        ahd_inb_scbram(ahd, SCB_CONTROL),
9177                        ahd_inb_scbram(ahd, SCB_SCSIID),
9178                        ahd_inw_scbram(ahd, SCB_NEXT),
9179                        ahd_inw_scbram(ahd, SCB_NEXT2),
9180                        ahd_inl_scbram(ahd, SCB_SGPTR),
9181                        ahd_inl_scbram(ahd, SCB_RESIDUAL_SGPTR));
9182         }
9183         printf("\n");
9184         ahd_set_scbptr(ahd, saved_scb_index);
9185         ahd_restore_modes(ahd, saved_modes);
9186 }
9187 #endif  /*  0  */
9188
9189 /**************************** Flexport Logic **********************************/
9190 /*
9191  * Read count 16bit words from 16bit word address start_addr from the
9192  * SEEPROM attached to the controller, into buf, using the controller's
9193  * SEEPROM reading state machine.  Optionally treat the data as a byte
9194  * stream in terms of byte order.
9195  */
9196 int
9197 ahd_read_seeprom(struct ahd_softc *ahd, uint16_t *buf,
9198                  u_int start_addr, u_int count, int bytestream)
9199 {
9200         u_int cur_addr;
9201         u_int end_addr;
9202         int   error;
9203
9204         /*
9205          * If we never make it through the loop even once,
9206          * we were passed invalid arguments.
9207          */
9208         error = EINVAL;
9209         AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
9210         end_addr = start_addr + count;
9211         for (cur_addr = start_addr; cur_addr < end_addr; cur_addr++) {
9212
9213                 ahd_outb(ahd, SEEADR, cur_addr);
9214                 ahd_outb(ahd, SEECTL, SEEOP_READ | SEESTART);
9215                 
9216                 error = ahd_wait_seeprom(ahd);
9217                 if (error)
9218                         break;
9219                 if (bytestream != 0) {
9220                         uint8_t *bytestream_ptr;
9221
9222                         bytestream_ptr = (uint8_t *)buf;
9223                         *bytestream_ptr++ = ahd_inb(ahd, SEEDAT);
9224                         *bytestream_ptr = ahd_inb(ahd, SEEDAT+1);
9225                 } else {
9226                         /*
9227                          * ahd_inw() already handles machine byte order.
9228                          */
9229                         *buf = ahd_inw(ahd, SEEDAT);
9230                 }
9231                 buf++;
9232         }
9233         return (error);
9234 }
9235
9236 /*
9237  * Write count 16bit words from buf, into SEEPROM attache to the
9238  * controller starting at 16bit word address start_addr, using the
9239  * controller's SEEPROM writing state machine.
9240  */
9241 int
9242 ahd_write_seeprom(struct ahd_softc *ahd, uint16_t *buf,
9243                   u_int start_addr, u_int count)
9244 {
9245         u_int cur_addr;
9246         u_int end_addr;
9247         int   error;
9248         int   retval;
9249
9250         AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
9251         error = ENOENT;
9252
9253         /* Place the chip into write-enable mode */
9254         ahd_outb(ahd, SEEADR, SEEOP_EWEN_ADDR);
9255         ahd_outb(ahd, SEECTL, SEEOP_EWEN | SEESTART);
9256         error = ahd_wait_seeprom(ahd);
9257         if (error)
9258                 return (error);
9259
9260         /*
9261          * Write the data.  If we don't get throught the loop at
9262          * least once, the arguments were invalid.
9263          */
9264         retval = EINVAL;
9265         end_addr = start_addr + count;
9266         for (cur_addr = start_addr; cur_addr < end_addr; cur_addr++) {
9267                 ahd_outw(ahd, SEEDAT, *buf++);
9268                 ahd_outb(ahd, SEEADR, cur_addr);
9269                 ahd_outb(ahd, SEECTL, SEEOP_WRITE | SEESTART);
9270                 
9271                 retval = ahd_wait_seeprom(ahd);
9272                 if (retval)
9273                         break;
9274         }
9275
9276         /*
9277          * Disable writes.
9278          */
9279         ahd_outb(ahd, SEEADR, SEEOP_EWDS_ADDR);
9280         ahd_outb(ahd, SEECTL, SEEOP_EWDS | SEESTART);
9281         error = ahd_wait_seeprom(ahd);
9282         if (error)
9283                 return (error);
9284         return (retval);
9285 }
9286
9287 /*
9288  * Wait ~100us for the serial eeprom to satisfy our request.
9289  */
9290 static int
9291 ahd_wait_seeprom(struct ahd_softc *ahd)
9292 {
9293         int cnt;
9294
9295         cnt = 5000;
9296         while ((ahd_inb(ahd, SEESTAT) & (SEEARBACK|SEEBUSY)) != 0 && --cnt)
9297                 ahd_delay(5);
9298
9299         if (cnt == 0)
9300                 return (ETIMEDOUT);
9301         return (0);
9302 }
9303
9304 /*
9305  * Validate the two checksums in the per_channel
9306  * vital product data struct.
9307  */
9308 static int
9309 ahd_verify_vpd_cksum(struct vpd_config *vpd)
9310 {
9311         int i;
9312         int maxaddr;
9313         uint32_t checksum;
9314         uint8_t *vpdarray;
9315
9316         vpdarray = (uint8_t *)vpd;
9317         maxaddr = offsetof(struct vpd_config, vpd_checksum);
9318         checksum = 0;
9319         for (i = offsetof(struct vpd_config, resource_type); i < maxaddr; i++)
9320                 checksum = checksum + vpdarray[i];
9321         if (checksum == 0
9322          || (-checksum & 0xFF) != vpd->vpd_checksum)
9323                 return (0);
9324
9325         checksum = 0;
9326         maxaddr = offsetof(struct vpd_config, checksum);
9327         for (i = offsetof(struct vpd_config, default_target_flags);
9328              i < maxaddr; i++)
9329                 checksum = checksum + vpdarray[i];
9330         if (checksum == 0
9331          || (-checksum & 0xFF) != vpd->checksum)
9332                 return (0);
9333         return (1);
9334 }
9335
9336 int
9337 ahd_verify_cksum(struct seeprom_config *sc)
9338 {
9339         int i;
9340         int maxaddr;
9341         uint32_t checksum;
9342         uint16_t *scarray;
9343
9344         maxaddr = (sizeof(*sc)/2) - 1;
9345         checksum = 0;
9346         scarray = (uint16_t *)sc;
9347
9348         for (i = 0; i < maxaddr; i++)
9349                 checksum = checksum + scarray[i];
9350         if (checksum == 0
9351          || (checksum & 0xFFFF) != sc->checksum) {
9352                 return (0);
9353         } else {
9354                 return (1);
9355         }
9356 }
9357
9358 int
9359 ahd_acquire_seeprom(struct ahd_softc *ahd)
9360 {
9361         /*
9362          * We should be able to determine the SEEPROM type
9363          * from the flexport logic, but unfortunately not
9364          * all implementations have this logic and there is
9365          * no programatic method for determining if the logic
9366          * is present.
9367          */
9368         return (1);
9369 #if 0
9370         uint8_t seetype;
9371         int     error;
9372
9373         error = ahd_read_flexport(ahd, FLXADDR_ROMSTAT_CURSENSECTL, &seetype);
9374         if (error != 0
9375          || ((seetype & FLX_ROMSTAT_SEECFG) == FLX_ROMSTAT_SEE_NONE))
9376                 return (0);
9377         return (1);
9378 #endif
9379 }
9380
9381 void
9382 ahd_release_seeprom(struct ahd_softc *ahd)
9383 {
9384         /* Currently a no-op */
9385 }
9386
9387 /*
9388  * Wait at most 2 seconds for flexport arbitration to succeed.
9389  */
9390 static int
9391 ahd_wait_flexport(struct ahd_softc *ahd)
9392 {
9393         int cnt;
9394
9395         AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
9396         cnt = 1000000 * 2 / 5;
9397         while ((ahd_inb(ahd, BRDCTL) & FLXARBACK) == 0 && --cnt)
9398                 ahd_delay(5);
9399
9400         if (cnt == 0)
9401                 return (ETIMEDOUT);
9402         return (0);
9403 }
9404
9405 int
9406 ahd_write_flexport(struct ahd_softc *ahd, u_int addr, u_int value)
9407 {
9408         int error;
9409
9410         AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
9411         if (addr > 7)
9412                 panic("ahd_write_flexport: address out of range");
9413         ahd_outb(ahd, BRDCTL, BRDEN|(addr << 3));
9414         error = ahd_wait_flexport(ahd);
9415         if (error != 0)
9416                 return (error);
9417         ahd_outb(ahd, BRDDAT, value);
9418         ahd_flush_device_writes(ahd);
9419         ahd_outb(ahd, BRDCTL, BRDSTB|BRDEN|(addr << 3));
9420         ahd_flush_device_writes(ahd);
9421         ahd_outb(ahd, BRDCTL, BRDEN|(addr << 3));
9422         ahd_flush_device_writes(ahd);
9423         ahd_outb(ahd, BRDCTL, 0);
9424         ahd_flush_device_writes(ahd);
9425         return (0);
9426 }
9427
9428 int
9429 ahd_read_flexport(struct ahd_softc *ahd, u_int addr, uint8_t *value)
9430 {
9431         int     error;
9432
9433         AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
9434         if (addr > 7)
9435                 panic("ahd_read_flexport: address out of range");
9436         ahd_outb(ahd, BRDCTL, BRDRW|BRDEN|(addr << 3));
9437         error = ahd_wait_flexport(ahd);
9438         if (error != 0)
9439                 return (error);
9440         *value = ahd_inb(ahd, BRDDAT);
9441         ahd_outb(ahd, BRDCTL, 0);
9442         ahd_flush_device_writes(ahd);
9443         return (0);
9444 }
9445
9446 /************************* Target Mode ****************************************/
9447 #ifdef AHD_TARGET_MODE
9448 cam_status
9449 ahd_find_tmode_devs(struct ahd_softc *ahd, struct cam_sim *sim, union ccb *ccb,
9450                     struct ahd_tmode_tstate **tstate,
9451                     struct ahd_tmode_lstate **lstate,
9452                     int notfound_failure)
9453 {
9454
9455         if ((ahd->features & AHD_TARGETMODE) == 0)
9456                 return (CAM_REQ_INVALID);
9457
9458         /*
9459          * Handle the 'black hole' device that sucks up
9460          * requests to unattached luns on enabled targets.
9461          */
9462         if (ccb->ccb_h.target_id == CAM_TARGET_WILDCARD
9463          && ccb->ccb_h.target_lun == CAM_LUN_WILDCARD) {
9464                 *tstate = NULL;
9465                 *lstate = ahd->black_hole;
9466         } else {
9467                 u_int max_id;
9468
9469                 max_id = (ahd->features & AHD_WIDE) ? 16 : 8;
9470                 if (ccb->ccb_h.target_id >= max_id)
9471                         return (CAM_TID_INVALID);
9472
9473                 if (ccb->ccb_h.target_lun >= AHD_NUM_LUNS)
9474                         return (CAM_LUN_INVALID);
9475
9476                 *tstate = ahd->enabled_targets[ccb->ccb_h.target_id];
9477                 *lstate = NULL;
9478                 if (*tstate != NULL)
9479                         *lstate =
9480                             (*tstate)->enabled_luns[ccb->ccb_h.target_lun];
9481         }
9482
9483         if (notfound_failure != 0 && *lstate == NULL)
9484                 return (CAM_PATH_INVALID);
9485
9486         return (CAM_REQ_CMP);
9487 }
9488
9489 void
9490 ahd_handle_en_lun(struct ahd_softc *ahd, struct cam_sim *sim, union ccb *ccb)
9491 {
9492 #if NOT_YET
9493         struct     ahd_tmode_tstate *tstate;
9494         struct     ahd_tmode_lstate *lstate;
9495         struct     ccb_en_lun *cel;
9496         cam_status status;
9497         u_int      target;
9498         u_int      lun;
9499         u_int      target_mask;
9500         u_long     s;
9501         char       channel;
9502
9503         status = ahd_find_tmode_devs(ahd, sim, ccb, &tstate, &lstate,
9504                                      /*notfound_failure*/FALSE);
9505
9506         if (status != CAM_REQ_CMP) {
9507                 ccb->ccb_h.status = status;
9508                 return;
9509         }
9510
9511         if ((ahd->features & AHD_MULTIROLE) != 0) {
9512                 u_int      our_id;
9513
9514                 our_id = ahd->our_id;
9515                 if (ccb->ccb_h.target_id != our_id) {
9516                         if ((ahd->features & AHD_MULTI_TID) != 0
9517                          && (ahd->flags & AHD_INITIATORROLE) != 0) {
9518                                 /*
9519                                  * Only allow additional targets if
9520                                  * the initiator role is disabled.
9521                                  * The hardware cannot handle a re-select-in
9522                                  * on the initiator id during a re-select-out
9523                                  * on a different target id.
9524                                  */
9525                                 status = CAM_TID_INVALID;
9526                         } else if ((ahd->flags & AHD_INITIATORROLE) != 0
9527                                 || ahd->enabled_luns > 0) {
9528                                 /*
9529                                  * Only allow our target id to change
9530                                  * if the initiator role is not configured
9531                                  * and there are no enabled luns which
9532                                  * are attached to the currently registered
9533                                  * scsi id.
9534                                  */
9535                                 status = CAM_TID_INVALID;
9536                         }
9537                 }
9538         }
9539
9540         if (status != CAM_REQ_CMP) {
9541                 ccb->ccb_h.status = status;
9542                 return;
9543         }
9544
9545         /*
9546          * We now have an id that is valid.
9547          * If we aren't in target mode, switch modes.
9548          */
9549         if ((ahd->flags & AHD_TARGETROLE) == 0
9550          && ccb->ccb_h.target_id != CAM_TARGET_WILDCARD) {
9551                 u_long  s;
9552
9553                 printf("Configuring Target Mode\n");
9554                 ahd_lock(ahd, &s);
9555                 if (LIST_FIRST(&ahd->pending_scbs) != NULL) {
9556                         ccb->ccb_h.status = CAM_BUSY;
9557                         ahd_unlock(ahd, &s);
9558                         return;
9559                 }
9560                 ahd->flags |= AHD_TARGETROLE;
9561                 if ((ahd->features & AHD_MULTIROLE) == 0)
9562                         ahd->flags &= ~AHD_INITIATORROLE;
9563                 ahd_pause(ahd);
9564                 ahd_loadseq(ahd);
9565                 ahd_restart(ahd);
9566                 ahd_unlock(ahd, &s);
9567         }
9568         cel = &ccb->cel;
9569         target = ccb->ccb_h.target_id;
9570         lun = ccb->ccb_h.target_lun;
9571         channel = SIM_CHANNEL(ahd, sim);
9572         target_mask = 0x01 << target;
9573         if (channel == 'B')
9574                 target_mask <<= 8;
9575
9576         if (cel->enable != 0) {
9577                 u_int scsiseq1;
9578
9579                 /* Are we already enabled?? */
9580                 if (lstate != NULL) {
9581                         xpt_print_path(ccb->ccb_h.path);
9582                         printf("Lun already enabled\n");
9583                         ccb->ccb_h.status = CAM_LUN_ALRDY_ENA;
9584                         return;
9585                 }
9586
9587                 if (cel->grp6_len != 0
9588                  || cel->grp7_len != 0) {
9589                         /*
9590                          * Don't (yet?) support vendor
9591                          * specific commands.
9592                          */
9593                         ccb->ccb_h.status = CAM_REQ_INVALID;
9594                         printf("Non-zero Group Codes\n");
9595                         return;
9596                 }
9597
9598                 /*
9599                  * Seems to be okay.
9600                  * Setup our data structures.
9601                  */
9602                 if (target != CAM_TARGET_WILDCARD && tstate == NULL) {
9603                         tstate = ahd_alloc_tstate(ahd, target, channel);
9604                         if (tstate == NULL) {
9605                                 xpt_print_path(ccb->ccb_h.path);
9606                                 printf("Couldn't allocate tstate\n");
9607                                 ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
9608                                 return;
9609                         }
9610                 }
9611                 lstate = malloc(sizeof(*lstate), M_DEVBUF, M_NOWAIT);
9612                 if (lstate == NULL) {
9613                         xpt_print_path(ccb->ccb_h.path);
9614                         printf("Couldn't allocate lstate\n");
9615                         ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
9616                         return;
9617                 }
9618                 memset(lstate, 0, sizeof(*lstate));
9619                 status = xpt_create_path(&lstate->path, /*periph*/NULL,
9620                                          xpt_path_path_id(ccb->ccb_h.path),
9621                                          xpt_path_target_id(ccb->ccb_h.path),
9622                                          xpt_path_lun_id(ccb->ccb_h.path));
9623                 if (status != CAM_REQ_CMP) {
9624                         free(lstate, M_DEVBUF);
9625                         xpt_print_path(ccb->ccb_h.path);
9626                         printf("Couldn't allocate path\n");
9627                         ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
9628                         return;
9629                 }
9630                 SLIST_INIT(&lstate->accept_tios);
9631                 SLIST_INIT(&lstate->immed_notifies);
9632                 ahd_lock(ahd, &s);
9633                 ahd_pause(ahd);
9634                 if (target != CAM_TARGET_WILDCARD) {
9635                         tstate->enabled_luns[lun] = lstate;
9636                         ahd->enabled_luns++;
9637
9638                         if ((ahd->features & AHD_MULTI_TID) != 0) {
9639                                 u_int targid_mask;
9640
9641                                 targid_mask = ahd_inw(ahd, TARGID);
9642                                 targid_mask |= target_mask;
9643                                 ahd_outw(ahd, TARGID, targid_mask);
9644                                 ahd_update_scsiid(ahd, targid_mask);
9645                         } else {
9646                                 u_int our_id;
9647                                 char  channel;
9648
9649                                 channel = SIM_CHANNEL(ahd, sim);
9650                                 our_id = SIM_SCSI_ID(ahd, sim);
9651
9652                                 /*
9653                                  * This can only happen if selections
9654                                  * are not enabled
9655                                  */
9656                                 if (target != our_id) {
9657                                         u_int sblkctl;
9658                                         char  cur_channel;
9659                                         int   swap;
9660
9661                                         sblkctl = ahd_inb(ahd, SBLKCTL);
9662                                         cur_channel = (sblkctl & SELBUSB)
9663                                                     ? 'B' : 'A';
9664                                         if ((ahd->features & AHD_TWIN) == 0)
9665                                                 cur_channel = 'A';
9666                                         swap = cur_channel != channel;
9667                                         ahd->our_id = target;
9668
9669                                         if (swap)
9670                                                 ahd_outb(ahd, SBLKCTL,
9671                                                          sblkctl ^ SELBUSB);
9672
9673                                         ahd_outb(ahd, SCSIID, target);
9674
9675                                         if (swap)
9676                                                 ahd_outb(ahd, SBLKCTL, sblkctl);
9677                                 }
9678                         }
9679                 } else
9680                         ahd->black_hole = lstate;
9681                 /* Allow select-in operations */
9682                 if (ahd->black_hole != NULL && ahd->enabled_luns > 0) {
9683                         scsiseq1 = ahd_inb(ahd, SCSISEQ_TEMPLATE);
9684                         scsiseq1 |= ENSELI;
9685                         ahd_outb(ahd, SCSISEQ_TEMPLATE, scsiseq1);
9686                         scsiseq1 = ahd_inb(ahd, SCSISEQ1);
9687                         scsiseq1 |= ENSELI;
9688                         ahd_outb(ahd, SCSISEQ1, scsiseq1);
9689                 }
9690                 ahd_unpause(ahd);
9691                 ahd_unlock(ahd, &s);
9692                 ccb->ccb_h.status = CAM_REQ_CMP;
9693                 xpt_print_path(ccb->ccb_h.path);
9694                 printf("Lun now enabled for target mode\n");
9695         } else {
9696                 struct scb *scb;
9697                 int i, empty;
9698
9699                 if (lstate == NULL) {
9700                         ccb->ccb_h.status = CAM_LUN_INVALID;
9701                         return;
9702                 }
9703
9704                 ahd_lock(ahd, &s);
9705                 
9706                 ccb->ccb_h.status = CAM_REQ_CMP;
9707                 LIST_FOREACH(scb, &ahd->pending_scbs, pending_links) {
9708                         struct ccb_hdr *ccbh;
9709
9710                         ccbh = &scb->io_ctx->ccb_h;
9711                         if (ccbh->func_code == XPT_CONT_TARGET_IO
9712                          && !xpt_path_comp(ccbh->path, ccb->ccb_h.path)){
9713                                 printf("CTIO pending\n");
9714                                 ccb->ccb_h.status = CAM_REQ_INVALID;
9715                                 ahd_unlock(ahd, &s);
9716                                 return;
9717                         }
9718                 }
9719
9720                 if (SLIST_FIRST(&lstate->accept_tios) != NULL) {
9721                         printf("ATIOs pending\n");
9722                         ccb->ccb_h.status = CAM_REQ_INVALID;
9723                 }
9724
9725                 if (SLIST_FIRST(&lstate->immed_notifies) != NULL) {
9726                         printf("INOTs pending\n");
9727                         ccb->ccb_h.status = CAM_REQ_INVALID;
9728                 }
9729
9730                 if (ccb->ccb_h.status != CAM_REQ_CMP) {
9731                         ahd_unlock(ahd, &s);
9732                         return;
9733                 }
9734
9735                 xpt_print_path(ccb->ccb_h.path);
9736                 printf("Target mode disabled\n");
9737                 xpt_free_path(lstate->path);
9738                 free(lstate, M_DEVBUF);
9739
9740                 ahd_pause(ahd);
9741                 /* Can we clean up the target too? */
9742                 if (target != CAM_TARGET_WILDCARD) {
9743                         tstate->enabled_luns[lun] = NULL;
9744                         ahd->enabled_luns--;
9745                         for (empty = 1, i = 0; i < 8; i++)
9746                                 if (tstate->enabled_luns[i] != NULL) {
9747                                         empty = 0;
9748                                         break;
9749                                 }
9750
9751                         if (empty) {
9752                                 ahd_free_tstate(ahd, target, channel,
9753                                                 /*force*/FALSE);
9754                                 if (ahd->features & AHD_MULTI_TID) {
9755                                         u_int targid_mask;
9756
9757                                         targid_mask = ahd_inw(ahd, TARGID);
9758                                         targid_mask &= ~target_mask;
9759                                         ahd_outw(ahd, TARGID, targid_mask);
9760                                         ahd_update_scsiid(ahd, targid_mask);
9761                                 }
9762                         }
9763                 } else {
9764
9765                         ahd->black_hole = NULL;
9766
9767                         /*
9768                          * We can't allow selections without
9769                          * our black hole device.
9770                          */
9771                         empty = TRUE;
9772                 }
9773                 if (ahd->enabled_luns == 0) {
9774                         /* Disallow select-in */
9775                         u_int scsiseq1;
9776
9777                         scsiseq1 = ahd_inb(ahd, SCSISEQ_TEMPLATE);
9778                         scsiseq1 &= ~ENSELI;
9779                         ahd_outb(ahd, SCSISEQ_TEMPLATE, scsiseq1);
9780                         scsiseq1 = ahd_inb(ahd, SCSISEQ1);
9781                         scsiseq1 &= ~ENSELI;
9782                         ahd_outb(ahd, SCSISEQ1, scsiseq1);
9783
9784                         if ((ahd->features & AHD_MULTIROLE) == 0) {
9785                                 printf("Configuring Initiator Mode\n");
9786                                 ahd->flags &= ~AHD_TARGETROLE;
9787                                 ahd->flags |= AHD_INITIATORROLE;
9788                                 ahd_pause(ahd);
9789                                 ahd_loadseq(ahd);
9790                                 ahd_restart(ahd);
9791                                 /*
9792                                  * Unpaused.  The extra unpause
9793                                  * that follows is harmless.
9794                                  */
9795                         }
9796                 }
9797                 ahd_unpause(ahd);
9798                 ahd_unlock(ahd, &s);
9799         }
9800 #endif
9801 }
9802
9803 static void
9804 ahd_update_scsiid(struct ahd_softc *ahd, u_int targid_mask)
9805 {
9806 #if NOT_YET
9807         u_int scsiid_mask;
9808         u_int scsiid;
9809
9810         if ((ahd->features & AHD_MULTI_TID) == 0)
9811                 panic("ahd_update_scsiid called on non-multitid unit\n");
9812
9813         /*
9814          * Since we will rely on the TARGID mask
9815          * for selection enables, ensure that OID
9816          * in SCSIID is not set to some other ID
9817          * that we don't want to allow selections on.
9818          */
9819         if ((ahd->features & AHD_ULTRA2) != 0)
9820                 scsiid = ahd_inb(ahd, SCSIID_ULTRA2);
9821         else
9822                 scsiid = ahd_inb(ahd, SCSIID);
9823         scsiid_mask = 0x1 << (scsiid & OID);
9824         if ((targid_mask & scsiid_mask) == 0) {
9825                 u_int our_id;
9826
9827                 /* ffs counts from 1 */
9828                 our_id = ffs(targid_mask);
9829                 if (our_id == 0)
9830                         our_id = ahd->our_id;
9831                 else
9832                         our_id--;
9833                 scsiid &= TID;
9834                 scsiid |= our_id;
9835         }
9836         if ((ahd->features & AHD_ULTRA2) != 0)
9837                 ahd_outb(ahd, SCSIID_ULTRA2, scsiid);
9838         else
9839                 ahd_outb(ahd, SCSIID, scsiid);
9840 #endif
9841 }
9842
9843 void
9844 ahd_run_tqinfifo(struct ahd_softc *ahd, int paused)
9845 {
9846         struct target_cmd *cmd;
9847
9848         ahd_sync_tqinfifo(ahd, BUS_DMASYNC_POSTREAD);
9849         while ((cmd = &ahd->targetcmds[ahd->tqinfifonext])->cmd_valid != 0) {
9850
9851                 /*
9852                  * Only advance through the queue if we
9853                  * have the resources to process the command.
9854                  */
9855                 if (ahd_handle_target_cmd(ahd, cmd) != 0)
9856                         break;
9857
9858                 cmd->cmd_valid = 0;
9859                 ahd_dmamap_sync(ahd, ahd->shared_data_dmat,
9860                                 ahd->shared_data_map.dmamap,
9861                                 ahd_targetcmd_offset(ahd, ahd->tqinfifonext),
9862                                 sizeof(struct target_cmd),
9863                                 BUS_DMASYNC_PREREAD);
9864                 ahd->tqinfifonext++;
9865
9866                 /*
9867                  * Lazily update our position in the target mode incoming
9868                  * command queue as seen by the sequencer.
9869                  */
9870                 if ((ahd->tqinfifonext & (HOST_TQINPOS - 1)) == 1) {
9871                         u_int hs_mailbox;
9872
9873                         hs_mailbox = ahd_inb(ahd, HS_MAILBOX);
9874                         hs_mailbox &= ~HOST_TQINPOS;
9875                         hs_mailbox |= ahd->tqinfifonext & HOST_TQINPOS;
9876                         ahd_outb(ahd, HS_MAILBOX, hs_mailbox);
9877                 }
9878         }
9879 }
9880
9881 static int
9882 ahd_handle_target_cmd(struct ahd_softc *ahd, struct target_cmd *cmd)
9883 {
9884         struct    ahd_tmode_tstate *tstate;
9885         struct    ahd_tmode_lstate *lstate;
9886         struct    ccb_accept_tio *atio;
9887         uint8_t *byte;
9888         int       initiator;
9889         int       target;
9890         int       lun;
9891
9892         initiator = SCSIID_TARGET(ahd, cmd->scsiid);
9893         target = SCSIID_OUR_ID(cmd->scsiid);
9894         lun    = (cmd->identify & MSG_IDENTIFY_LUNMASK);
9895
9896         byte = cmd->bytes;
9897         tstate = ahd->enabled_targets[target];
9898         lstate = NULL;
9899         if (tstate != NULL)
9900                 lstate = tstate->enabled_luns[lun];
9901
9902         /*
9903          * Commands for disabled luns go to the black hole driver.
9904          */
9905         if (lstate == NULL)
9906                 lstate = ahd->black_hole;
9907
9908         atio = (struct ccb_accept_tio*)SLIST_FIRST(&lstate->accept_tios);
9909         if (atio == NULL) {
9910                 ahd->flags |= AHD_TQINFIFO_BLOCKED;
9911                 /*
9912                  * Wait for more ATIOs from the peripheral driver for this lun.
9913                  */
9914                 return (1);
9915         } else
9916                 ahd->flags &= ~AHD_TQINFIFO_BLOCKED;
9917 #ifdef AHD_DEBUG
9918         if ((ahd_debug & AHD_SHOW_TQIN) != 0)
9919                 printf("Incoming command from %d for %d:%d%s\n",
9920                        initiator, target, lun,
9921                        lstate == ahd->black_hole ? "(Black Holed)" : "");
9922 #endif
9923         SLIST_REMOVE_HEAD(&lstate->accept_tios, sim_links.sle);
9924
9925         if (lstate == ahd->black_hole) {
9926                 /* Fill in the wildcards */
9927                 atio->ccb_h.target_id = target;
9928                 atio->ccb_h.target_lun = lun;
9929         }
9930
9931         /*
9932          * Package it up and send it off to
9933          * whomever has this lun enabled.
9934          */
9935         atio->sense_len = 0;
9936         atio->init_id = initiator;
9937         if (byte[0] != 0xFF) {
9938                 /* Tag was included */
9939                 atio->tag_action = *byte++;
9940                 atio->tag_id = *byte++;
9941                 atio->ccb_h.flags = CAM_TAG_ACTION_VALID;
9942         } else {
9943                 atio->ccb_h.flags = 0;
9944         }
9945         byte++;
9946
9947         /* Okay.  Now determine the cdb size based on the command code */
9948         switch (*byte >> CMD_GROUP_CODE_SHIFT) {
9949         case 0:
9950                 atio->cdb_len = 6;
9951                 break;
9952         case 1:
9953         case 2:
9954                 atio->cdb_len = 10;
9955                 break;
9956         case 4:
9957                 atio->cdb_len = 16;
9958                 break;
9959         case 5:
9960                 atio->cdb_len = 12;
9961                 break;
9962         case 3:
9963         default:
9964                 /* Only copy the opcode. */
9965                 atio->cdb_len = 1;
9966                 printf("Reserved or VU command code type encountered\n");
9967                 break;
9968         }
9969         
9970         memcpy(atio->cdb_io.cdb_bytes, byte, atio->cdb_len);
9971
9972         atio->ccb_h.status |= CAM_CDB_RECVD;
9973
9974         if ((cmd->identify & MSG_IDENTIFY_DISCFLAG) == 0) {
9975                 /*
9976                  * We weren't allowed to disconnect.
9977                  * We're hanging on the bus until a
9978                  * continue target I/O comes in response
9979                  * to this accept tio.
9980                  */
9981 #ifdef AHD_DEBUG
9982                 if ((ahd_debug & AHD_SHOW_TQIN) != 0)
9983                         printf("Received Immediate Command %d:%d:%d - %p\n",
9984                                initiator, target, lun, ahd->pending_device);
9985 #endif
9986                 ahd->pending_device = lstate;
9987                 ahd_freeze_ccb((union ccb *)atio);
9988                 atio->ccb_h.flags |= CAM_DIS_DISCONNECT;
9989         }
9990         xpt_done((union ccb*)atio);
9991         return (0);
9992 }
9993
9994 #endif