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