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