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