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