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