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