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