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