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