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