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