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