[SCSI] Add spi_populate_*_msg functions
[safe/jmp/linux-2.6] / drivers / scsi / aic7xxx / aic7xxx_core.c
1 /*
2  * Core routines and tables shareable across OS platforms.
3  *
4  * Copyright (c) 1994-2002 Justin T. Gibbs.
5  * Copyright (c) 2000-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/aic7xxx.c#155 $
41  */
42
43 #ifdef __linux__
44 #include "aic7xxx_osm.h"
45 #include "aic7xxx_inline.h"
46 #include "aicasm/aicasm_insformat.h"
47 #else
48 #include <dev/aic7xxx/aic7xxx_osm.h>
49 #include <dev/aic7xxx/aic7xxx_inline.h>
50 #include <dev/aic7xxx/aicasm/aicasm_insformat.h>
51 #endif
52
53 /***************************** Lookup Tables **********************************/
54 char *ahc_chip_names[] =
55 {
56         "NONE",
57         "aic7770",
58         "aic7850",
59         "aic7855",
60         "aic7859",
61         "aic7860",
62         "aic7870",
63         "aic7880",
64         "aic7895",
65         "aic7895C",
66         "aic7890/91",
67         "aic7896/97",
68         "aic7892",
69         "aic7899"
70 };
71 static const u_int num_chip_names = NUM_ELEMENTS(ahc_chip_names);
72
73 /*
74  * Hardware error codes.
75  */
76 struct ahc_hard_error_entry {
77         uint8_t errno;
78         char *errmesg;
79 };
80
81 static struct ahc_hard_error_entry ahc_hard_errors[] = {
82         { ILLHADDR,     "Illegal Host Access" },
83         { ILLSADDR,     "Illegal Sequencer Address referrenced" },
84         { ILLOPCODE,    "Illegal Opcode in sequencer program" },
85         { SQPARERR,     "Sequencer Parity Error" },
86         { DPARERR,      "Data-path Parity Error" },
87         { MPARERR,      "Scratch or SCB Memory Parity Error" },
88         { PCIERRSTAT,   "PCI Error detected" },
89         { CIOPARERR,    "CIOBUS Parity Error" },
90 };
91 static const u_int num_errors = NUM_ELEMENTS(ahc_hard_errors);
92
93 static struct ahc_phase_table_entry ahc_phase_table[] =
94 {
95         { P_DATAOUT,    MSG_NOOP,               "in Data-out phase"     },
96         { P_DATAIN,     MSG_INITIATOR_DET_ERR,  "in Data-in phase"      },
97         { P_DATAOUT_DT, MSG_NOOP,               "in DT Data-out phase"  },
98         { P_DATAIN_DT,  MSG_INITIATOR_DET_ERR,  "in DT Data-in phase"   },
99         { P_COMMAND,    MSG_NOOP,               "in Command phase"      },
100         { P_MESGOUT,    MSG_NOOP,               "in Message-out phase"  },
101         { P_STATUS,     MSG_INITIATOR_DET_ERR,  "in Status phase"       },
102         { P_MESGIN,     MSG_PARITY_ERROR,       "in Message-in phase"   },
103         { P_BUSFREE,    MSG_NOOP,               "while idle"            },
104         { 0,            MSG_NOOP,               "in unknown phase"      }
105 };
106
107 /*
108  * In most cases we only wish to itterate over real phases, so
109  * exclude the last element from the count.
110  */
111 static const u_int num_phases = NUM_ELEMENTS(ahc_phase_table) - 1;
112
113 /*
114  * Valid SCSIRATE values.  (p. 3-17)
115  * Provides a mapping of tranfer periods in ns to the proper value to
116  * stick in the scsixfer reg.
117  */
118 static struct ahc_syncrate ahc_syncrates[] =
119 {
120       /* ultra2    fast/ultra  period     rate */
121         { 0x42,      0x000,      9,      "80.0" },
122         { 0x03,      0x000,     10,      "40.0" },
123         { 0x04,      0x000,     11,      "33.0" },
124         { 0x05,      0x100,     12,      "20.0" },
125         { 0x06,      0x110,     15,      "16.0" },
126         { 0x07,      0x120,     18,      "13.4" },
127         { 0x08,      0x000,     25,      "10.0" },
128         { 0x19,      0x010,     31,      "8.0"  },
129         { 0x1a,      0x020,     37,      "6.67" },
130         { 0x1b,      0x030,     43,      "5.7"  },
131         { 0x1c,      0x040,     50,      "5.0"  },
132         { 0x00,      0x050,     56,      "4.4"  },
133         { 0x00,      0x060,     62,      "4.0"  },
134         { 0x00,      0x070,     68,      "3.6"  },
135         { 0x00,      0x000,      0,      NULL   }
136 };
137
138 /* Our Sequencer Program */
139 #include "aic7xxx_seq.h"
140
141 /**************************** Function Declarations ***************************/
142 static void             ahc_force_renegotiation(struct ahc_softc *ahc,
143                                                 struct ahc_devinfo *devinfo);
144 static struct ahc_tmode_tstate*
145                         ahc_alloc_tstate(struct ahc_softc *ahc,
146                                          u_int scsi_id, char channel);
147 #ifdef AHC_TARGET_MODE
148 static void             ahc_free_tstate(struct ahc_softc *ahc,
149                                         u_int scsi_id, char channel, int force);
150 #endif
151 static struct ahc_syncrate*
152                         ahc_devlimited_syncrate(struct ahc_softc *ahc,
153                                                 struct ahc_initiator_tinfo *,
154                                                 u_int *period,
155                                                 u_int *ppr_options,
156                                                 role_t role);
157 static void             ahc_update_pending_scbs(struct ahc_softc *ahc);
158 static void             ahc_fetch_devinfo(struct ahc_softc *ahc,
159                                           struct ahc_devinfo *devinfo);
160 static void             ahc_scb_devinfo(struct ahc_softc *ahc,
161                                         struct ahc_devinfo *devinfo,
162                                         struct scb *scb);
163 static void             ahc_assert_atn(struct ahc_softc *ahc);
164 static void             ahc_setup_initiator_msgout(struct ahc_softc *ahc,
165                                                    struct ahc_devinfo *devinfo,
166                                                    struct scb *scb);
167 static void             ahc_build_transfer_msg(struct ahc_softc *ahc,
168                                                struct ahc_devinfo *devinfo);
169 static void             ahc_construct_sdtr(struct ahc_softc *ahc,
170                                            struct ahc_devinfo *devinfo,
171                                            u_int period, u_int offset);
172 static void             ahc_construct_wdtr(struct ahc_softc *ahc,
173                                            struct ahc_devinfo *devinfo,
174                                            u_int bus_width);
175 static void             ahc_construct_ppr(struct ahc_softc *ahc,
176                                           struct ahc_devinfo *devinfo,
177                                           u_int period, u_int offset,
178                                           u_int bus_width, u_int ppr_options);
179 static void             ahc_clear_msg_state(struct ahc_softc *ahc);
180 static void             ahc_handle_proto_violation(struct ahc_softc *ahc);
181 static void             ahc_handle_message_phase(struct ahc_softc *ahc);
182 typedef enum {
183         AHCMSG_1B,
184         AHCMSG_2B,
185         AHCMSG_EXT
186 } ahc_msgtype;
187 static int              ahc_sent_msg(struct ahc_softc *ahc, ahc_msgtype type,
188                                      u_int msgval, int full);
189 static int              ahc_parse_msg(struct ahc_softc *ahc,
190                                       struct ahc_devinfo *devinfo);
191 static int              ahc_handle_msg_reject(struct ahc_softc *ahc,
192                                               struct ahc_devinfo *devinfo);
193 static void             ahc_handle_ign_wide_residue(struct ahc_softc *ahc,
194                                                 struct ahc_devinfo *devinfo);
195 static void             ahc_reinitialize_dataptrs(struct ahc_softc *ahc);
196 static void             ahc_handle_devreset(struct ahc_softc *ahc,
197                                             struct ahc_devinfo *devinfo,
198                                             cam_status status, char *message,
199                                             int verbose_level);
200 #ifdef AHC_TARGET_MODE
201 static void             ahc_setup_target_msgin(struct ahc_softc *ahc,
202                                                struct ahc_devinfo *devinfo,
203                                                struct scb *scb);
204 #endif
205
206 static bus_dmamap_callback_t    ahc_dmamap_cb; 
207 static void                     ahc_build_free_scb_list(struct ahc_softc *ahc);
208 static int                      ahc_init_scbdata(struct ahc_softc *ahc);
209 static void                     ahc_fini_scbdata(struct ahc_softc *ahc);
210 static void             ahc_qinfifo_requeue(struct ahc_softc *ahc,
211                                             struct scb *prev_scb,
212                                             struct scb *scb);
213 static int              ahc_qinfifo_count(struct ahc_softc *ahc);
214 static u_int            ahc_rem_scb_from_disc_list(struct ahc_softc *ahc,
215                                                    u_int prev, u_int scbptr);
216 static void             ahc_add_curscb_to_free_list(struct ahc_softc *ahc);
217 static u_int            ahc_rem_wscb(struct ahc_softc *ahc,
218                                      u_int scbpos, u_int prev);
219 static void             ahc_reset_current_bus(struct ahc_softc *ahc);
220 #ifdef AHC_DUMP_SEQ
221 static void             ahc_dumpseq(struct ahc_softc *ahc);
222 #endif
223 static int              ahc_loadseq(struct ahc_softc *ahc);
224 static int              ahc_check_patch(struct ahc_softc *ahc,
225                                         struct patch **start_patch,
226                                         u_int start_instr, u_int *skip_addr);
227 static void             ahc_download_instr(struct ahc_softc *ahc,
228                                            u_int instrptr, uint8_t *dconsts);
229 #ifdef AHC_TARGET_MODE
230 static void             ahc_queue_lstate_event(struct ahc_softc *ahc,
231                                                struct ahc_tmode_lstate *lstate,
232                                                u_int initiator_id,
233                                                u_int event_type,
234                                                u_int event_arg);
235 static void             ahc_update_scsiid(struct ahc_softc *ahc,
236                                           u_int targid_mask);
237 static int              ahc_handle_target_cmd(struct ahc_softc *ahc,
238                                               struct target_cmd *cmd);
239 #endif
240 /************************* Sequencer Execution Control ************************/
241 /*
242  * Restart the sequencer program from address zero
243  */
244 void
245 ahc_restart(struct ahc_softc *ahc)
246 {
247
248         ahc_pause(ahc);
249
250         /* No more pending messages. */
251         ahc_clear_msg_state(ahc);
252
253         ahc_outb(ahc, SCSISIGO, 0);             /* De-assert BSY */
254         ahc_outb(ahc, MSG_OUT, MSG_NOOP);       /* No message to send */
255         ahc_outb(ahc, SXFRCTL1, ahc_inb(ahc, SXFRCTL1) & ~BITBUCKET);
256         ahc_outb(ahc, LASTPHASE, P_BUSFREE);
257         ahc_outb(ahc, SAVED_SCSIID, 0xFF);
258         ahc_outb(ahc, SAVED_LUN, 0xFF);
259
260         /*
261          * Ensure that the sequencer's idea of TQINPOS
262          * matches our own.  The sequencer increments TQINPOS
263          * only after it sees a DMA complete and a reset could
264          * occur before the increment leaving the kernel to believe
265          * the command arrived but the sequencer to not.
266          */
267         ahc_outb(ahc, TQINPOS, ahc->tqinfifonext);
268
269         /* Always allow reselection */
270         ahc_outb(ahc, SCSISEQ,
271                  ahc_inb(ahc, SCSISEQ_TEMPLATE) & (ENSELI|ENRSELI|ENAUTOATNP));
272         if ((ahc->features & AHC_CMD_CHAN) != 0) {
273                 /* Ensure that no DMA operations are in progress */
274                 ahc_outb(ahc, CCSCBCNT, 0);
275                 ahc_outb(ahc, CCSGCTL, 0);
276                 ahc_outb(ahc, CCSCBCTL, 0);
277         }
278         /*
279          * If we were in the process of DMA'ing SCB data into
280          * an SCB, replace that SCB on the free list.  This prevents
281          * an SCB leak.
282          */
283         if ((ahc_inb(ahc, SEQ_FLAGS2) & SCB_DMA) != 0) {
284                 ahc_add_curscb_to_free_list(ahc);
285                 ahc_outb(ahc, SEQ_FLAGS2,
286                          ahc_inb(ahc, SEQ_FLAGS2) & ~SCB_DMA);
287         }
288
289         /*
290          * Clear any pending sequencer interrupt.  It is no
291          * longer relevant since we're resetting the Program
292          * Counter.
293          */
294         ahc_outb(ahc, CLRINT, CLRSEQINT);
295
296         ahc_outb(ahc, MWI_RESIDUAL, 0);
297         ahc_outb(ahc, SEQCTL, ahc->seqctl);
298         ahc_outb(ahc, SEQADDR0, 0);
299         ahc_outb(ahc, SEQADDR1, 0);
300
301         ahc_unpause(ahc);
302 }
303
304 /************************* Input/Output Queues ********************************/
305 void
306 ahc_run_qoutfifo(struct ahc_softc *ahc)
307 {
308         struct scb *scb;
309         u_int  scb_index;
310
311         ahc_sync_qoutfifo(ahc, BUS_DMASYNC_POSTREAD);
312         while (ahc->qoutfifo[ahc->qoutfifonext] != SCB_LIST_NULL) {
313
314                 scb_index = ahc->qoutfifo[ahc->qoutfifonext];
315                 if ((ahc->qoutfifonext & 0x03) == 0x03) {
316                         u_int modnext;
317
318                         /*
319                          * Clear 32bits of QOUTFIFO at a time
320                          * so that we don't clobber an incoming
321                          * byte DMA to the array on architectures
322                          * that only support 32bit load and store
323                          * operations.
324                          */
325                         modnext = ahc->qoutfifonext & ~0x3;
326                         *((uint32_t *)(&ahc->qoutfifo[modnext])) = 0xFFFFFFFFUL;
327                         ahc_dmamap_sync(ahc, ahc->shared_data_dmat,
328                                         ahc->shared_data_dmamap,
329                                         /*offset*/modnext, /*len*/4,
330                                         BUS_DMASYNC_PREREAD);
331                 }
332                 ahc->qoutfifonext++;
333
334                 scb = ahc_lookup_scb(ahc, scb_index);
335                 if (scb == NULL) {
336                         printf("%s: WARNING no command for scb %d "
337                                "(cmdcmplt)\nQOUTPOS = %d\n",
338                                ahc_name(ahc), scb_index,
339                                (ahc->qoutfifonext - 1) & 0xFF);
340                         continue;
341                 }
342
343                 /*
344                  * Save off the residual
345                  * if there is one.
346                  */
347                 ahc_update_residual(ahc, scb);
348                 ahc_done(ahc, scb);
349         }
350 }
351
352 void
353 ahc_run_untagged_queues(struct ahc_softc *ahc)
354 {
355         int i;
356
357         for (i = 0; i < 16; i++)
358                 ahc_run_untagged_queue(ahc, &ahc->untagged_queues[i]);
359 }
360
361 void
362 ahc_run_untagged_queue(struct ahc_softc *ahc, struct scb_tailq *queue)
363 {
364         struct scb *scb;
365
366         if (ahc->untagged_queue_lock != 0)
367                 return;
368
369         if ((scb = TAILQ_FIRST(queue)) != NULL
370          && (scb->flags & SCB_ACTIVE) == 0) {
371                 scb->flags |= SCB_ACTIVE;
372                 ahc_queue_scb(ahc, scb);
373         }
374 }
375
376 /************************* Interrupt Handling *********************************/
377 void
378 ahc_handle_brkadrint(struct ahc_softc *ahc)
379 {
380         /*
381          * We upset the sequencer :-(
382          * Lookup the error message
383          */
384         int i;
385         int error;
386
387         error = ahc_inb(ahc, ERROR);
388         for (i = 0; error != 1 && i < num_errors; i++)
389                 error >>= 1;
390         printf("%s: brkadrint, %s at seqaddr = 0x%x\n",
391                ahc_name(ahc), ahc_hard_errors[i].errmesg,
392                ahc_inb(ahc, SEQADDR0) |
393                (ahc_inb(ahc, SEQADDR1) << 8));
394
395         ahc_dump_card_state(ahc);
396
397         /* Tell everyone that this HBA is no longer available */
398         ahc_abort_scbs(ahc, CAM_TARGET_WILDCARD, ALL_CHANNELS,
399                        CAM_LUN_WILDCARD, SCB_LIST_NULL, ROLE_UNKNOWN,
400                        CAM_NO_HBA);
401
402         /* Disable all interrupt sources by resetting the controller */
403         ahc_shutdown(ahc);
404 }
405
406 void
407 ahc_handle_seqint(struct ahc_softc *ahc, u_int intstat)
408 {
409         struct scb *scb;
410         struct ahc_devinfo devinfo;
411         
412         ahc_fetch_devinfo(ahc, &devinfo);
413
414         /*
415          * Clear the upper byte that holds SEQINT status
416          * codes and clear the SEQINT bit. We will unpause
417          * the sequencer, if appropriate, after servicing
418          * the request.
419          */
420         ahc_outb(ahc, CLRINT, CLRSEQINT);
421         switch (intstat & SEQINT_MASK) {
422         case BAD_STATUS:
423         {
424                 u_int  scb_index;
425                 struct hardware_scb *hscb;
426
427                 /*
428                  * Set the default return value to 0 (don't
429                  * send sense).  The sense code will change
430                  * this if needed.
431                  */
432                 ahc_outb(ahc, RETURN_1, 0);
433
434                 /*
435                  * The sequencer will notify us when a command
436                  * has an error that would be of interest to
437                  * the kernel.  This allows us to leave the sequencer
438                  * running in the common case of command completes
439                  * without error.  The sequencer will already have
440                  * dma'd the SCB back up to us, so we can reference
441                  * the in kernel copy directly.
442                  */
443                 scb_index = ahc_inb(ahc, SCB_TAG);
444                 scb = ahc_lookup_scb(ahc, scb_index);
445                 if (scb == NULL) {
446                         ahc_print_devinfo(ahc, &devinfo);
447                         printf("ahc_intr - referenced scb "
448                                "not valid during seqint 0x%x scb(%d)\n",
449                                intstat, scb_index);
450                         ahc_dump_card_state(ahc);
451                         panic("for safety");
452                         goto unpause;
453                 }
454
455                 hscb = scb->hscb; 
456
457                 /* Don't want to clobber the original sense code */
458                 if ((scb->flags & SCB_SENSE) != 0) {
459                         /*
460                          * Clear the SCB_SENSE Flag and have
461                          * the sequencer do a normal command
462                          * complete.
463                          */
464                         scb->flags &= ~SCB_SENSE;
465                         ahc_set_transaction_status(scb, CAM_AUTOSENSE_FAIL);
466                         break;
467                 }
468                 ahc_set_transaction_status(scb, CAM_SCSI_STATUS_ERROR);
469                 /* Freeze the queue until the client sees the error. */
470                 ahc_freeze_devq(ahc, scb);
471                 ahc_freeze_scb(scb);
472                 ahc_set_scsi_status(scb, hscb->shared_data.status.scsi_status);
473                 switch (hscb->shared_data.status.scsi_status) {
474                 case SCSI_STATUS_OK:
475                         printf("%s: Interrupted for staus of 0???\n",
476                                ahc_name(ahc));
477                         break;
478                 case SCSI_STATUS_CMD_TERMINATED:
479                 case SCSI_STATUS_CHECK_COND:
480                 {
481                         struct ahc_dma_seg *sg;
482                         struct scsi_sense *sc;
483                         struct ahc_initiator_tinfo *targ_info;
484                         struct ahc_tmode_tstate *tstate;
485                         struct ahc_transinfo *tinfo;
486 #ifdef AHC_DEBUG
487                         if (ahc_debug & AHC_SHOW_SENSE) {
488                                 ahc_print_path(ahc, scb);
489                                 printf("SCB %d: requests Check Status\n",
490                                        scb->hscb->tag);
491                         }
492 #endif
493
494                         if (ahc_perform_autosense(scb) == 0)
495                                 break;
496
497                         targ_info = ahc_fetch_transinfo(ahc,
498                                                         devinfo.channel,
499                                                         devinfo.our_scsiid,
500                                                         devinfo.target,
501                                                         &tstate);
502                         tinfo = &targ_info->curr;
503                         sg = scb->sg_list;
504                         sc = (struct scsi_sense *)(&hscb->shared_data.cdb); 
505                         /*
506                          * Save off the residual if there is one.
507                          */
508                         ahc_update_residual(ahc, scb);
509 #ifdef AHC_DEBUG
510                         if (ahc_debug & AHC_SHOW_SENSE) {
511                                 ahc_print_path(ahc, scb);
512                                 printf("Sending Sense\n");
513                         }
514 #endif
515                         sg->addr = ahc_get_sense_bufaddr(ahc, scb);
516                         sg->len = ahc_get_sense_bufsize(ahc, scb);
517                         sg->len |= AHC_DMA_LAST_SEG;
518
519                         /* Fixup byte order */
520                         sg->addr = ahc_htole32(sg->addr);
521                         sg->len = ahc_htole32(sg->len);
522
523                         sc->opcode = REQUEST_SENSE;
524                         sc->byte2 = 0;
525                         if (tinfo->protocol_version <= SCSI_REV_2
526                          && SCB_GET_LUN(scb) < 8)
527                                 sc->byte2 = SCB_GET_LUN(scb) << 5;
528                         sc->unused[0] = 0;
529                         sc->unused[1] = 0;
530                         sc->length = sg->len;
531                         sc->control = 0;
532
533                         /*
534                          * We can't allow the target to disconnect.
535                          * This will be an untagged transaction and
536                          * having the target disconnect will make this
537                          * transaction indestinguishable from outstanding
538                          * tagged transactions.
539                          */
540                         hscb->control = 0;
541
542                         /*
543                          * This request sense could be because the
544                          * the device lost power or in some other
545                          * way has lost our transfer negotiations.
546                          * Renegotiate if appropriate.  Unit attention
547                          * errors will be reported before any data
548                          * phases occur.
549                          */
550                         if (ahc_get_residual(scb) 
551                          == ahc_get_transfer_length(scb)) {
552                                 ahc_update_neg_request(ahc, &devinfo,
553                                                        tstate, targ_info,
554                                                        AHC_NEG_IF_NON_ASYNC);
555                         }
556                         if (tstate->auto_negotiate & devinfo.target_mask) {
557                                 hscb->control |= MK_MESSAGE;
558                                 scb->flags &= ~SCB_NEGOTIATE;
559                                 scb->flags |= SCB_AUTO_NEGOTIATE;
560                         }
561                         hscb->cdb_len = sizeof(*sc);
562                         hscb->dataptr = sg->addr; 
563                         hscb->datacnt = sg->len;
564                         hscb->sgptr = scb->sg_list_phys | SG_FULL_RESID;
565                         hscb->sgptr = ahc_htole32(hscb->sgptr);
566                         scb->sg_count = 1;
567                         scb->flags |= SCB_SENSE;
568                         ahc_qinfifo_requeue_tail(ahc, scb);
569                         ahc_outb(ahc, RETURN_1, SEND_SENSE);
570                         /*
571                          * Ensure we have enough time to actually
572                          * retrieve the sense.
573                          */
574                         ahc_scb_timer_reset(scb, 5 * 1000000);
575                         break;
576                 }
577                 default:
578                         break;
579                 }
580                 break;
581         }
582         case NO_MATCH:
583         {
584                 /* Ensure we don't leave the selection hardware on */
585                 ahc_outb(ahc, SCSISEQ,
586                          ahc_inb(ahc, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP));
587
588                 printf("%s:%c:%d: no active SCB for reconnecting "
589                        "target - issuing BUS DEVICE RESET\n",
590                        ahc_name(ahc), devinfo.channel, devinfo.target);
591                 printf("SAVED_SCSIID == 0x%x, SAVED_LUN == 0x%x, "
592                        "ARG_1 == 0x%x ACCUM = 0x%x\n",
593                        ahc_inb(ahc, SAVED_SCSIID), ahc_inb(ahc, SAVED_LUN),
594                        ahc_inb(ahc, ARG_1), ahc_inb(ahc, ACCUM));
595                 printf("SEQ_FLAGS == 0x%x, SCBPTR == 0x%x, BTT == 0x%x, "
596                        "SINDEX == 0x%x\n",
597                        ahc_inb(ahc, SEQ_FLAGS), ahc_inb(ahc, SCBPTR),
598                        ahc_index_busy_tcl(ahc,
599                             BUILD_TCL(ahc_inb(ahc, SAVED_SCSIID),
600                                       ahc_inb(ahc, SAVED_LUN))),
601                        ahc_inb(ahc, SINDEX));
602                 printf("SCSIID == 0x%x, SCB_SCSIID == 0x%x, SCB_LUN == 0x%x, "
603                        "SCB_TAG == 0x%x, SCB_CONTROL == 0x%x\n",
604                        ahc_inb(ahc, SCSIID), ahc_inb(ahc, SCB_SCSIID),
605                        ahc_inb(ahc, SCB_LUN), ahc_inb(ahc, SCB_TAG),
606                        ahc_inb(ahc, SCB_CONTROL));
607                 printf("SCSIBUSL == 0x%x, SCSISIGI == 0x%x\n",
608                        ahc_inb(ahc, SCSIBUSL), ahc_inb(ahc, SCSISIGI));
609                 printf("SXFRCTL0 == 0x%x\n", ahc_inb(ahc, SXFRCTL0));
610                 printf("SEQCTL == 0x%x\n", ahc_inb(ahc, SEQCTL));
611                 ahc_dump_card_state(ahc);
612                 ahc->msgout_buf[0] = MSG_BUS_DEV_RESET;
613                 ahc->msgout_len = 1;
614                 ahc->msgout_index = 0;
615                 ahc->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
616                 ahc_outb(ahc, MSG_OUT, HOST_MSG);
617                 ahc_assert_atn(ahc);
618                 break;
619         }
620         case SEND_REJECT: 
621         {
622                 u_int rejbyte = ahc_inb(ahc, ACCUM);
623                 printf("%s:%c:%d: Warning - unknown message received from "
624                        "target (0x%x).  Rejecting\n", 
625                        ahc_name(ahc), devinfo.channel, devinfo.target, rejbyte);
626                 break; 
627         }
628         case PROTO_VIOLATION:
629         {
630                 ahc_handle_proto_violation(ahc);
631                 break;
632         }
633         case IGN_WIDE_RES:
634                 ahc_handle_ign_wide_residue(ahc, &devinfo);
635                 break;
636         case PDATA_REINIT:
637                 ahc_reinitialize_dataptrs(ahc);
638                 break;
639         case BAD_PHASE:
640         {
641                 u_int lastphase;
642
643                 lastphase = ahc_inb(ahc, LASTPHASE);
644                 printf("%s:%c:%d: unknown scsi bus phase %x, "
645                        "lastphase = 0x%x.  Attempting to continue\n",
646                        ahc_name(ahc), devinfo.channel, devinfo.target,
647                        lastphase, ahc_inb(ahc, SCSISIGI));
648                 break;
649         }
650         case MISSED_BUSFREE:
651         {
652                 u_int lastphase;
653
654                 lastphase = ahc_inb(ahc, LASTPHASE);
655                 printf("%s:%c:%d: Missed busfree. "
656                        "Lastphase = 0x%x, Curphase = 0x%x\n",
657                        ahc_name(ahc), devinfo.channel, devinfo.target,
658                        lastphase, ahc_inb(ahc, SCSISIGI));
659                 ahc_restart(ahc);
660                 return;
661         }
662         case HOST_MSG_LOOP:
663         {
664                 /*
665                  * The sequencer has encountered a message phase
666                  * that requires host assistance for completion.
667                  * While handling the message phase(s), we will be
668                  * notified by the sequencer after each byte is
669                  * transfered so we can track bus phase changes.
670                  *
671                  * If this is the first time we've seen a HOST_MSG_LOOP
672                  * interrupt, initialize the state of the host message
673                  * loop.
674                  */
675                 if (ahc->msg_type == MSG_TYPE_NONE) {
676                         struct scb *scb;
677                         u_int scb_index;
678                         u_int bus_phase;
679
680                         bus_phase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
681                         if (bus_phase != P_MESGIN
682                          && bus_phase != P_MESGOUT) {
683                                 printf("ahc_intr: HOST_MSG_LOOP bad "
684                                        "phase 0x%x\n",
685                                       bus_phase);
686                                 /*
687                                  * Probably transitioned to bus free before
688                                  * we got here.  Just punt the message.
689                                  */
690                                 ahc_clear_intstat(ahc);
691                                 ahc_restart(ahc);
692                                 return;
693                         }
694
695                         scb_index = ahc_inb(ahc, SCB_TAG);
696                         scb = ahc_lookup_scb(ahc, scb_index);
697                         if (devinfo.role == ROLE_INITIATOR) {
698                                 if (scb == NULL)
699                                         panic("HOST_MSG_LOOP with "
700                                               "invalid SCB %x\n", scb_index);
701
702                                 if (bus_phase == P_MESGOUT)
703                                         ahc_setup_initiator_msgout(ahc,
704                                                                    &devinfo,
705                                                                    scb);
706                                 else {
707                                         ahc->msg_type =
708                                             MSG_TYPE_INITIATOR_MSGIN;
709                                         ahc->msgin_index = 0;
710                                 }
711                         }
712 #ifdef AHC_TARGET_MODE
713                         else {
714                                 if (bus_phase == P_MESGOUT) {
715                                         ahc->msg_type =
716                                             MSG_TYPE_TARGET_MSGOUT;
717                                         ahc->msgin_index = 0;
718                                 }
719                                 else 
720                                         ahc_setup_target_msgin(ahc,
721                                                                &devinfo,
722                                                                scb);
723                         }
724 #endif
725                 }
726
727                 ahc_handle_message_phase(ahc);
728                 break;
729         }
730         case PERR_DETECTED:
731         {
732                 /*
733                  * If we've cleared the parity error interrupt
734                  * but the sequencer still believes that SCSIPERR
735                  * is true, it must be that the parity error is
736                  * for the currently presented byte on the bus,
737                  * and we are not in a phase (data-in) where we will
738                  * eventually ack this byte.  Ack the byte and
739                  * throw it away in the hope that the target will
740                  * take us to message out to deliver the appropriate
741                  * error message.
742                  */
743                 if ((intstat & SCSIINT) == 0
744                  && (ahc_inb(ahc, SSTAT1) & SCSIPERR) != 0) {
745
746                         if ((ahc->features & AHC_DT) == 0) {
747                                 u_int curphase;
748
749                                 /*
750                                  * The hardware will only let you ack bytes
751                                  * if the expected phase in SCSISIGO matches
752                                  * the current phase.  Make sure this is
753                                  * currently the case.
754                                  */
755                                 curphase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
756                                 ahc_outb(ahc, LASTPHASE, curphase);
757                                 ahc_outb(ahc, SCSISIGO, curphase);
758                         }
759                         if ((ahc_inb(ahc, SCSISIGI) & (CDI|MSGI)) == 0) {
760                                 int wait;
761
762                                 /*
763                                  * In a data phase.  Faster to bitbucket
764                                  * the data than to individually ack each
765                                  * byte.  This is also the only strategy
766                                  * that will work with AUTOACK enabled.
767                                  */
768                                 ahc_outb(ahc, SXFRCTL1,
769                                          ahc_inb(ahc, SXFRCTL1) | BITBUCKET);
770                                 wait = 5000;
771                                 while (--wait != 0) {
772                                         if ((ahc_inb(ahc, SCSISIGI)
773                                           & (CDI|MSGI)) != 0)
774                                                 break;
775                                         ahc_delay(100);
776                                 }
777                                 ahc_outb(ahc, SXFRCTL1,
778                                          ahc_inb(ahc, SXFRCTL1) & ~BITBUCKET);
779                                 if (wait == 0) {
780                                         struct  scb *scb;
781                                         u_int   scb_index;
782
783                                         ahc_print_devinfo(ahc, &devinfo);
784                                         printf("Unable to clear parity error.  "
785                                                "Resetting bus.\n");
786                                         scb_index = ahc_inb(ahc, SCB_TAG);
787                                         scb = ahc_lookup_scb(ahc, scb_index);
788                                         if (scb != NULL)
789                                                 ahc_set_transaction_status(scb,
790                                                     CAM_UNCOR_PARITY);
791                                         ahc_reset_channel(ahc, devinfo.channel, 
792                                                           /*init reset*/TRUE);
793                                 }
794                         } else {
795                                 ahc_inb(ahc, SCSIDATL);
796                         }
797                 }
798                 break;
799         }
800         case DATA_OVERRUN:
801         {
802                 /*
803                  * When the sequencer detects an overrun, it
804                  * places the controller in "BITBUCKET" mode
805                  * and allows the target to complete its transfer.
806                  * Unfortunately, none of the counters get updated
807                  * when the controller is in this mode, so we have
808                  * no way of knowing how large the overrun was.
809                  */
810                 u_int scbindex = ahc_inb(ahc, SCB_TAG);
811                 u_int lastphase = ahc_inb(ahc, LASTPHASE);
812                 u_int i;
813
814                 scb = ahc_lookup_scb(ahc, scbindex);
815                 for (i = 0; i < num_phases; i++) {
816                         if (lastphase == ahc_phase_table[i].phase)
817                                 break;
818                 }
819                 ahc_print_path(ahc, scb);
820                 printf("data overrun detected %s."
821                        "  Tag == 0x%x.\n",
822                        ahc_phase_table[i].phasemsg,
823                        scb->hscb->tag);
824                 ahc_print_path(ahc, scb);
825                 printf("%s seen Data Phase.  Length = %ld.  NumSGs = %d.\n",
826                        ahc_inb(ahc, SEQ_FLAGS) & DPHASE ? "Have" : "Haven't",
827                        ahc_get_transfer_length(scb), scb->sg_count);
828                 if (scb->sg_count > 0) {
829                         for (i = 0; i < scb->sg_count; i++) {
830
831                                 printf("sg[%d] - Addr 0x%x%x : Length %d\n",
832                                        i,
833                                        (ahc_le32toh(scb->sg_list[i].len) >> 24
834                                         & SG_HIGH_ADDR_BITS),
835                                        ahc_le32toh(scb->sg_list[i].addr),
836                                        ahc_le32toh(scb->sg_list[i].len)
837                                        & AHC_SG_LEN_MASK);
838                         }
839                 }
840                 /*
841                  * Set this and it will take effect when the
842                  * target does a command complete.
843                  */
844                 ahc_freeze_devq(ahc, scb);
845                 if ((scb->flags & SCB_SENSE) == 0) {
846                         ahc_set_transaction_status(scb, CAM_DATA_RUN_ERR);
847                 } else {
848                         scb->flags &= ~SCB_SENSE;
849                         ahc_set_transaction_status(scb, CAM_AUTOSENSE_FAIL);
850                 }
851                 ahc_freeze_scb(scb);
852
853                 if ((ahc->features & AHC_ULTRA2) != 0) {
854                         /*
855                          * Clear the channel in case we return
856                          * to data phase later.
857                          */
858                         ahc_outb(ahc, SXFRCTL0,
859                                  ahc_inb(ahc, SXFRCTL0) | CLRSTCNT|CLRCHN);
860                         ahc_outb(ahc, SXFRCTL0,
861                                  ahc_inb(ahc, SXFRCTL0) | CLRSTCNT|CLRCHN);
862                 }
863                 if ((ahc->flags & AHC_39BIT_ADDRESSING) != 0) {
864                         u_int dscommand1;
865
866                         /* Ensure HHADDR is 0 for future DMA operations. */
867                         dscommand1 = ahc_inb(ahc, DSCOMMAND1);
868                         ahc_outb(ahc, DSCOMMAND1, dscommand1 | HADDLDSEL0);
869                         ahc_outb(ahc, HADDR, 0);
870                         ahc_outb(ahc, DSCOMMAND1, dscommand1);
871                 }
872                 break;
873         }
874         case MKMSG_FAILED:
875         {
876                 u_int scbindex;
877
878                 printf("%s:%c:%d:%d: Attempt to issue message failed\n",
879                        ahc_name(ahc), devinfo.channel, devinfo.target,
880                        devinfo.lun);
881                 scbindex = ahc_inb(ahc, SCB_TAG);
882                 scb = ahc_lookup_scb(ahc, scbindex);
883                 if (scb != NULL
884                  && (scb->flags & SCB_RECOVERY_SCB) != 0)
885                         /*
886                          * Ensure that we didn't put a second instance of this
887                          * SCB into the QINFIFO.
888                          */
889                         ahc_search_qinfifo(ahc, SCB_GET_TARGET(ahc, scb),
890                                            SCB_GET_CHANNEL(ahc, scb),
891                                            SCB_GET_LUN(scb), scb->hscb->tag,
892                                            ROLE_INITIATOR, /*status*/0,
893                                            SEARCH_REMOVE);
894                 break;
895         }
896         case NO_FREE_SCB:
897         {
898                 printf("%s: No free or disconnected SCBs\n", ahc_name(ahc));
899                 ahc_dump_card_state(ahc);
900                 panic("for safety");
901                 break;
902         }
903         case SCB_MISMATCH:
904         {
905                 u_int scbptr;
906
907                 scbptr = ahc_inb(ahc, SCBPTR);
908                 printf("Bogus TAG after DMA.  SCBPTR %d, tag %d, our tag %d\n",
909                        scbptr, ahc_inb(ahc, ARG_1),
910                        ahc->scb_data->hscbs[scbptr].tag);
911                 ahc_dump_card_state(ahc);
912                 panic("for saftey");
913                 break;
914         }
915         case OUT_OF_RANGE:
916         {
917                 printf("%s: BTT calculation out of range\n", ahc_name(ahc));
918                 printf("SAVED_SCSIID == 0x%x, SAVED_LUN == 0x%x, "
919                        "ARG_1 == 0x%x ACCUM = 0x%x\n",
920                        ahc_inb(ahc, SAVED_SCSIID), ahc_inb(ahc, SAVED_LUN),
921                        ahc_inb(ahc, ARG_1), ahc_inb(ahc, ACCUM));
922                 printf("SEQ_FLAGS == 0x%x, SCBPTR == 0x%x, BTT == 0x%x, "
923                        "SINDEX == 0x%x\n, A == 0x%x\n",
924                        ahc_inb(ahc, SEQ_FLAGS), ahc_inb(ahc, SCBPTR),
925                        ahc_index_busy_tcl(ahc,
926                             BUILD_TCL(ahc_inb(ahc, SAVED_SCSIID),
927                                       ahc_inb(ahc, SAVED_LUN))),
928                        ahc_inb(ahc, SINDEX),
929                        ahc_inb(ahc, ACCUM));
930                 printf("SCSIID == 0x%x, SCB_SCSIID == 0x%x, SCB_LUN == 0x%x, "
931                        "SCB_TAG == 0x%x, SCB_CONTROL == 0x%x\n",
932                        ahc_inb(ahc, SCSIID), ahc_inb(ahc, SCB_SCSIID),
933                        ahc_inb(ahc, SCB_LUN), ahc_inb(ahc, SCB_TAG),
934                        ahc_inb(ahc, SCB_CONTROL));
935                 printf("SCSIBUSL == 0x%x, SCSISIGI == 0x%x\n",
936                        ahc_inb(ahc, SCSIBUSL), ahc_inb(ahc, SCSISIGI));
937                 ahc_dump_card_state(ahc);
938                 panic("for safety");
939                 break;
940         }
941         default:
942                 printf("ahc_intr: seqint, "
943                        "intstat == 0x%x, scsisigi = 0x%x\n",
944                        intstat, ahc_inb(ahc, SCSISIGI));
945                 break;
946         }
947 unpause:
948         /*
949          *  The sequencer is paused immediately on
950          *  a SEQINT, so we should restart it when
951          *  we're done.
952          */
953         ahc_unpause(ahc);
954 }
955
956 void
957 ahc_handle_scsiint(struct ahc_softc *ahc, u_int intstat)
958 {
959         u_int   scb_index;
960         u_int   status0;
961         u_int   status;
962         struct  scb *scb;
963         char    cur_channel;
964         char    intr_channel;
965
966         if ((ahc->features & AHC_TWIN) != 0
967          && ((ahc_inb(ahc, SBLKCTL) & SELBUSB) != 0))
968                 cur_channel = 'B';
969         else
970                 cur_channel = 'A';
971         intr_channel = cur_channel;
972
973         if ((ahc->features & AHC_ULTRA2) != 0)
974                 status0 = ahc_inb(ahc, SSTAT0) & IOERR;
975         else
976                 status0 = 0;
977         status = ahc_inb(ahc, SSTAT1) & (SELTO|SCSIRSTI|BUSFREE|SCSIPERR);
978         if (status == 0 && status0 == 0) {
979                 if ((ahc->features & AHC_TWIN) != 0) {
980                         /* Try the other channel */
981                         ahc_outb(ahc, SBLKCTL, ahc_inb(ahc, SBLKCTL) ^ SELBUSB);
982                         status = ahc_inb(ahc, SSTAT1)
983                                & (SELTO|SCSIRSTI|BUSFREE|SCSIPERR);
984                         intr_channel = (cur_channel == 'A') ? 'B' : 'A';
985                 }
986                 if (status == 0) {
987                         printf("%s: Spurious SCSI interrupt\n", ahc_name(ahc));
988                         ahc_outb(ahc, CLRINT, CLRSCSIINT);
989                         ahc_unpause(ahc);
990                         return;
991                 }
992         }
993
994         /* Make sure the sequencer is in a safe location. */
995         ahc_clear_critical_section(ahc);
996
997         scb_index = ahc_inb(ahc, SCB_TAG);
998         scb = ahc_lookup_scb(ahc, scb_index);
999         if (scb != NULL
1000          && (ahc_inb(ahc, SEQ_FLAGS) & NOT_IDENTIFIED) != 0)
1001                 scb = NULL;
1002
1003         if ((ahc->features & AHC_ULTRA2) != 0
1004          && (status0 & IOERR) != 0) {
1005                 int now_lvd;
1006
1007                 now_lvd = ahc_inb(ahc, SBLKCTL) & ENAB40;
1008                 printf("%s: Transceiver State Has Changed to %s mode\n",
1009                        ahc_name(ahc), now_lvd ? "LVD" : "SE");
1010                 ahc_outb(ahc, CLRSINT0, CLRIOERR);
1011                 /*
1012                  * When transitioning to SE mode, the reset line
1013                  * glitches, triggering an arbitration bug in some
1014                  * Ultra2 controllers.  This bug is cleared when we
1015                  * assert the reset line.  Since a reset glitch has
1016                  * already occurred with this transition and a
1017                  * transceiver state change is handled just like
1018                  * a bus reset anyway, asserting the reset line
1019                  * ourselves is safe.
1020                  */
1021                 ahc_reset_channel(ahc, intr_channel,
1022                                  /*Initiate Reset*/now_lvd == 0);
1023         } else if ((status & SCSIRSTI) != 0) {
1024                 printf("%s: Someone reset channel %c\n",
1025                         ahc_name(ahc), intr_channel);
1026                 if (intr_channel != cur_channel)
1027                         ahc_outb(ahc, SBLKCTL, ahc_inb(ahc, SBLKCTL) ^ SELBUSB);
1028                 ahc_reset_channel(ahc, intr_channel, /*Initiate Reset*/FALSE);
1029         } else if ((status & SCSIPERR) != 0) {
1030                 /*
1031                  * Determine the bus phase and queue an appropriate message.
1032                  * SCSIPERR is latched true as soon as a parity error
1033                  * occurs.  If the sequencer acked the transfer that
1034                  * caused the parity error and the currently presented
1035                  * transfer on the bus has correct parity, SCSIPERR will
1036                  * be cleared by CLRSCSIPERR.  Use this to determine if
1037                  * we should look at the last phase the sequencer recorded,
1038                  * or the current phase presented on the bus.
1039                  */
1040                 struct  ahc_devinfo devinfo;
1041                 u_int   mesg_out;
1042                 u_int   curphase;
1043                 u_int   errorphase;
1044                 u_int   lastphase;
1045                 u_int   scsirate;
1046                 u_int   i;
1047                 u_int   sstat2;
1048                 int     silent;
1049
1050                 lastphase = ahc_inb(ahc, LASTPHASE);
1051                 curphase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
1052                 sstat2 = ahc_inb(ahc, SSTAT2);
1053                 ahc_outb(ahc, CLRSINT1, CLRSCSIPERR);
1054                 /*
1055                  * For all phases save DATA, the sequencer won't
1056                  * automatically ack a byte that has a parity error
1057                  * in it.  So the only way that the current phase
1058                  * could be 'data-in' is if the parity error is for
1059                  * an already acked byte in the data phase.  During
1060                  * synchronous data-in transfers, we may actually
1061                  * ack bytes before latching the current phase in
1062                  * LASTPHASE, leading to the discrepancy between
1063                  * curphase and lastphase.
1064                  */
1065                 if ((ahc_inb(ahc, SSTAT1) & SCSIPERR) != 0
1066                  || curphase == P_DATAIN || curphase == P_DATAIN_DT)
1067                         errorphase = curphase;
1068                 else
1069                         errorphase = lastphase;
1070
1071                 for (i = 0; i < num_phases; i++) {
1072                         if (errorphase == ahc_phase_table[i].phase)
1073                                 break;
1074                 }
1075                 mesg_out = ahc_phase_table[i].mesg_out;
1076                 silent = FALSE;
1077                 if (scb != NULL) {
1078                         if (SCB_IS_SILENT(scb))
1079                                 silent = TRUE;
1080                         else
1081                                 ahc_print_path(ahc, scb);
1082                         scb->flags |= SCB_TRANSMISSION_ERROR;
1083                 } else
1084                         printf("%s:%c:%d: ", ahc_name(ahc), intr_channel,
1085                                SCSIID_TARGET(ahc, ahc_inb(ahc, SAVED_SCSIID)));
1086                 scsirate = ahc_inb(ahc, SCSIRATE);
1087                 if (silent == FALSE) {
1088                         printf("parity error detected %s. "
1089                                "SEQADDR(0x%x) SCSIRATE(0x%x)\n",
1090                                ahc_phase_table[i].phasemsg,
1091                                ahc_inw(ahc, SEQADDR0),
1092                                scsirate);
1093                         if ((ahc->features & AHC_DT) != 0) {
1094                                 if ((sstat2 & CRCVALERR) != 0)
1095                                         printf("\tCRC Value Mismatch\n");
1096                                 if ((sstat2 & CRCENDERR) != 0)
1097                                         printf("\tNo terminal CRC packet "
1098                                                "recevied\n");
1099                                 if ((sstat2 & CRCREQERR) != 0)
1100                                         printf("\tIllegal CRC packet "
1101                                                "request\n");
1102                                 if ((sstat2 & DUAL_EDGE_ERR) != 0)
1103                                         printf("\tUnexpected %sDT Data Phase\n",
1104                                                (scsirate & SINGLE_EDGE)
1105                                              ? "" : "non-");
1106                         }
1107                 }
1108
1109                 if ((ahc->features & AHC_DT) != 0
1110                  && (sstat2 & DUAL_EDGE_ERR) != 0) {
1111                         /*
1112                          * This error applies regardless of
1113                          * data direction, so ignore the value
1114                          * in the phase table.
1115                          */
1116                         mesg_out = MSG_INITIATOR_DET_ERR;
1117                 }
1118
1119                 /*
1120                  * We've set the hardware to assert ATN if we   
1121                  * get a parity error on "in" phases, so all we  
1122                  * need to do is stuff the message buffer with
1123                  * the appropriate message.  "In" phases have set
1124                  * mesg_out to something other than MSG_NOP.
1125                  */
1126                 if (mesg_out != MSG_NOOP) {
1127                         if (ahc->msg_type != MSG_TYPE_NONE)
1128                                 ahc->send_msg_perror = TRUE;
1129                         else
1130                                 ahc_outb(ahc, MSG_OUT, mesg_out);
1131                 }
1132                 /*
1133                  * Force a renegotiation with this target just in
1134                  * case we are out of sync for some external reason
1135                  * unknown (or unreported) by the target.
1136                  */
1137                 ahc_fetch_devinfo(ahc, &devinfo);
1138                 ahc_force_renegotiation(ahc, &devinfo);
1139
1140                 ahc_outb(ahc, CLRINT, CLRSCSIINT);
1141                 ahc_unpause(ahc);
1142         } else if ((status & SELTO) != 0) {
1143                 u_int   scbptr;
1144
1145                 /* Stop the selection */
1146                 ahc_outb(ahc, SCSISEQ, 0);
1147
1148                 /* No more pending messages */
1149                 ahc_clear_msg_state(ahc);
1150
1151                 /* Clear interrupt state */
1152                 ahc_outb(ahc, SIMODE1, ahc_inb(ahc, SIMODE1) & ~ENBUSFREE);
1153                 ahc_outb(ahc, CLRSINT1, CLRSELTIMEO|CLRBUSFREE|CLRSCSIPERR);
1154
1155                 /*
1156                  * Although the driver does not care about the
1157                  * 'Selection in Progress' status bit, the busy
1158                  * LED does.  SELINGO is only cleared by a sucessfull
1159                  * selection, so we must manually clear it to insure
1160                  * the LED turns off just incase no future successful
1161                  * selections occur (e.g. no devices on the bus).
1162                  */
1163                 ahc_outb(ahc, CLRSINT0, CLRSELINGO);
1164
1165                 scbptr = ahc_inb(ahc, WAITING_SCBH);
1166                 ahc_outb(ahc, SCBPTR, scbptr);
1167                 scb_index = ahc_inb(ahc, SCB_TAG);
1168
1169                 scb = ahc_lookup_scb(ahc, scb_index);
1170                 if (scb == NULL) {
1171                         printf("%s: ahc_intr - referenced scb not "
1172                                "valid during SELTO scb(%d, %d)\n",
1173                                ahc_name(ahc), scbptr, scb_index);
1174                         ahc_dump_card_state(ahc);
1175                 } else {
1176                         struct ahc_devinfo devinfo;
1177 #ifdef AHC_DEBUG
1178                         if ((ahc_debug & AHC_SHOW_SELTO) != 0) {
1179                                 ahc_print_path(ahc, scb);
1180                                 printf("Saw Selection Timeout for SCB 0x%x\n",
1181                                        scb_index);
1182                         }
1183 #endif
1184                         ahc_scb_devinfo(ahc, &devinfo, scb);
1185                         ahc_set_transaction_status(scb, CAM_SEL_TIMEOUT);
1186                         ahc_freeze_devq(ahc, scb);
1187
1188                         /*
1189                          * Cancel any pending transactions on the device
1190                          * now that it seems to be missing.  This will
1191                          * also revert us to async/narrow transfers until
1192                          * we can renegotiate with the device.
1193                          */
1194                         ahc_handle_devreset(ahc, &devinfo,
1195                                             CAM_SEL_TIMEOUT,
1196                                             "Selection Timeout",
1197                                             /*verbose_level*/1);
1198                 }
1199                 ahc_outb(ahc, CLRINT, CLRSCSIINT);
1200                 ahc_restart(ahc);
1201         } else if ((status & BUSFREE) != 0
1202                 && (ahc_inb(ahc, SIMODE1) & ENBUSFREE) != 0) {
1203                 struct  ahc_devinfo devinfo;
1204                 u_int   lastphase;
1205                 u_int   saved_scsiid;
1206                 u_int   saved_lun;
1207                 u_int   target;
1208                 u_int   initiator_role_id;
1209                 char    channel;
1210                 int     printerror;
1211
1212                 /*
1213                  * Clear our selection hardware as soon as possible.
1214                  * We may have an entry in the waiting Q for this target,
1215                  * that is affected by this busfree and we don't want to
1216                  * go about selecting the target while we handle the event.
1217                  */
1218                 ahc_outb(ahc, SCSISEQ,
1219                          ahc_inb(ahc, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP));
1220
1221                 /*
1222                  * Disable busfree interrupts and clear the busfree
1223                  * interrupt status.  We do this here so that several
1224                  * bus transactions occur prior to clearing the SCSIINT
1225                  * latch.  It can take a bit for the clearing to take effect.
1226                  */
1227                 ahc_outb(ahc, SIMODE1, ahc_inb(ahc, SIMODE1) & ~ENBUSFREE);
1228                 ahc_outb(ahc, CLRSINT1, CLRBUSFREE|CLRSCSIPERR);
1229
1230                 /*
1231                  * Look at what phase we were last in.
1232                  * If its message out, chances are pretty good
1233                  * that the busfree was in response to one of
1234                  * our abort requests.
1235                  */
1236                 lastphase = ahc_inb(ahc, LASTPHASE);
1237                 saved_scsiid = ahc_inb(ahc, SAVED_SCSIID);
1238                 saved_lun = ahc_inb(ahc, SAVED_LUN);
1239                 target = SCSIID_TARGET(ahc, saved_scsiid);
1240                 initiator_role_id = SCSIID_OUR_ID(saved_scsiid);
1241                 channel = SCSIID_CHANNEL(ahc, saved_scsiid);
1242                 ahc_compile_devinfo(&devinfo, initiator_role_id,
1243                                     target, saved_lun, channel, ROLE_INITIATOR);
1244                 printerror = 1;
1245
1246                 if (lastphase == P_MESGOUT) {
1247                         u_int tag;
1248
1249                         tag = SCB_LIST_NULL;
1250                         if (ahc_sent_msg(ahc, AHCMSG_1B, MSG_ABORT_TAG, TRUE)
1251                          || ahc_sent_msg(ahc, AHCMSG_1B, MSG_ABORT, TRUE)) {
1252                                 if (ahc->msgout_buf[ahc->msgout_index - 1]
1253                                  == MSG_ABORT_TAG)
1254                                         tag = scb->hscb->tag;
1255                                 ahc_print_path(ahc, scb);
1256                                 printf("SCB %d - Abort%s Completed.\n",
1257                                        scb->hscb->tag, tag == SCB_LIST_NULL ?
1258                                        "" : " Tag");
1259                                 ahc_abort_scbs(ahc, target, channel,
1260                                                saved_lun, tag,
1261                                                ROLE_INITIATOR,
1262                                                CAM_REQ_ABORTED);
1263                                 printerror = 0;
1264                         } else if (ahc_sent_msg(ahc, AHCMSG_1B,
1265                                                 MSG_BUS_DEV_RESET, TRUE)) {
1266 #ifdef __FreeBSD__
1267                                 /*
1268                                  * Don't mark the user's request for this BDR
1269                                  * as completing with CAM_BDR_SENT.  CAM3
1270                                  * specifies CAM_REQ_CMP.
1271                                  */
1272                                 if (scb != NULL
1273                                  && scb->io_ctx->ccb_h.func_code== XPT_RESET_DEV
1274                                  && ahc_match_scb(ahc, scb, target, channel,
1275                                                   CAM_LUN_WILDCARD,
1276                                                   SCB_LIST_NULL,
1277                                                   ROLE_INITIATOR)) {
1278                                         ahc_set_transaction_status(scb, CAM_REQ_CMP);
1279                                 }
1280 #endif
1281                                 ahc_compile_devinfo(&devinfo,
1282                                                     initiator_role_id,
1283                                                     target,
1284                                                     CAM_LUN_WILDCARD,
1285                                                     channel,
1286                                                     ROLE_INITIATOR);
1287                                 ahc_handle_devreset(ahc, &devinfo,
1288                                                     CAM_BDR_SENT,
1289                                                     "Bus Device Reset",
1290                                                     /*verbose_level*/0);
1291                                 printerror = 0;
1292                         } else if (ahc_sent_msg(ahc, AHCMSG_EXT,
1293                                                 MSG_EXT_PPR, FALSE)) {
1294                                 struct ahc_initiator_tinfo *tinfo;
1295                                 struct ahc_tmode_tstate *tstate;
1296
1297                                 /*
1298                                  * PPR Rejected.  Try non-ppr negotiation
1299                                  * and retry command.
1300                                  */
1301                                 tinfo = ahc_fetch_transinfo(ahc,
1302                                                             devinfo.channel,
1303                                                             devinfo.our_scsiid,
1304                                                             devinfo.target,
1305                                                             &tstate);
1306                                 tinfo->curr.transport_version = 2;
1307                                 tinfo->goal.transport_version = 2;
1308                                 tinfo->goal.ppr_options = 0;
1309                                 ahc_qinfifo_requeue_tail(ahc, scb);
1310                                 printerror = 0;
1311                         } else if (ahc_sent_msg(ahc, AHCMSG_EXT,
1312                                                 MSG_EXT_WDTR, FALSE)) {
1313                                 /*
1314                                  * Negotiation Rejected.  Go-narrow and
1315                                  * retry command.
1316                                  */
1317                                 ahc_set_width(ahc, &devinfo,
1318                                               MSG_EXT_WDTR_BUS_8_BIT,
1319                                               AHC_TRANS_CUR|AHC_TRANS_GOAL,
1320                                               /*paused*/TRUE);
1321                                 ahc_qinfifo_requeue_tail(ahc, scb);
1322                                 printerror = 0;
1323                         } else if (ahc_sent_msg(ahc, AHCMSG_EXT,
1324                                                 MSG_EXT_SDTR, FALSE)) {
1325                                 /*
1326                                  * Negotiation Rejected.  Go-async and
1327                                  * retry command.
1328                                  */
1329                                 ahc_set_syncrate(ahc, &devinfo,
1330                                                 /*syncrate*/NULL,
1331                                                 /*period*/0, /*offset*/0,
1332                                                 /*ppr_options*/0,
1333                                                 AHC_TRANS_CUR|AHC_TRANS_GOAL,
1334                                                 /*paused*/TRUE);
1335                                 ahc_qinfifo_requeue_tail(ahc, scb);
1336                                 printerror = 0;
1337                         }
1338                 }
1339                 if (printerror != 0) {
1340                         u_int i;
1341
1342                         if (scb != NULL) {
1343                                 u_int tag;
1344
1345                                 if ((scb->hscb->control & TAG_ENB) != 0)
1346                                         tag = scb->hscb->tag;
1347                                 else
1348                                         tag = SCB_LIST_NULL;
1349                                 ahc_print_path(ahc, scb);
1350                                 ahc_abort_scbs(ahc, target, channel,
1351                                                SCB_GET_LUN(scb), tag,
1352                                                ROLE_INITIATOR,
1353                                                CAM_UNEXP_BUSFREE);
1354                         } else {
1355                                 /*
1356                                  * We had not fully identified this connection,
1357                                  * so we cannot abort anything.
1358                                  */
1359                                 printf("%s: ", ahc_name(ahc));
1360                         }
1361                         for (i = 0; i < num_phases; i++) {
1362                                 if (lastphase == ahc_phase_table[i].phase)
1363                                         break;
1364                         }
1365                         if (lastphase != P_BUSFREE) {
1366                                 /*
1367                                  * Renegotiate with this device at the
1368                                  * next oportunity just in case this busfree
1369                                  * is due to a negotiation mismatch with the
1370                                  * device.
1371                                  */
1372                                 ahc_force_renegotiation(ahc, &devinfo);
1373                         }
1374                         printf("Unexpected busfree %s\n"
1375                                "SEQADDR == 0x%x\n",
1376                                ahc_phase_table[i].phasemsg,
1377                                ahc_inb(ahc, SEQADDR0)
1378                                 | (ahc_inb(ahc, SEQADDR1) << 8));
1379                 }
1380                 ahc_outb(ahc, CLRINT, CLRSCSIINT);
1381                 ahc_restart(ahc);
1382         } else {
1383                 printf("%s: Missing case in ahc_handle_scsiint. status = %x\n",
1384                        ahc_name(ahc), status);
1385                 ahc_outb(ahc, CLRINT, CLRSCSIINT);
1386         }
1387 }
1388
1389 /*
1390  * Force renegotiation to occur the next time we initiate
1391  * a command to the current device.
1392  */
1393 static void
1394 ahc_force_renegotiation(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
1395 {
1396         struct  ahc_initiator_tinfo *targ_info;
1397         struct  ahc_tmode_tstate *tstate;
1398
1399         targ_info = ahc_fetch_transinfo(ahc,
1400                                         devinfo->channel,
1401                                         devinfo->our_scsiid,
1402                                         devinfo->target,
1403                                         &tstate);
1404         ahc_update_neg_request(ahc, devinfo, tstate,
1405                                targ_info, AHC_NEG_IF_NON_ASYNC);
1406 }
1407
1408 #define AHC_MAX_STEPS 2000
1409 void
1410 ahc_clear_critical_section(struct ahc_softc *ahc)
1411 {
1412         int     stepping;
1413         int     steps;
1414         u_int   simode0;
1415         u_int   simode1;
1416
1417         if (ahc->num_critical_sections == 0)
1418                 return;
1419
1420         stepping = FALSE;
1421         steps = 0;
1422         simode0 = 0;
1423         simode1 = 0;
1424         for (;;) {
1425                 struct  cs *cs;
1426                 u_int   seqaddr;
1427                 u_int   i;
1428
1429                 seqaddr = ahc_inb(ahc, SEQADDR0)
1430                         | (ahc_inb(ahc, SEQADDR1) << 8);
1431
1432                 /*
1433                  * Seqaddr represents the next instruction to execute, 
1434                  * so we are really executing the instruction just
1435                  * before it.
1436                  */
1437                 if (seqaddr != 0)
1438                         seqaddr -= 1;
1439                 cs = ahc->critical_sections;
1440                 for (i = 0; i < ahc->num_critical_sections; i++, cs++) {
1441                         
1442                         if (cs->begin < seqaddr && cs->end >= seqaddr)
1443                                 break;
1444                 }
1445
1446                 if (i == ahc->num_critical_sections)
1447                         break;
1448
1449                 if (steps > AHC_MAX_STEPS) {
1450                         printf("%s: Infinite loop in critical section\n",
1451                                ahc_name(ahc));
1452                         ahc_dump_card_state(ahc);
1453                         panic("critical section loop");
1454                 }
1455
1456                 steps++;
1457                 if (stepping == FALSE) {
1458
1459                         /*
1460                          * Disable all interrupt sources so that the
1461                          * sequencer will not be stuck by a pausing
1462                          * interrupt condition while we attempt to
1463                          * leave a critical section.
1464                          */
1465                         simode0 = ahc_inb(ahc, SIMODE0);
1466                         ahc_outb(ahc, SIMODE0, 0);
1467                         simode1 = ahc_inb(ahc, SIMODE1);
1468                         if ((ahc->features & AHC_DT) != 0)
1469                                 /*
1470                                  * On DT class controllers, we
1471                                  * use the enhanced busfree logic.
1472                                  * Unfortunately we cannot re-enable
1473                                  * busfree detection within the
1474                                  * current connection, so we must
1475                                  * leave it on while single stepping.
1476                                  */
1477                                 ahc_outb(ahc, SIMODE1, simode1 & ENBUSFREE);
1478                         else
1479                                 ahc_outb(ahc, SIMODE1, 0);
1480                         ahc_outb(ahc, CLRINT, CLRSCSIINT);
1481                         ahc_outb(ahc, SEQCTL, ahc->seqctl | STEP);
1482                         stepping = TRUE;
1483                 }
1484                 if ((ahc->features & AHC_DT) != 0) {
1485                         ahc_outb(ahc, CLRSINT1, CLRBUSFREE);
1486                         ahc_outb(ahc, CLRINT, CLRSCSIINT);
1487                 }
1488                 ahc_outb(ahc, HCNTRL, ahc->unpause);
1489                 while (!ahc_is_paused(ahc))
1490                         ahc_delay(200);
1491         }
1492         if (stepping) {
1493                 ahc_outb(ahc, SIMODE0, simode0);
1494                 ahc_outb(ahc, SIMODE1, simode1);
1495                 ahc_outb(ahc, SEQCTL, ahc->seqctl);
1496         }
1497 }
1498
1499 /*
1500  * Clear any pending interrupt status.
1501  */
1502 void
1503 ahc_clear_intstat(struct ahc_softc *ahc)
1504 {
1505         /* Clear any interrupt conditions this may have caused */
1506         ahc_outb(ahc, CLRSINT1, CLRSELTIMEO|CLRATNO|CLRSCSIRSTI
1507                                 |CLRBUSFREE|CLRSCSIPERR|CLRPHASECHG|
1508                                 CLRREQINIT);
1509         ahc_flush_device_writes(ahc);
1510         ahc_outb(ahc, CLRSINT0, CLRSELDO|CLRSELDI|CLRSELINGO);
1511         ahc_flush_device_writes(ahc);
1512         ahc_outb(ahc, CLRINT, CLRSCSIINT);
1513         ahc_flush_device_writes(ahc);
1514 }
1515
1516 /**************************** Debugging Routines ******************************/
1517 #ifdef AHC_DEBUG
1518 uint32_t ahc_debug = AHC_DEBUG_OPTS;
1519 #endif
1520
1521 void
1522 ahc_print_scb(struct scb *scb)
1523 {
1524         int i;
1525
1526         struct hardware_scb *hscb = scb->hscb;
1527
1528         printf("scb:%p control:0x%x scsiid:0x%x lun:%d cdb_len:%d\n",
1529                (void *)scb,
1530                hscb->control,
1531                hscb->scsiid,
1532                hscb->lun,
1533                hscb->cdb_len);
1534         printf("Shared Data: ");
1535         for (i = 0; i < sizeof(hscb->shared_data.cdb); i++)
1536                 printf("%#02x", hscb->shared_data.cdb[i]);
1537         printf("        dataptr:%#x datacnt:%#x sgptr:%#x tag:%#x\n",
1538                 ahc_le32toh(hscb->dataptr),
1539                 ahc_le32toh(hscb->datacnt),
1540                 ahc_le32toh(hscb->sgptr),
1541                 hscb->tag);
1542         if (scb->sg_count > 0) {
1543                 for (i = 0; i < scb->sg_count; i++) {
1544                         printf("sg[%d] - Addr 0x%x%x : Length %d\n",
1545                                i,
1546                                (ahc_le32toh(scb->sg_list[i].len) >> 24
1547                                 & SG_HIGH_ADDR_BITS),
1548                                ahc_le32toh(scb->sg_list[i].addr),
1549                                ahc_le32toh(scb->sg_list[i].len));
1550                 }
1551         }
1552 }
1553
1554 /************************* Transfer Negotiation *******************************/
1555 /*
1556  * Allocate per target mode instance (ID we respond to as a target)
1557  * transfer negotiation data structures.
1558  */
1559 static struct ahc_tmode_tstate *
1560 ahc_alloc_tstate(struct ahc_softc *ahc, u_int scsi_id, char channel)
1561 {
1562         struct ahc_tmode_tstate *master_tstate;
1563         struct ahc_tmode_tstate *tstate;
1564         int i;
1565
1566         master_tstate = ahc->enabled_targets[ahc->our_id];
1567         if (channel == 'B') {
1568                 scsi_id += 8;
1569                 master_tstate = ahc->enabled_targets[ahc->our_id_b + 8];
1570         }
1571         if (ahc->enabled_targets[scsi_id] != NULL
1572          && ahc->enabled_targets[scsi_id] != master_tstate)
1573                 panic("%s: ahc_alloc_tstate - Target already allocated",
1574                       ahc_name(ahc));
1575         tstate = (struct ahc_tmode_tstate*)malloc(sizeof(*tstate),
1576                                                    M_DEVBUF, M_NOWAIT);
1577         if (tstate == NULL)
1578                 return (NULL);
1579
1580         /*
1581          * If we have allocated a master tstate, copy user settings from
1582          * the master tstate (taken from SRAM or the EEPROM) for this
1583          * channel, but reset our current and goal settings to async/narrow
1584          * until an initiator talks to us.
1585          */
1586         if (master_tstate != NULL) {
1587                 memcpy(tstate, master_tstate, sizeof(*tstate));
1588                 memset(tstate->enabled_luns, 0, sizeof(tstate->enabled_luns));
1589                 tstate->ultraenb = 0;
1590                 for (i = 0; i < AHC_NUM_TARGETS; i++) {
1591                         memset(&tstate->transinfo[i].curr, 0,
1592                               sizeof(tstate->transinfo[i].curr));
1593                         memset(&tstate->transinfo[i].goal, 0,
1594                               sizeof(tstate->transinfo[i].goal));
1595                 }
1596         } else
1597                 memset(tstate, 0, sizeof(*tstate));
1598         ahc->enabled_targets[scsi_id] = tstate;
1599         return (tstate);
1600 }
1601
1602 #ifdef AHC_TARGET_MODE
1603 /*
1604  * Free per target mode instance (ID we respond to as a target)
1605  * transfer negotiation data structures.
1606  */
1607 static void
1608 ahc_free_tstate(struct ahc_softc *ahc, u_int scsi_id, char channel, int force)
1609 {
1610         struct ahc_tmode_tstate *tstate;
1611
1612         /*
1613          * Don't clean up our "master" tstate.
1614          * It has our default user settings.
1615          */
1616         if (((channel == 'B' && scsi_id == ahc->our_id_b)
1617           || (channel == 'A' && scsi_id == ahc->our_id))
1618          && force == FALSE)
1619                 return;
1620
1621         if (channel == 'B')
1622                 scsi_id += 8;
1623         tstate = ahc->enabled_targets[scsi_id];
1624         if (tstate != NULL)
1625                 free(tstate, M_DEVBUF);
1626         ahc->enabled_targets[scsi_id] = NULL;
1627 }
1628 #endif
1629
1630 /*
1631  * Called when we have an active connection to a target on the bus,
1632  * this function finds the nearest syncrate to the input period limited
1633  * by the capabilities of the bus connectivity of and sync settings for
1634  * the target.
1635  */
1636 struct ahc_syncrate *
1637 ahc_devlimited_syncrate(struct ahc_softc *ahc,
1638                         struct ahc_initiator_tinfo *tinfo,
1639                         u_int *period, u_int *ppr_options, role_t role)
1640 {
1641         struct  ahc_transinfo *transinfo;
1642         u_int   maxsync;
1643
1644         if ((ahc->features & AHC_ULTRA2) != 0) {
1645                 if ((ahc_inb(ahc, SBLKCTL) & ENAB40) != 0
1646                  && (ahc_inb(ahc, SSTAT2) & EXP_ACTIVE) == 0) {
1647                         maxsync = AHC_SYNCRATE_DT;
1648                 } else {
1649                         maxsync = AHC_SYNCRATE_ULTRA;
1650                         /* Can't do DT on an SE bus */
1651                         *ppr_options &= ~MSG_EXT_PPR_DT_REQ;
1652                 }
1653         } else if ((ahc->features & AHC_ULTRA) != 0) {
1654                 maxsync = AHC_SYNCRATE_ULTRA;
1655         } else {
1656                 maxsync = AHC_SYNCRATE_FAST;
1657         }
1658         /*
1659          * Never allow a value higher than our current goal
1660          * period otherwise we may allow a target initiated
1661          * negotiation to go above the limit as set by the
1662          * user.  In the case of an initiator initiated
1663          * sync negotiation, we limit based on the user
1664          * setting.  This allows the system to still accept
1665          * incoming negotiations even if target initiated
1666          * negotiation is not performed.
1667          */
1668         if (role == ROLE_TARGET)
1669                 transinfo = &tinfo->user;
1670         else 
1671                 transinfo = &tinfo->goal;
1672         *ppr_options &= transinfo->ppr_options;
1673         if (transinfo->width == MSG_EXT_WDTR_BUS_8_BIT) {
1674                 maxsync = MAX(maxsync, AHC_SYNCRATE_ULTRA2);
1675                 *ppr_options &= ~MSG_EXT_PPR_DT_REQ;
1676         }
1677         if (transinfo->period == 0) {
1678                 *period = 0;
1679                 *ppr_options = 0;
1680                 return (NULL);
1681         }
1682         *period = MAX(*period, transinfo->period);
1683         return (ahc_find_syncrate(ahc, period, ppr_options, maxsync));
1684 }
1685
1686 /*
1687  * Look up the valid period to SCSIRATE conversion in our table.
1688  * Return the period and offset that should be sent to the target
1689  * if this was the beginning of an SDTR.
1690  */
1691 struct ahc_syncrate *
1692 ahc_find_syncrate(struct ahc_softc *ahc, u_int *period,
1693                   u_int *ppr_options, u_int maxsync)
1694 {
1695         struct ahc_syncrate *syncrate;
1696
1697         if ((ahc->features & AHC_DT) == 0)
1698                 *ppr_options &= ~MSG_EXT_PPR_DT_REQ;
1699
1700         /* Skip all DT only entries if DT is not available */
1701         if ((*ppr_options & MSG_EXT_PPR_DT_REQ) == 0
1702          && maxsync < AHC_SYNCRATE_ULTRA2)
1703                 maxsync = AHC_SYNCRATE_ULTRA2;
1704         
1705         for (syncrate = &ahc_syncrates[maxsync];
1706              syncrate->rate != NULL;
1707              syncrate++) {
1708
1709                 /*
1710                  * The Ultra2 table doesn't go as low
1711                  * as for the Fast/Ultra cards.
1712                  */
1713                 if ((ahc->features & AHC_ULTRA2) != 0
1714                  && (syncrate->sxfr_u2 == 0))
1715                         break;
1716
1717                 if (*period <= syncrate->period) {
1718                         /*
1719                          * When responding to a target that requests
1720                          * sync, the requested rate may fall between
1721                          * two rates that we can output, but still be
1722                          * a rate that we can receive.  Because of this,
1723                          * we want to respond to the target with
1724                          * the same rate that it sent to us even
1725                          * if the period we use to send data to it
1726                          * is lower.  Only lower the response period
1727                          * if we must.
1728                          */
1729                         if (syncrate == &ahc_syncrates[maxsync])
1730                                 *period = syncrate->period;
1731
1732                         /*
1733                          * At some speeds, we only support
1734                          * ST transfers.
1735                          */
1736                         if ((syncrate->sxfr_u2 & ST_SXFR) != 0)
1737                                 *ppr_options &= ~MSG_EXT_PPR_DT_REQ;
1738                         break;
1739                 }
1740         }
1741
1742         if ((*period == 0)
1743          || (syncrate->rate == NULL)
1744          || ((ahc->features & AHC_ULTRA2) != 0
1745           && (syncrate->sxfr_u2 == 0))) {
1746                 /* Use asynchronous transfers. */
1747                 *period = 0;
1748                 syncrate = NULL;
1749                 *ppr_options &= ~MSG_EXT_PPR_DT_REQ;
1750         }
1751         return (syncrate);
1752 }
1753
1754 /*
1755  * Convert from an entry in our syncrate table to the SCSI equivalent
1756  * sync "period" factor.
1757  */
1758 u_int
1759 ahc_find_period(struct ahc_softc *ahc, u_int scsirate, u_int maxsync)
1760 {
1761         struct ahc_syncrate *syncrate;
1762
1763         if ((ahc->features & AHC_ULTRA2) != 0)
1764                 scsirate &= SXFR_ULTRA2;
1765         else
1766                 scsirate &= SXFR;
1767
1768         syncrate = &ahc_syncrates[maxsync];
1769         while (syncrate->rate != NULL) {
1770
1771                 if ((ahc->features & AHC_ULTRA2) != 0) {
1772                         if (syncrate->sxfr_u2 == 0)
1773                                 break;
1774                         else if (scsirate == (syncrate->sxfr_u2 & SXFR_ULTRA2))
1775                                 return (syncrate->period);
1776                 } else if (scsirate == (syncrate->sxfr & SXFR)) {
1777                                 return (syncrate->period);
1778                 }
1779                 syncrate++;
1780         }
1781         return (0); /* async */
1782 }
1783
1784 /*
1785  * Truncate the given synchronous offset to a value the
1786  * current adapter type and syncrate are capable of.
1787  */
1788 void
1789 ahc_validate_offset(struct ahc_softc *ahc,
1790                     struct ahc_initiator_tinfo *tinfo,
1791                     struct ahc_syncrate *syncrate,
1792                     u_int *offset, int wide, role_t role)
1793 {
1794         u_int maxoffset;
1795
1796         /* Limit offset to what we can do */
1797         if (syncrate == NULL) {
1798                 maxoffset = 0;
1799         } else if ((ahc->features & AHC_ULTRA2) != 0) {
1800                 maxoffset = MAX_OFFSET_ULTRA2;
1801         } else {
1802                 if (wide)
1803                         maxoffset = MAX_OFFSET_16BIT;
1804                 else
1805                         maxoffset = MAX_OFFSET_8BIT;
1806         }
1807         *offset = MIN(*offset, maxoffset);
1808         if (tinfo != NULL) {
1809                 if (role == ROLE_TARGET)
1810                         *offset = MIN(*offset, tinfo->user.offset);
1811                 else
1812                         *offset = MIN(*offset, tinfo->goal.offset);
1813         }
1814 }
1815
1816 /*
1817  * Truncate the given transfer width parameter to a value the
1818  * current adapter type is capable of.
1819  */
1820 void
1821 ahc_validate_width(struct ahc_softc *ahc, struct ahc_initiator_tinfo *tinfo,
1822                    u_int *bus_width, role_t role)
1823 {
1824         switch (*bus_width) {
1825         default:
1826                 if (ahc->features & AHC_WIDE) {
1827                         /* Respond Wide */
1828                         *bus_width = MSG_EXT_WDTR_BUS_16_BIT;
1829                         break;
1830                 }
1831                 /* FALLTHROUGH */
1832         case MSG_EXT_WDTR_BUS_8_BIT:
1833                 *bus_width = MSG_EXT_WDTR_BUS_8_BIT;
1834                 break;
1835         }
1836         if (tinfo != NULL) {
1837                 if (role == ROLE_TARGET)
1838                         *bus_width = MIN(tinfo->user.width, *bus_width);
1839                 else
1840                         *bus_width = MIN(tinfo->goal.width, *bus_width);
1841         }
1842 }
1843
1844 /*
1845  * Update the bitmask of targets for which the controller should
1846  * negotiate with at the next convenient oportunity.  This currently
1847  * means the next time we send the initial identify messages for
1848  * a new transaction.
1849  */
1850 int
1851 ahc_update_neg_request(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
1852                        struct ahc_tmode_tstate *tstate,
1853                        struct ahc_initiator_tinfo *tinfo, ahc_neg_type neg_type)
1854 {
1855         u_int auto_negotiate_orig;
1856
1857         auto_negotiate_orig = tstate->auto_negotiate;
1858         if (neg_type == AHC_NEG_ALWAYS) {
1859                 /*
1860                  * Force our "current" settings to be
1861                  * unknown so that unless a bus reset
1862                  * occurs the need to renegotiate is
1863                  * recorded persistently.
1864                  */
1865                 if ((ahc->features & AHC_WIDE) != 0)
1866                         tinfo->curr.width = AHC_WIDTH_UNKNOWN;
1867                 tinfo->curr.period = AHC_PERIOD_UNKNOWN;
1868                 tinfo->curr.offset = AHC_OFFSET_UNKNOWN;
1869         }
1870         if (tinfo->curr.period != tinfo->goal.period
1871          || tinfo->curr.width != tinfo->goal.width
1872          || tinfo->curr.offset != tinfo->goal.offset
1873          || tinfo->curr.ppr_options != tinfo->goal.ppr_options
1874          || (neg_type == AHC_NEG_IF_NON_ASYNC
1875           && (tinfo->goal.offset != 0
1876            || tinfo->goal.width != MSG_EXT_WDTR_BUS_8_BIT
1877            || tinfo->goal.ppr_options != 0)))
1878                 tstate->auto_negotiate |= devinfo->target_mask;
1879         else
1880                 tstate->auto_negotiate &= ~devinfo->target_mask;
1881
1882         return (auto_negotiate_orig != tstate->auto_negotiate);
1883 }
1884
1885 /*
1886  * Update the user/goal/curr tables of synchronous negotiation
1887  * parameters as well as, in the case of a current or active update,
1888  * any data structures on the host controller.  In the case of an
1889  * active update, the specified target is currently talking to us on
1890  * the bus, so the transfer parameter update must take effect
1891  * immediately.
1892  */
1893 void
1894 ahc_set_syncrate(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
1895                  struct ahc_syncrate *syncrate, u_int period,
1896                  u_int offset, u_int ppr_options, u_int type, int paused)
1897 {
1898         struct  ahc_initiator_tinfo *tinfo;
1899         struct  ahc_tmode_tstate *tstate;
1900         u_int   old_period;
1901         u_int   old_offset;
1902         u_int   old_ppr;
1903         int     active;
1904         int     update_needed;
1905
1906         active = (type & AHC_TRANS_ACTIVE) == AHC_TRANS_ACTIVE;
1907         update_needed = 0;
1908
1909         if (syncrate == NULL) {
1910                 period = 0;
1911                 offset = 0;
1912         }
1913
1914         tinfo = ahc_fetch_transinfo(ahc, devinfo->channel, devinfo->our_scsiid,
1915                                     devinfo->target, &tstate);
1916
1917         if ((type & AHC_TRANS_USER) != 0) {
1918                 tinfo->user.period = period;
1919                 tinfo->user.offset = offset;
1920                 tinfo->user.ppr_options = ppr_options;
1921         }
1922
1923         if ((type & AHC_TRANS_GOAL) != 0) {
1924                 tinfo->goal.period = period;
1925                 tinfo->goal.offset = offset;
1926                 tinfo->goal.ppr_options = ppr_options;
1927         }
1928
1929         old_period = tinfo->curr.period;
1930         old_offset = tinfo->curr.offset;
1931         old_ppr    = tinfo->curr.ppr_options;
1932
1933         if ((type & AHC_TRANS_CUR) != 0
1934          && (old_period != period
1935           || old_offset != offset
1936           || old_ppr != ppr_options)) {
1937                 u_int   scsirate;
1938
1939                 update_needed++;
1940                 scsirate = tinfo->scsirate;
1941                 if ((ahc->features & AHC_ULTRA2) != 0) {
1942
1943                         scsirate &= ~(SXFR_ULTRA2|SINGLE_EDGE|ENABLE_CRC);
1944                         if (syncrate != NULL) {
1945                                 scsirate |= syncrate->sxfr_u2;
1946                                 if ((ppr_options & MSG_EXT_PPR_DT_REQ) != 0)
1947                                         scsirate |= ENABLE_CRC;
1948                                 else
1949                                         scsirate |= SINGLE_EDGE;
1950                         }
1951                 } else {
1952
1953                         scsirate &= ~(SXFR|SOFS);
1954                         /*
1955                          * Ensure Ultra mode is set properly for
1956                          * this target.
1957                          */
1958                         tstate->ultraenb &= ~devinfo->target_mask;
1959                         if (syncrate != NULL) {
1960                                 if (syncrate->sxfr & ULTRA_SXFR) {
1961                                         tstate->ultraenb |=
1962                                                 devinfo->target_mask;
1963                                 }
1964                                 scsirate |= syncrate->sxfr & SXFR;
1965                                 scsirate |= offset & SOFS;
1966                         }
1967                         if (active) {
1968                                 u_int sxfrctl0;
1969
1970                                 sxfrctl0 = ahc_inb(ahc, SXFRCTL0);
1971                                 sxfrctl0 &= ~FAST20;
1972                                 if (tstate->ultraenb & devinfo->target_mask)
1973                                         sxfrctl0 |= FAST20;
1974                                 ahc_outb(ahc, SXFRCTL0, sxfrctl0);
1975                         }
1976                 }
1977                 if (active) {
1978                         ahc_outb(ahc, SCSIRATE, scsirate);
1979                         if ((ahc->features & AHC_ULTRA2) != 0)
1980                                 ahc_outb(ahc, SCSIOFFSET, offset);
1981                 }
1982
1983                 tinfo->scsirate = scsirate;
1984                 tinfo->curr.period = period;
1985                 tinfo->curr.offset = offset;
1986                 tinfo->curr.ppr_options = ppr_options;
1987
1988                 ahc_send_async(ahc, devinfo->channel, devinfo->target,
1989                                CAM_LUN_WILDCARD, AC_TRANSFER_NEG, NULL);
1990                 if (bootverbose) {
1991                         if (offset != 0) {
1992                                 printf("%s: target %d synchronous at %sMHz%s, "
1993                                        "offset = 0x%x\n", ahc_name(ahc),
1994                                        devinfo->target, syncrate->rate,
1995                                        (ppr_options & MSG_EXT_PPR_DT_REQ)
1996                                        ? " DT" : "", offset);
1997                         } else {
1998                                 printf("%s: target %d using "
1999                                        "asynchronous transfers\n",
2000                                        ahc_name(ahc), devinfo->target);
2001                         }
2002                 }
2003         }
2004
2005         update_needed += ahc_update_neg_request(ahc, devinfo, tstate,
2006                                                 tinfo, AHC_NEG_TO_GOAL);
2007
2008         if (update_needed)
2009                 ahc_update_pending_scbs(ahc);
2010 }
2011
2012 /*
2013  * Update the user/goal/curr tables of wide negotiation
2014  * parameters as well as, in the case of a current or active update,
2015  * any data structures on the host controller.  In the case of an
2016  * active update, the specified target is currently talking to us on
2017  * the bus, so the transfer parameter update must take effect
2018  * immediately.
2019  */
2020 void
2021 ahc_set_width(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
2022               u_int width, u_int type, int paused)
2023 {
2024         struct  ahc_initiator_tinfo *tinfo;
2025         struct  ahc_tmode_tstate *tstate;
2026         u_int   oldwidth;
2027         int     active;
2028         int     update_needed;
2029
2030         active = (type & AHC_TRANS_ACTIVE) == AHC_TRANS_ACTIVE;
2031         update_needed = 0;
2032         tinfo = ahc_fetch_transinfo(ahc, devinfo->channel, devinfo->our_scsiid,
2033                                     devinfo->target, &tstate);
2034
2035         if ((type & AHC_TRANS_USER) != 0)
2036                 tinfo->user.width = width;
2037
2038         if ((type & AHC_TRANS_GOAL) != 0)
2039                 tinfo->goal.width = width;
2040
2041         oldwidth = tinfo->curr.width;
2042         if ((type & AHC_TRANS_CUR) != 0 && oldwidth != width) {
2043                 u_int   scsirate;
2044
2045                 update_needed++;
2046                 scsirate =  tinfo->scsirate;
2047                 scsirate &= ~WIDEXFER;
2048                 if (width == MSG_EXT_WDTR_BUS_16_BIT)
2049                         scsirate |= WIDEXFER;
2050
2051                 tinfo->scsirate = scsirate;
2052
2053                 if (active)
2054                         ahc_outb(ahc, SCSIRATE, scsirate);
2055
2056                 tinfo->curr.width = width;
2057
2058                 ahc_send_async(ahc, devinfo->channel, devinfo->target,
2059                                CAM_LUN_WILDCARD, AC_TRANSFER_NEG, NULL);
2060                 if (bootverbose) {
2061                         printf("%s: target %d using %dbit transfers\n",
2062                                ahc_name(ahc), devinfo->target,
2063                                8 * (0x01 << width));
2064                 }
2065         }
2066
2067         update_needed += ahc_update_neg_request(ahc, devinfo, tstate,
2068                                                 tinfo, AHC_NEG_TO_GOAL);
2069         if (update_needed)
2070                 ahc_update_pending_scbs(ahc);
2071 }
2072
2073 /*
2074  * Update the current state of tagged queuing for a given target.
2075  */
2076 void
2077 ahc_set_tags(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
2078              ahc_queue_alg alg)
2079 {
2080         ahc_platform_set_tags(ahc, devinfo, alg);
2081         ahc_send_async(ahc, devinfo->channel, devinfo->target,
2082                        devinfo->lun, AC_TRANSFER_NEG, &alg);
2083 }
2084
2085 /*
2086  * When the transfer settings for a connection change, update any
2087  * in-transit SCBs to contain the new data so the hardware will
2088  * be set correctly during future (re)selections.
2089  */
2090 static void
2091 ahc_update_pending_scbs(struct ahc_softc *ahc)
2092 {
2093         struct  scb *pending_scb;
2094         int     pending_scb_count;
2095         int     i;
2096         int     paused;
2097         u_int   saved_scbptr;
2098
2099         /*
2100          * Traverse the pending SCB list and ensure that all of the
2101          * SCBs there have the proper settings.
2102          */
2103         pending_scb_count = 0;
2104         LIST_FOREACH(pending_scb, &ahc->pending_scbs, pending_links) {
2105                 struct ahc_devinfo devinfo;
2106                 struct hardware_scb *pending_hscb;
2107                 struct ahc_initiator_tinfo *tinfo;
2108                 struct ahc_tmode_tstate *tstate;
2109
2110                 ahc_scb_devinfo(ahc, &devinfo, pending_scb);
2111                 tinfo = ahc_fetch_transinfo(ahc, devinfo.channel,
2112                                             devinfo.our_scsiid,
2113                                             devinfo.target, &tstate);
2114                 pending_hscb = pending_scb->hscb;
2115                 pending_hscb->control &= ~ULTRAENB;
2116                 if ((tstate->ultraenb & devinfo.target_mask) != 0)
2117                         pending_hscb->control |= ULTRAENB;
2118                 pending_hscb->scsirate = tinfo->scsirate;
2119                 pending_hscb->scsioffset = tinfo->curr.offset;
2120                 if ((tstate->auto_negotiate & devinfo.target_mask) == 0
2121                  && (pending_scb->flags & SCB_AUTO_NEGOTIATE) != 0) {
2122                         pending_scb->flags &= ~SCB_AUTO_NEGOTIATE;
2123                         pending_hscb->control &= ~MK_MESSAGE;
2124                 }
2125                 ahc_sync_scb(ahc, pending_scb,
2126                              BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
2127                 pending_scb_count++;
2128         }
2129
2130         if (pending_scb_count == 0)
2131                 return;
2132
2133         if (ahc_is_paused(ahc)) {
2134                 paused = 1;
2135         } else {
2136                 paused = 0;
2137                 ahc_pause(ahc);
2138         }
2139
2140         saved_scbptr = ahc_inb(ahc, SCBPTR);
2141         /* Ensure that the hscbs down on the card match the new information */
2142         for (i = 0; i < ahc->scb_data->maxhscbs; i++) {
2143                 struct  hardware_scb *pending_hscb;
2144                 u_int   control;
2145                 u_int   scb_tag;
2146
2147                 ahc_outb(ahc, SCBPTR, i);
2148                 scb_tag = ahc_inb(ahc, SCB_TAG);
2149                 pending_scb = ahc_lookup_scb(ahc, scb_tag);
2150                 if (pending_scb == NULL)
2151                         continue;
2152
2153                 pending_hscb = pending_scb->hscb;
2154                 control = ahc_inb(ahc, SCB_CONTROL);
2155                 control &= ~(ULTRAENB|MK_MESSAGE);
2156                 control |= pending_hscb->control & (ULTRAENB|MK_MESSAGE);
2157                 ahc_outb(ahc, SCB_CONTROL, control);
2158                 ahc_outb(ahc, SCB_SCSIRATE, pending_hscb->scsirate);
2159                 ahc_outb(ahc, SCB_SCSIOFFSET, pending_hscb->scsioffset);
2160         }
2161         ahc_outb(ahc, SCBPTR, saved_scbptr);
2162
2163         if (paused == 0)
2164                 ahc_unpause(ahc);
2165 }
2166
2167 /**************************** Pathing Information *****************************/
2168 static void
2169 ahc_fetch_devinfo(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
2170 {
2171         u_int   saved_scsiid;
2172         role_t  role;
2173         int     our_id;
2174
2175         if (ahc_inb(ahc, SSTAT0) & TARGET)
2176                 role = ROLE_TARGET;
2177         else
2178                 role = ROLE_INITIATOR;
2179
2180         if (role == ROLE_TARGET
2181          && (ahc->features & AHC_MULTI_TID) != 0
2182          && (ahc_inb(ahc, SEQ_FLAGS)
2183            & (CMDPHASE_PENDING|TARG_CMD_PENDING|NO_DISCONNECT)) != 0) {
2184                 /* We were selected, so pull our id from TARGIDIN */
2185                 our_id = ahc_inb(ahc, TARGIDIN) & OID;
2186         } else if ((ahc->features & AHC_ULTRA2) != 0)
2187                 our_id = ahc_inb(ahc, SCSIID_ULTRA2) & OID;
2188         else
2189                 our_id = ahc_inb(ahc, SCSIID) & OID;
2190
2191         saved_scsiid = ahc_inb(ahc, SAVED_SCSIID);
2192         ahc_compile_devinfo(devinfo,
2193                             our_id,
2194                             SCSIID_TARGET(ahc, saved_scsiid),
2195                             ahc_inb(ahc, SAVED_LUN),
2196                             SCSIID_CHANNEL(ahc, saved_scsiid),
2197                             role);
2198 }
2199
2200 struct ahc_phase_table_entry*
2201 ahc_lookup_phase_entry(int phase)
2202 {
2203         struct ahc_phase_table_entry *entry;
2204         struct ahc_phase_table_entry *last_entry;
2205
2206         /*
2207          * num_phases doesn't include the default entry which
2208          * will be returned if the phase doesn't match.
2209          */
2210         last_entry = &ahc_phase_table[num_phases];
2211         for (entry = ahc_phase_table; entry < last_entry; entry++) {
2212                 if (phase == entry->phase)
2213                         break;
2214         }
2215         return (entry);
2216 }
2217
2218 void
2219 ahc_compile_devinfo(struct ahc_devinfo *devinfo, u_int our_id, u_int target,
2220                     u_int lun, char channel, role_t role)
2221 {
2222         devinfo->our_scsiid = our_id;
2223         devinfo->target = target;
2224         devinfo->lun = lun;
2225         devinfo->target_offset = target;
2226         devinfo->channel = channel;
2227         devinfo->role = role;
2228         if (channel == 'B')
2229                 devinfo->target_offset += 8;
2230         devinfo->target_mask = (0x01 << devinfo->target_offset);
2231 }
2232
2233 void
2234 ahc_print_devinfo(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
2235 {
2236         printf("%s:%c:%d:%d: ", ahc_name(ahc), devinfo->channel,
2237                devinfo->target, devinfo->lun);
2238 }
2239
2240 static void
2241 ahc_scb_devinfo(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
2242                 struct scb *scb)
2243 {
2244         role_t  role;
2245         int     our_id;
2246
2247         our_id = SCSIID_OUR_ID(scb->hscb->scsiid);
2248         role = ROLE_INITIATOR;
2249         if ((scb->flags & SCB_TARGET_SCB) != 0)
2250                 role = ROLE_TARGET;
2251         ahc_compile_devinfo(devinfo, our_id, SCB_GET_TARGET(ahc, scb),
2252                             SCB_GET_LUN(scb), SCB_GET_CHANNEL(ahc, scb), role);
2253 }
2254
2255
2256 /************************ Message Phase Processing ****************************/
2257 static void
2258 ahc_assert_atn(struct ahc_softc *ahc)
2259 {
2260         u_int scsisigo;
2261
2262         scsisigo = ATNO;
2263         if ((ahc->features & AHC_DT) == 0)
2264                 scsisigo |= ahc_inb(ahc, SCSISIGI);
2265         ahc_outb(ahc, SCSISIGO, scsisigo);
2266 }
2267
2268 /*
2269  * When an initiator transaction with the MK_MESSAGE flag either reconnects
2270  * or enters the initial message out phase, we are interrupted.  Fill our
2271  * outgoing message buffer with the appropriate message and beging handing
2272  * the message phase(s) manually.
2273  */
2274 static void
2275 ahc_setup_initiator_msgout(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
2276                            struct scb *scb)
2277 {
2278         /*
2279          * To facilitate adding multiple messages together,
2280          * each routine should increment the index and len
2281          * variables instead of setting them explicitly.
2282          */
2283         ahc->msgout_index = 0;
2284         ahc->msgout_len = 0;
2285
2286         if ((scb->flags & SCB_DEVICE_RESET) == 0
2287          && ahc_inb(ahc, MSG_OUT) == MSG_IDENTIFYFLAG) {
2288                 u_int identify_msg;
2289
2290                 identify_msg = MSG_IDENTIFYFLAG | SCB_GET_LUN(scb);
2291                 if ((scb->hscb->control & DISCENB) != 0)
2292                         identify_msg |= MSG_IDENTIFY_DISCFLAG;
2293                 ahc->msgout_buf[ahc->msgout_index++] = identify_msg;
2294                 ahc->msgout_len++;
2295
2296                 if ((scb->hscb->control & TAG_ENB) != 0) {
2297                         ahc->msgout_buf[ahc->msgout_index++] =
2298                             scb->hscb->control & (TAG_ENB|SCB_TAG_TYPE);
2299                         ahc->msgout_buf[ahc->msgout_index++] = scb->hscb->tag;
2300                         ahc->msgout_len += 2;
2301                 }
2302         }
2303
2304         if (scb->flags & SCB_DEVICE_RESET) {
2305                 ahc->msgout_buf[ahc->msgout_index++] = MSG_BUS_DEV_RESET;
2306                 ahc->msgout_len++;
2307                 ahc_print_path(ahc, scb);
2308                 printf("Bus Device Reset Message Sent\n");
2309                 /*
2310                  * Clear our selection hardware in advance of
2311                  * the busfree.  We may have an entry in the waiting
2312                  * Q for this target, and we don't want to go about
2313                  * selecting while we handle the busfree and blow it
2314                  * away.
2315                  */
2316                 ahc_outb(ahc, SCSISEQ, (ahc_inb(ahc, SCSISEQ) & ~ENSELO));
2317         } else if ((scb->flags & SCB_ABORT) != 0) {
2318                 if ((scb->hscb->control & TAG_ENB) != 0)
2319                         ahc->msgout_buf[ahc->msgout_index++] = MSG_ABORT_TAG;
2320                 else
2321                         ahc->msgout_buf[ahc->msgout_index++] = MSG_ABORT;
2322                 ahc->msgout_len++;
2323                 ahc_print_path(ahc, scb);
2324                 printf("Abort%s Message Sent\n",
2325                        (scb->hscb->control & TAG_ENB) != 0 ? " Tag" : "");
2326                 /*
2327                  * Clear our selection hardware in advance of
2328                  * the busfree.  We may have an entry in the waiting
2329                  * Q for this target, and we don't want to go about
2330                  * selecting while we handle the busfree and blow it
2331                  * away.
2332                  */
2333                 ahc_outb(ahc, SCSISEQ, (ahc_inb(ahc, SCSISEQ) & ~ENSELO));
2334         } else if ((scb->flags & (SCB_AUTO_NEGOTIATE|SCB_NEGOTIATE)) != 0) {
2335                 ahc_build_transfer_msg(ahc, devinfo);
2336         } else {
2337                 printf("ahc_intr: AWAITING_MSG for an SCB that "
2338                        "does not have a waiting message\n");
2339                 printf("SCSIID = %x, target_mask = %x\n", scb->hscb->scsiid,
2340                        devinfo->target_mask);
2341                 panic("SCB = %d, SCB Control = %x, MSG_OUT = %x "
2342                       "SCB flags = %x", scb->hscb->tag, scb->hscb->control,
2343                       ahc_inb(ahc, MSG_OUT), scb->flags);
2344         }
2345
2346         /*
2347          * Clear the MK_MESSAGE flag from the SCB so we aren't
2348          * asked to send this message again.
2349          */
2350         ahc_outb(ahc, SCB_CONTROL, ahc_inb(ahc, SCB_CONTROL) & ~MK_MESSAGE);
2351         scb->hscb->control &= ~MK_MESSAGE;
2352         ahc->msgout_index = 0;
2353         ahc->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
2354 }
2355
2356 /*
2357  * Build an appropriate transfer negotiation message for the
2358  * currently active target.
2359  */
2360 static void
2361 ahc_build_transfer_msg(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
2362 {
2363         /*
2364          * We need to initiate transfer negotiations.
2365          * If our current and goal settings are identical,
2366          * we want to renegotiate due to a check condition.
2367          */
2368         struct  ahc_initiator_tinfo *tinfo;
2369         struct  ahc_tmode_tstate *tstate;
2370         struct  ahc_syncrate *rate;
2371         int     dowide;
2372         int     dosync;
2373         int     doppr;
2374         u_int   period;
2375         u_int   ppr_options;
2376         u_int   offset;
2377
2378         tinfo = ahc_fetch_transinfo(ahc, devinfo->channel, devinfo->our_scsiid,
2379                                     devinfo->target, &tstate);
2380         /*
2381          * Filter our period based on the current connection.
2382          * If we can't perform DT transfers on this segment (not in LVD
2383          * mode for instance), then our decision to issue a PPR message
2384          * may change.
2385          */
2386         period = tinfo->goal.period;
2387         offset = tinfo->goal.offset;
2388         ppr_options = tinfo->goal.ppr_options;
2389         /* Target initiated PPR is not allowed in the SCSI spec */
2390         if (devinfo->role == ROLE_TARGET)
2391                 ppr_options = 0;
2392         rate = ahc_devlimited_syncrate(ahc, tinfo, &period,
2393                                        &ppr_options, devinfo->role);
2394         dowide = tinfo->curr.width != tinfo->goal.width;
2395         dosync = tinfo->curr.offset != offset || tinfo->curr.period != period;
2396         /*
2397          * Only use PPR if we have options that need it, even if the device
2398          * claims to support it.  There might be an expander in the way
2399          * that doesn't.
2400          */
2401         doppr = ppr_options != 0;
2402
2403         if (!dowide && !dosync && !doppr) {
2404                 dowide = tinfo->goal.width != MSG_EXT_WDTR_BUS_8_BIT;
2405                 dosync = tinfo->goal.offset != 0;
2406         }
2407
2408         if (!dowide && !dosync && !doppr) {
2409                 /*
2410                  * Force async with a WDTR message if we have a wide bus,
2411                  * or just issue an SDTR with a 0 offset.
2412                  */
2413                 if ((ahc->features & AHC_WIDE) != 0)
2414                         dowide = 1;
2415                 else
2416                         dosync = 1;
2417
2418                 if (bootverbose) {
2419                         ahc_print_devinfo(ahc, devinfo);
2420                         printf("Ensuring async\n");
2421                 }
2422         }
2423
2424         /* Target initiated PPR is not allowed in the SCSI spec */
2425         if (devinfo->role == ROLE_TARGET)
2426                 doppr = 0;
2427
2428         /*
2429          * Both the PPR message and SDTR message require the
2430          * goal syncrate to be limited to what the target device
2431          * is capable of handling (based on whether an LVD->SE
2432          * expander is on the bus), so combine these two cases.
2433          * Regardless, guarantee that if we are using WDTR and SDTR
2434          * messages that WDTR comes first.
2435          */
2436         if (doppr || (dosync && !dowide)) {
2437
2438                 offset = tinfo->goal.offset;
2439                 ahc_validate_offset(ahc, tinfo, rate, &offset,
2440                                     doppr ? tinfo->goal.width
2441                                           : tinfo->curr.width,
2442                                     devinfo->role);
2443                 if (doppr) {
2444                         ahc_construct_ppr(ahc, devinfo, period, offset,
2445                                           tinfo->goal.width, ppr_options);
2446                 } else {
2447                         ahc_construct_sdtr(ahc, devinfo, period, offset);
2448                 }
2449         } else {
2450                 ahc_construct_wdtr(ahc, devinfo, tinfo->goal.width);
2451         }
2452 }
2453
2454 /*
2455  * Build a synchronous negotiation message in our message
2456  * buffer based on the input parameters.
2457  */
2458 static void
2459 ahc_construct_sdtr(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
2460                    u_int period, u_int offset)
2461 {
2462         if (offset == 0)
2463                 period = AHC_ASYNC_XFER_PERIOD;
2464         ahc->msgout_index += spi_populate_sync_msg(
2465                         ahc->msgout_buf + ahc->msgout_index, period, offset);
2466         ahc->msgout_len += 5;
2467         if (bootverbose) {
2468                 printf("(%s:%c:%d:%d): Sending SDTR period %x, offset %x\n",
2469                        ahc_name(ahc), devinfo->channel, devinfo->target,
2470                        devinfo->lun, period, offset);
2471         }
2472 }
2473
2474 /*
2475  * Build a wide negotiation message in our message
2476  * buffer based on the input parameters.
2477  */
2478 static void
2479 ahc_construct_wdtr(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
2480                    u_int bus_width)
2481 {
2482         ahc->msgout_index += spi_populate_width_msg(
2483                         ahc->msgout_buf + ahc->msgout_index, bus_width);
2484         ahc->msgout_len += 4;
2485         if (bootverbose) {
2486                 printf("(%s:%c:%d:%d): Sending WDTR %x\n",
2487                        ahc_name(ahc), devinfo->channel, devinfo->target,
2488                        devinfo->lun, bus_width);
2489         }
2490 }
2491
2492 /*
2493  * Build a parallel protocol request message in our message
2494  * buffer based on the input parameters.
2495  */
2496 static void
2497 ahc_construct_ppr(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
2498                   u_int period, u_int offset, u_int bus_width,
2499                   u_int ppr_options)
2500 {
2501         if (offset == 0)
2502                 period = AHC_ASYNC_XFER_PERIOD;
2503         ahc->msgout_index += spi_populate_ppr_msg(
2504                         ahc->msgout_buf + ahc->msgout_index, period, offset,
2505                         bus_width, ppr_options);
2506         ahc->msgout_len += 8;
2507         if (bootverbose) {
2508                 printf("(%s:%c:%d:%d): Sending PPR bus_width %x, period %x, "
2509                        "offset %x, ppr_options %x\n", ahc_name(ahc),
2510                        devinfo->channel, devinfo->target, devinfo->lun,
2511                        bus_width, period, offset, ppr_options);
2512         }
2513 }
2514
2515 /*
2516  * Clear any active message state.
2517  */
2518 static void
2519 ahc_clear_msg_state(struct ahc_softc *ahc)
2520 {
2521         ahc->msgout_len = 0;
2522         ahc->msgin_index = 0;
2523         ahc->msg_type = MSG_TYPE_NONE;
2524         if ((ahc_inb(ahc, SCSISIGI) & ATNI) != 0) {
2525                 /*
2526                  * The target didn't care to respond to our
2527                  * message request, so clear ATN.
2528                  */
2529                 ahc_outb(ahc, CLRSINT1, CLRATNO);
2530         }
2531         ahc_outb(ahc, MSG_OUT, MSG_NOOP);
2532         ahc_outb(ahc, SEQ_FLAGS2,
2533                  ahc_inb(ahc, SEQ_FLAGS2) & ~TARGET_MSG_PENDING);
2534 }
2535
2536 static void
2537 ahc_handle_proto_violation(struct ahc_softc *ahc)
2538 {
2539         struct  ahc_devinfo devinfo;
2540         struct  scb *scb;
2541         u_int   scbid;
2542         u_int   seq_flags;
2543         u_int   curphase;
2544         u_int   lastphase;
2545         int     found;
2546
2547         ahc_fetch_devinfo(ahc, &devinfo);
2548         scbid = ahc_inb(ahc, SCB_TAG);
2549         scb = ahc_lookup_scb(ahc, scbid);
2550         seq_flags = ahc_inb(ahc, SEQ_FLAGS);
2551         curphase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
2552         lastphase = ahc_inb(ahc, LASTPHASE);
2553         if ((seq_flags & NOT_IDENTIFIED) != 0) {
2554
2555                 /*
2556                  * The reconnecting target either did not send an
2557                  * identify message, or did, but we didn't find an SCB
2558                  * to match.
2559                  */
2560                 ahc_print_devinfo(ahc, &devinfo);
2561                 printf("Target did not send an IDENTIFY message. "
2562                        "LASTPHASE = 0x%x.\n", lastphase);
2563                 scb = NULL;
2564         } else if (scb == NULL) {
2565                 /*
2566                  * We don't seem to have an SCB active for this
2567                  * transaction.  Print an error and reset the bus.
2568                  */
2569                 ahc_print_devinfo(ahc, &devinfo);
2570                 printf("No SCB found during protocol violation\n");
2571                 goto proto_violation_reset;
2572         } else {
2573                 ahc_set_transaction_status(scb, CAM_SEQUENCE_FAIL);
2574                 if ((seq_flags & NO_CDB_SENT) != 0) {
2575                         ahc_print_path(ahc, scb);
2576                         printf("No or incomplete CDB sent to device.\n");
2577                 } else if ((ahc_inb(ahc, SCB_CONTROL) & STATUS_RCVD) == 0) {
2578                         /*
2579                          * The target never bothered to provide status to
2580                          * us prior to completing the command.  Since we don't
2581                          * know the disposition of this command, we must attempt
2582                          * to abort it.  Assert ATN and prepare to send an abort
2583                          * message.
2584                          */
2585                         ahc_print_path(ahc, scb);
2586                         printf("Completed command without status.\n");
2587                 } else {
2588                         ahc_print_path(ahc, scb);
2589                         printf("Unknown protocol violation.\n");
2590                         ahc_dump_card_state(ahc);
2591                 }
2592         }
2593         if ((lastphase & ~P_DATAIN_DT) == 0
2594          || lastphase == P_COMMAND) {
2595 proto_violation_reset:
2596                 /*
2597                  * Target either went directly to data/command
2598                  * phase or didn't respond to our ATN.
2599                  * The only safe thing to do is to blow
2600                  * it away with a bus reset.
2601                  */
2602                 found = ahc_reset_channel(ahc, 'A', TRUE);
2603                 printf("%s: Issued Channel %c Bus Reset. "
2604                        "%d SCBs aborted\n", ahc_name(ahc), 'A', found);
2605         } else {
2606                 /*
2607                  * Leave the selection hardware off in case
2608                  * this abort attempt will affect yet to
2609                  * be sent commands.
2610                  */
2611                 ahc_outb(ahc, SCSISEQ,
2612                          ahc_inb(ahc, SCSISEQ) & ~ENSELO);
2613                 ahc_assert_atn(ahc);
2614                 ahc_outb(ahc, MSG_OUT, HOST_MSG);
2615                 if (scb == NULL) {
2616                         ahc_print_devinfo(ahc, &devinfo);
2617                         ahc->msgout_buf[0] = MSG_ABORT_TASK;
2618                         ahc->msgout_len = 1;
2619                         ahc->msgout_index = 0;
2620                         ahc->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
2621                 } else {
2622                         ahc_print_path(ahc, scb);
2623                         scb->flags |= SCB_ABORT;
2624                 }
2625                 printf("Protocol violation %s.  Attempting to abort.\n",
2626                        ahc_lookup_phase_entry(curphase)->phasemsg);
2627         }
2628 }
2629
2630 /*
2631  * Manual message loop handler.
2632  */
2633 static void
2634 ahc_handle_message_phase(struct ahc_softc *ahc)
2635
2636         struct  ahc_devinfo devinfo;
2637         u_int   bus_phase;
2638         int     end_session;
2639
2640         ahc_fetch_devinfo(ahc, &devinfo);
2641         end_session = FALSE;
2642         bus_phase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
2643
2644 reswitch:
2645         switch (ahc->msg_type) {
2646         case MSG_TYPE_INITIATOR_MSGOUT:
2647         {
2648                 int lastbyte;
2649                 int phasemis;
2650                 int msgdone;
2651
2652                 if (ahc->msgout_len == 0)
2653                         panic("HOST_MSG_LOOP interrupt with no active message");
2654
2655 #ifdef AHC_DEBUG
2656                 if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
2657                         ahc_print_devinfo(ahc, &devinfo);
2658                         printf("INITIATOR_MSG_OUT");
2659                 }
2660 #endif
2661                 phasemis = bus_phase != P_MESGOUT;
2662                 if (phasemis) {
2663 #ifdef AHC_DEBUG
2664                         if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
2665                                 printf(" PHASEMIS %s\n",
2666                                        ahc_lookup_phase_entry(bus_phase)
2667                                                              ->phasemsg);
2668                         }
2669 #endif
2670                         if (bus_phase == P_MESGIN) {
2671                                 /*
2672                                  * Change gears and see if
2673                                  * this messages is of interest to
2674                                  * us or should be passed back to
2675                                  * the sequencer.
2676                                  */
2677                                 ahc_outb(ahc, CLRSINT1, CLRATNO);
2678                                 ahc->send_msg_perror = FALSE;
2679                                 ahc->msg_type = MSG_TYPE_INITIATOR_MSGIN;
2680                                 ahc->msgin_index = 0;
2681                                 goto reswitch;
2682                         }
2683                         end_session = TRUE;
2684                         break;
2685                 }
2686
2687                 if (ahc->send_msg_perror) {
2688                         ahc_outb(ahc, CLRSINT1, CLRATNO);
2689                         ahc_outb(ahc, CLRSINT1, CLRREQINIT);
2690 #ifdef AHC_DEBUG
2691                         if ((ahc_debug & AHC_SHOW_MESSAGES) != 0)
2692                                 printf(" byte 0x%x\n", ahc->send_msg_perror);
2693 #endif
2694                         ahc_outb(ahc, SCSIDATL, MSG_PARITY_ERROR);
2695                         break;
2696                 }
2697
2698                 msgdone = ahc->msgout_index == ahc->msgout_len;
2699                 if (msgdone) {
2700                         /*
2701                          * The target has requested a retry.
2702                          * Re-assert ATN, reset our message index to
2703                          * 0, and try again.
2704                          */
2705                         ahc->msgout_index = 0;
2706                         ahc_assert_atn(ahc);
2707                 }
2708
2709                 lastbyte = ahc->msgout_index == (ahc->msgout_len - 1);
2710                 if (lastbyte) {
2711                         /* Last byte is signified by dropping ATN */
2712                         ahc_outb(ahc, CLRSINT1, CLRATNO);
2713                 }
2714
2715                 /*
2716                  * Clear our interrupt status and present
2717                  * the next byte on the bus.
2718                  */
2719                 ahc_outb(ahc, CLRSINT1, CLRREQINIT);
2720 #ifdef AHC_DEBUG
2721                 if ((ahc_debug & AHC_SHOW_MESSAGES) != 0)
2722                         printf(" byte 0x%x\n",
2723                                ahc->msgout_buf[ahc->msgout_index]);
2724 #endif
2725                 ahc_outb(ahc, SCSIDATL, ahc->msgout_buf[ahc->msgout_index++]);
2726                 break;
2727         }
2728         case MSG_TYPE_INITIATOR_MSGIN:
2729         {
2730                 int phasemis;
2731                 int message_done;
2732
2733 #ifdef AHC_DEBUG
2734                 if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
2735                         ahc_print_devinfo(ahc, &devinfo);
2736                         printf("INITIATOR_MSG_IN");
2737                 }
2738 #endif
2739                 phasemis = bus_phase != P_MESGIN;
2740                 if (phasemis) {
2741 #ifdef AHC_DEBUG
2742                         if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
2743                                 printf(" PHASEMIS %s\n",
2744                                        ahc_lookup_phase_entry(bus_phase)
2745                                                              ->phasemsg);
2746                         }
2747 #endif
2748                         ahc->msgin_index = 0;
2749                         if (bus_phase == P_MESGOUT
2750                          && (ahc->send_msg_perror == TRUE
2751                           || (ahc->msgout_len != 0
2752                            && ahc->msgout_index == 0))) {
2753                                 ahc->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
2754                                 goto reswitch;
2755                         }
2756                         end_session = TRUE;
2757                         break;
2758                 }
2759
2760                 /* Pull the byte in without acking it */
2761                 ahc->msgin_buf[ahc->msgin_index] = ahc_inb(ahc, SCSIBUSL);
2762 #ifdef AHC_DEBUG
2763                 if ((ahc_debug & AHC_SHOW_MESSAGES) != 0)
2764                         printf(" byte 0x%x\n",
2765                                ahc->msgin_buf[ahc->msgin_index]);
2766 #endif
2767
2768                 message_done = ahc_parse_msg(ahc, &devinfo);
2769
2770                 if (message_done) {
2771                         /*
2772                          * Clear our incoming message buffer in case there
2773                          * is another message following this one.
2774                          */
2775                         ahc->msgin_index = 0;
2776
2777                         /*
2778                          * If this message illicited a response,
2779                          * assert ATN so the target takes us to the
2780                          * message out phase.
2781                          */
2782                         if (ahc->msgout_len != 0) {
2783 #ifdef AHC_DEBUG
2784                                 if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
2785                                         ahc_print_devinfo(ahc, &devinfo);
2786                                         printf("Asserting ATN for response\n");
2787                                 }
2788 #endif
2789                                 ahc_assert_atn(ahc);
2790                         }
2791                 } else 
2792                         ahc->msgin_index++;
2793
2794                 if (message_done == MSGLOOP_TERMINATED) {
2795                         end_session = TRUE;
2796                 } else {
2797                         /* Ack the byte */
2798                         ahc_outb(ahc, CLRSINT1, CLRREQINIT);
2799                         ahc_inb(ahc, SCSIDATL);
2800                 }
2801                 break;
2802         }
2803         case MSG_TYPE_TARGET_MSGIN:
2804         {
2805                 int msgdone;
2806                 int msgout_request;
2807
2808                 if (ahc->msgout_len == 0)
2809                         panic("Target MSGIN with no active message");
2810
2811                 /*
2812                  * If we interrupted a mesgout session, the initiator
2813                  * will not know this until our first REQ.  So, we
2814                  * only honor mesgout requests after we've sent our
2815                  * first byte.
2816                  */
2817                 if ((ahc_inb(ahc, SCSISIGI) & ATNI) != 0
2818                  && ahc->msgout_index > 0)
2819                         msgout_request = TRUE;
2820                 else
2821                         msgout_request = FALSE;
2822
2823                 if (msgout_request) {
2824
2825                         /*
2826                          * Change gears and see if
2827                          * this messages is of interest to
2828                          * us or should be passed back to
2829                          * the sequencer.
2830                          */
2831                         ahc->msg_type = MSG_TYPE_TARGET_MSGOUT;
2832                         ahc_outb(ahc, SCSISIGO, P_MESGOUT | BSYO);
2833                         ahc->msgin_index = 0;
2834                         /* Dummy read to REQ for first byte */
2835                         ahc_inb(ahc, SCSIDATL);
2836                         ahc_outb(ahc, SXFRCTL0,
2837                                  ahc_inb(ahc, SXFRCTL0) | SPIOEN);
2838                         break;
2839                 }
2840
2841                 msgdone = ahc->msgout_index == ahc->msgout_len;
2842                 if (msgdone) {
2843                         ahc_outb(ahc, SXFRCTL0,
2844                                  ahc_inb(ahc, SXFRCTL0) & ~SPIOEN);
2845                         end_session = TRUE;
2846                         break;
2847                 }
2848
2849                 /*
2850                  * Present the next byte on the bus.
2851                  */
2852                 ahc_outb(ahc, SXFRCTL0, ahc_inb(ahc, SXFRCTL0) | SPIOEN);
2853                 ahc_outb(ahc, SCSIDATL, ahc->msgout_buf[ahc->msgout_index++]);
2854                 break;
2855         }
2856         case MSG_TYPE_TARGET_MSGOUT:
2857         {
2858                 int lastbyte;
2859                 int msgdone;
2860
2861                 /*
2862                  * The initiator signals that this is
2863                  * the last byte by dropping ATN.
2864                  */
2865                 lastbyte = (ahc_inb(ahc, SCSISIGI) & ATNI) == 0;
2866
2867                 /*
2868                  * Read the latched byte, but turn off SPIOEN first
2869                  * so that we don't inadvertently cause a REQ for the
2870                  * next byte.
2871                  */
2872                 ahc_outb(ahc, SXFRCTL0, ahc_inb(ahc, SXFRCTL0) & ~SPIOEN);
2873                 ahc->msgin_buf[ahc->msgin_index] = ahc_inb(ahc, SCSIDATL);
2874                 msgdone = ahc_parse_msg(ahc, &devinfo);
2875                 if (msgdone == MSGLOOP_TERMINATED) {
2876                         /*
2877                          * The message is *really* done in that it caused
2878                          * us to go to bus free.  The sequencer has already
2879                          * been reset at this point, so pull the ejection
2880                          * handle.
2881                          */
2882                         return;
2883                 }
2884                 
2885                 ahc->msgin_index++;
2886
2887                 /*
2888                  * XXX Read spec about initiator dropping ATN too soon
2889                  *     and use msgdone to detect it.
2890                  */
2891                 if (msgdone == MSGLOOP_MSGCOMPLETE) {
2892                         ahc->msgin_index = 0;
2893
2894                         /*
2895                          * If this message illicited a response, transition
2896                          * to the Message in phase and send it.
2897                          */
2898                         if (ahc->msgout_len != 0) {
2899                                 ahc_outb(ahc, SCSISIGO, P_MESGIN | BSYO);
2900                                 ahc_outb(ahc, SXFRCTL0,
2901                                          ahc_inb(ahc, SXFRCTL0) | SPIOEN);
2902                                 ahc->msg_type = MSG_TYPE_TARGET_MSGIN;
2903                                 ahc->msgin_index = 0;
2904                                 break;
2905                         }
2906                 }
2907
2908                 if (lastbyte)
2909                         end_session = TRUE;
2910                 else {
2911                         /* Ask for the next byte. */
2912                         ahc_outb(ahc, SXFRCTL0,
2913                                  ahc_inb(ahc, SXFRCTL0) | SPIOEN);
2914                 }
2915
2916                 break;
2917         }
2918         default:
2919                 panic("Unknown REQINIT message type");
2920         }
2921
2922         if (end_session) {
2923                 ahc_clear_msg_state(ahc);
2924                 ahc_outb(ahc, RETURN_1, EXIT_MSG_LOOP);
2925         } else
2926                 ahc_outb(ahc, RETURN_1, CONT_MSG_LOOP);
2927 }
2928
2929 /*
2930  * See if we sent a particular extended message to the target.
2931  * If "full" is true, return true only if the target saw the full
2932  * message.  If "full" is false, return true if the target saw at
2933  * least the first byte of the message.
2934  */
2935 static int
2936 ahc_sent_msg(struct ahc_softc *ahc, ahc_msgtype type, u_int msgval, int full)
2937 {
2938         int found;
2939         u_int index;
2940
2941         found = FALSE;
2942         index = 0;
2943
2944         while (index < ahc->msgout_len) {
2945                 if (ahc->msgout_buf[index] == MSG_EXTENDED) {
2946                         u_int end_index;
2947
2948                         end_index = index + 1 + ahc->msgout_buf[index + 1];
2949                         if (ahc->msgout_buf[index+2] == msgval
2950                          && type == AHCMSG_EXT) {
2951
2952                                 if (full) {
2953                                         if (ahc->msgout_index > end_index)
2954                                                 found = TRUE;
2955                                 } else if (ahc->msgout_index > index)
2956                                         found = TRUE;
2957                         }
2958                         index = end_index;
2959                 } else if (ahc->msgout_buf[index] >= MSG_SIMPLE_TASK
2960                         && ahc->msgout_buf[index] <= MSG_IGN_WIDE_RESIDUE) {
2961
2962                         /* Skip tag type and tag id or residue param*/
2963                         index += 2;
2964                 } else {
2965                         /* Single byte message */
2966                         if (type == AHCMSG_1B
2967                          && ahc->msgout_buf[index] == msgval
2968                          && ahc->msgout_index > index)
2969                                 found = TRUE;
2970                         index++;
2971                 }
2972
2973                 if (found)
2974                         break;
2975         }
2976         return (found);
2977 }
2978
2979 /*
2980  * Wait for a complete incoming message, parse it, and respond accordingly.
2981  */
2982 static int
2983 ahc_parse_msg(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
2984 {
2985         struct  ahc_initiator_tinfo *tinfo;
2986         struct  ahc_tmode_tstate *tstate;
2987         int     reject;
2988         int     done;
2989         int     response;
2990         u_int   targ_scsirate;
2991
2992         done = MSGLOOP_IN_PROG;
2993         response = FALSE;
2994         reject = FALSE;
2995         tinfo = ahc_fetch_transinfo(ahc, devinfo->channel, devinfo->our_scsiid,
2996                                     devinfo->target, &tstate);
2997         targ_scsirate = tinfo->scsirate;
2998
2999         /*
3000          * Parse as much of the message as is available,
3001          * rejecting it if we don't support it.  When
3002          * the entire message is available and has been
3003          * handled, return MSGLOOP_MSGCOMPLETE, indicating
3004          * that we have parsed an entire message.
3005          *
3006          * In the case of extended messages, we accept the length
3007          * byte outright and perform more checking once we know the
3008          * extended message type.
3009          */
3010         switch (ahc->msgin_buf[0]) {
3011         case MSG_DISCONNECT:
3012         case MSG_SAVEDATAPOINTER:
3013         case MSG_CMDCOMPLETE:
3014         case MSG_RESTOREPOINTERS:
3015         case MSG_IGN_WIDE_RESIDUE:
3016                 /*
3017                  * End our message loop as these are messages
3018                  * the sequencer handles on its own.
3019                  */
3020                 done = MSGLOOP_TERMINATED;
3021                 break;
3022         case MSG_MESSAGE_REJECT:
3023                 response = ahc_handle_msg_reject(ahc, devinfo);
3024                 /* FALLTHROUGH */
3025         case MSG_NOOP:
3026                 done = MSGLOOP_MSGCOMPLETE;
3027                 break;
3028         case MSG_EXTENDED:
3029         {
3030                 /* Wait for enough of the message to begin validation */
3031                 if (ahc->msgin_index < 2)
3032                         break;
3033                 switch (ahc->msgin_buf[2]) {
3034                 case MSG_EXT_SDTR:
3035                 {
3036                         struct   ahc_syncrate *syncrate;
3037                         u_int    period;
3038                         u_int    ppr_options;
3039                         u_int    offset;
3040                         u_int    saved_offset;
3041                         
3042                         if (ahc->msgin_buf[1] != MSG_EXT_SDTR_LEN) {
3043                                 reject = TRUE;
3044                                 break;
3045                         }
3046
3047                         /*
3048                          * Wait until we have both args before validating
3049                          * and acting on this message.
3050                          *
3051                          * Add one to MSG_EXT_SDTR_LEN to account for
3052                          * the extended message preamble.
3053                          */
3054                         if (ahc->msgin_index < (MSG_EXT_SDTR_LEN + 1))
3055                                 break;
3056
3057                         period = ahc->msgin_buf[3];
3058                         ppr_options = 0;
3059                         saved_offset = offset = ahc->msgin_buf[4];
3060                         syncrate = ahc_devlimited_syncrate(ahc, tinfo, &period,
3061                                                            &ppr_options,
3062                                                            devinfo->role);
3063                         ahc_validate_offset(ahc, tinfo, syncrate, &offset,
3064                                             targ_scsirate & WIDEXFER,
3065                                             devinfo->role);
3066                         if (bootverbose) {
3067                                 printf("(%s:%c:%d:%d): Received "
3068                                        "SDTR period %x, offset %x\n\t"
3069                                        "Filtered to period %x, offset %x\n",
3070                                        ahc_name(ahc), devinfo->channel,
3071                                        devinfo->target, devinfo->lun,
3072                                        ahc->msgin_buf[3], saved_offset,
3073                                        period, offset);
3074                         }
3075                         ahc_set_syncrate(ahc, devinfo, 
3076                                          syncrate, period,
3077                                          offset, ppr_options,
3078                                          AHC_TRANS_ACTIVE|AHC_TRANS_GOAL,
3079                                          /*paused*/TRUE);
3080
3081                         /*
3082                          * See if we initiated Sync Negotiation
3083                          * and didn't have to fall down to async
3084                          * transfers.
3085                          */
3086                         if (ahc_sent_msg(ahc, AHCMSG_EXT, MSG_EXT_SDTR, TRUE)) {
3087                                 /* We started it */
3088                                 if (saved_offset != offset) {
3089                                         /* Went too low - force async */
3090                                         reject = TRUE;
3091                                 }
3092                         } else {
3093                                 /*
3094                                  * Send our own SDTR in reply
3095                                  */
3096                                 if (bootverbose
3097                                  && devinfo->role == ROLE_INITIATOR) {
3098                                         printf("(%s:%c:%d:%d): Target "
3099                                                "Initiated SDTR\n",
3100                                                ahc_name(ahc), devinfo->channel,
3101                                                devinfo->target, devinfo->lun);
3102                                 }
3103                                 ahc->msgout_index = 0;
3104                                 ahc->msgout_len = 0;
3105                                 ahc_construct_sdtr(ahc, devinfo,
3106                                                    period, offset);
3107                                 ahc->msgout_index = 0;
3108                                 response = TRUE;
3109                         }
3110                         done = MSGLOOP_MSGCOMPLETE;
3111                         break;
3112                 }
3113                 case MSG_EXT_WDTR:
3114                 {
3115                         u_int bus_width;
3116                         u_int saved_width;
3117                         u_int sending_reply;
3118
3119                         sending_reply = FALSE;
3120                         if (ahc->msgin_buf[1] != MSG_EXT_WDTR_LEN) {
3121                                 reject = TRUE;
3122                                 break;
3123                         }
3124
3125                         /*
3126                          * Wait until we have our arg before validating
3127                          * and acting on this message.
3128                          *
3129                          * Add one to MSG_EXT_WDTR_LEN to account for
3130                          * the extended message preamble.
3131                          */
3132                         if (ahc->msgin_index < (MSG_EXT_WDTR_LEN + 1))
3133                                 break;
3134
3135                         bus_width = ahc->msgin_buf[3];
3136                         saved_width = bus_width;
3137                         ahc_validate_width(ahc, tinfo, &bus_width,
3138                                            devinfo->role);
3139                         if (bootverbose) {
3140                                 printf("(%s:%c:%d:%d): Received WDTR "
3141                                        "%x filtered to %x\n",
3142                                        ahc_name(ahc), devinfo->channel,
3143                                        devinfo->target, devinfo->lun,
3144                                        saved_width, bus_width);
3145                         }
3146
3147                         if (ahc_sent_msg(ahc, AHCMSG_EXT, MSG_EXT_WDTR, TRUE)) {
3148                                 /*
3149                                  * Don't send a WDTR back to the
3150                                  * target, since we asked first.
3151                                  * If the width went higher than our
3152                                  * request, reject it.
3153                                  */
3154                                 if (saved_width > bus_width) {
3155                                         reject = TRUE;
3156                                         printf("(%s:%c:%d:%d): requested %dBit "
3157                                                "transfers.  Rejecting...\n",
3158                                                ahc_name(ahc), devinfo->channel,
3159                                                devinfo->target, devinfo->lun,
3160                                                8 * (0x01 << bus_width));
3161                                         bus_width = 0;
3162                                 }
3163                         } else {
3164                                 /*
3165                                  * Send our own WDTR in reply
3166                                  */
3167                                 if (bootverbose
3168                                  && devinfo->role == ROLE_INITIATOR) {
3169                                         printf("(%s:%c:%d:%d): Target "
3170                                                "Initiated WDTR\n",
3171                                                ahc_name(ahc), devinfo->channel,
3172                                                devinfo->target, devinfo->lun);
3173                                 }
3174                                 ahc->msgout_index = 0;
3175                                 ahc->msgout_len = 0;
3176                                 ahc_construct_wdtr(ahc, devinfo, bus_width);
3177                                 ahc->msgout_index = 0;
3178                                 response = TRUE;
3179                                 sending_reply = TRUE;
3180                         }
3181                         /*
3182                          * After a wide message, we are async, but
3183                          * some devices don't seem to honor this portion
3184                          * of the spec.  Force a renegotiation of the
3185                          * sync component of our transfer agreement even
3186                          * if our goal is async.  By updating our width
3187                          * after forcing the negotiation, we avoid
3188                          * renegotiating for width.
3189                          */
3190                         ahc_update_neg_request(ahc, devinfo, tstate,
3191                                                tinfo, AHC_NEG_ALWAYS);
3192                         ahc_set_width(ahc, devinfo, bus_width,
3193                                       AHC_TRANS_ACTIVE|AHC_TRANS_GOAL,
3194                                       /*paused*/TRUE);
3195                         if (sending_reply == FALSE && reject == FALSE) {
3196
3197                                 /*
3198                                  * We will always have an SDTR to send.
3199                                  */
3200                                 ahc->msgout_index = 0;
3201                                 ahc->msgout_len = 0;
3202                                 ahc_build_transfer_msg(ahc, devinfo);
3203                                 ahc->msgout_index = 0;
3204                                 response = TRUE;
3205                         }
3206                         done = MSGLOOP_MSGCOMPLETE;
3207                         break;
3208                 }
3209                 case MSG_EXT_PPR:
3210                 {
3211                         struct  ahc_syncrate *syncrate;
3212                         u_int   period;
3213                         u_int   offset;
3214                         u_int   bus_width;
3215                         u_int   ppr_options;
3216                         u_int   saved_width;
3217                         u_int   saved_offset;
3218                         u_int   saved_ppr_options;
3219
3220                         if (ahc->msgin_buf[1] != MSG_EXT_PPR_LEN) {
3221                                 reject = TRUE;
3222                                 break;
3223                         }
3224
3225                         /*
3226                          * Wait until we have all args before validating
3227                          * and acting on this message.
3228                          *
3229                          * Add one to MSG_EXT_PPR_LEN to account for
3230                          * the extended message preamble.
3231                          */
3232                         if (ahc->msgin_index < (MSG_EXT_PPR_LEN + 1))
3233                                 break;
3234
3235                         period = ahc->msgin_buf[3];
3236                         offset = ahc->msgin_buf[5];
3237                         bus_width = ahc->msgin_buf[6];
3238                         saved_width = bus_width;
3239                         ppr_options = ahc->msgin_buf[7];
3240                         /*
3241                          * According to the spec, a DT only
3242                          * period factor with no DT option
3243                          * set implies async.
3244                          */
3245                         if ((ppr_options & MSG_EXT_PPR_DT_REQ) == 0
3246                          && period == 9)
3247                                 offset = 0;
3248                         saved_ppr_options = ppr_options;
3249                         saved_offset = offset;
3250
3251                         /*
3252                          * Mask out any options we don't support
3253                          * on any controller.  Transfer options are
3254                          * only available if we are negotiating wide.
3255                          */
3256                         ppr_options &= MSG_EXT_PPR_DT_REQ;
3257                         if (bus_width == 0)
3258                                 ppr_options = 0;
3259
3260                         ahc_validate_width(ahc, tinfo, &bus_width,
3261                                            devinfo->role);
3262                         syncrate = ahc_devlimited_syncrate(ahc, tinfo, &period,
3263                                                            &ppr_options,
3264                                                            devinfo->role);
3265                         ahc_validate_offset(ahc, tinfo, syncrate,
3266                                             &offset, bus_width,
3267                                             devinfo->role);
3268
3269                         if (ahc_sent_msg(ahc, AHCMSG_EXT, MSG_EXT_PPR, TRUE)) {
3270                                 /*
3271                                  * If we are unable to do any of the
3272                                  * requested options (we went too low),
3273                                  * then we'll have to reject the message.
3274                                  */
3275                                 if (saved_width > bus_width
3276                                  || saved_offset != offset
3277                                  || saved_ppr_options != ppr_options) {
3278                                         reject = TRUE;
3279                                         period = 0;
3280                                         offset = 0;
3281                                         bus_width = 0;
3282                                         ppr_options = 0;
3283                                         syncrate = NULL;
3284                                 }
3285                         } else {
3286                                 if (devinfo->role != ROLE_TARGET)
3287                                         printf("(%s:%c:%d:%d): Target "
3288                                                "Initiated PPR\n",
3289                                                ahc_name(ahc), devinfo->channel,
3290                                                devinfo->target, devinfo->lun);
3291                                 else
3292                                         printf("(%s:%c:%d:%d): Initiator "
3293                                                "Initiated PPR\n",
3294                                                ahc_name(ahc), devinfo->channel,
3295                                                devinfo->target, devinfo->lun);
3296                                 ahc->msgout_index = 0;
3297                                 ahc->msgout_len = 0;
3298                                 ahc_construct_ppr(ahc, devinfo, period, offset,
3299                                                   bus_width, ppr_options);
3300                                 ahc->msgout_index = 0;
3301                                 response = TRUE;
3302                         }
3303                         if (bootverbose) {
3304                                 printf("(%s:%c:%d:%d): Received PPR width %x, "
3305                                        "period %x, offset %x,options %x\n"
3306                                        "\tFiltered to width %x, period %x, "
3307                                        "offset %x, options %x\n",
3308                                        ahc_name(ahc), devinfo->channel,
3309                                        devinfo->target, devinfo->lun,
3310                                        saved_width, ahc->msgin_buf[3],
3311                                        saved_offset, saved_ppr_options,
3312                                        bus_width, period, offset, ppr_options);
3313                         }
3314                         ahc_set_width(ahc, devinfo, bus_width,
3315                                       AHC_TRANS_ACTIVE|AHC_TRANS_GOAL,
3316                                       /*paused*/TRUE);
3317                         ahc_set_syncrate(ahc, devinfo,
3318                                          syncrate, period,
3319                                          offset, ppr_options,
3320                                          AHC_TRANS_ACTIVE|AHC_TRANS_GOAL,
3321                                          /*paused*/TRUE);
3322                         done = MSGLOOP_MSGCOMPLETE;
3323                         break;
3324                 }
3325                 default:
3326                         /* Unknown extended message.  Reject it. */
3327                         reject = TRUE;
3328                         break;
3329                 }
3330                 break;
3331         }
3332 #ifdef AHC_TARGET_MODE
3333         case MSG_BUS_DEV_RESET:
3334                 ahc_handle_devreset(ahc, devinfo,
3335                                     CAM_BDR_SENT,
3336                                     "Bus Device Reset Received",
3337                                     /*verbose_level*/0);
3338                 ahc_restart(ahc);
3339                 done = MSGLOOP_TERMINATED;
3340                 break;
3341         case MSG_ABORT_TAG:
3342         case MSG_ABORT:
3343         case MSG_CLEAR_QUEUE:
3344         {
3345                 int tag;
3346
3347                 /* Target mode messages */
3348                 if (devinfo->role != ROLE_TARGET) {
3349                         reject = TRUE;
3350                         break;
3351                 }
3352                 tag = SCB_LIST_NULL;
3353                 if (ahc->msgin_buf[0] == MSG_ABORT_TAG)
3354                         tag = ahc_inb(ahc, INITIATOR_TAG);
3355                 ahc_abort_scbs(ahc, devinfo->target, devinfo->channel,
3356                                devinfo->lun, tag, ROLE_TARGET,
3357                                CAM_REQ_ABORTED);
3358
3359                 tstate = ahc->enabled_targets[devinfo->our_scsiid];
3360                 if (tstate != NULL) {
3361                         struct ahc_tmode_lstate* lstate;
3362
3363                         lstate = tstate->enabled_luns[devinfo->lun];
3364                         if (lstate != NULL) {
3365                                 ahc_queue_lstate_event(ahc, lstate,
3366                                                        devinfo->our_scsiid,
3367                                                        ahc->msgin_buf[0],
3368                                                        /*arg*/tag);
3369                                 ahc_send_lstate_events(ahc, lstate);
3370                         }
3371                 }
3372                 ahc_restart(ahc);
3373                 done = MSGLOOP_TERMINATED;
3374                 break;
3375         }
3376 #endif
3377         case MSG_TERM_IO_PROC:
3378         default:
3379                 reject = TRUE;
3380                 break;
3381         }
3382
3383         if (reject) {
3384                 /*
3385                  * Setup to reject the message.
3386                  */
3387                 ahc->msgout_index = 0;
3388                 ahc->msgout_len = 1;
3389                 ahc->msgout_buf[0] = MSG_MESSAGE_REJECT;
3390                 done = MSGLOOP_MSGCOMPLETE;
3391                 response = TRUE;
3392         }
3393
3394         if (done != MSGLOOP_IN_PROG && !response)
3395                 /* Clear the outgoing message buffer */
3396                 ahc->msgout_len = 0;
3397
3398         return (done);
3399 }
3400
3401 /*
3402  * Process a message reject message.
3403  */
3404 static int
3405 ahc_handle_msg_reject(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
3406 {
3407         /*
3408          * What we care about here is if we had an
3409          * outstanding SDTR or WDTR message for this
3410          * target.  If we did, this is a signal that
3411          * the target is refusing negotiation.
3412          */
3413         struct scb *scb;
3414         struct ahc_initiator_tinfo *tinfo;
3415         struct ahc_tmode_tstate *tstate;
3416         u_int scb_index;
3417         u_int last_msg;
3418         int   response = 0;
3419
3420         scb_index = ahc_inb(ahc, SCB_TAG);
3421         scb = ahc_lookup_scb(ahc, scb_index);
3422         tinfo = ahc_fetch_transinfo(ahc, devinfo->channel,
3423                                     devinfo->our_scsiid,
3424                                     devinfo->target, &tstate);
3425         /* Might be necessary */
3426         last_msg = ahc_inb(ahc, LAST_MSG);
3427
3428         if (ahc_sent_msg(ahc, AHCMSG_EXT, MSG_EXT_PPR, /*full*/FALSE)) {
3429                 /*
3430                  * Target does not support the PPR message.
3431                  * Attempt to negotiate SPI-2 style.
3432                  */
3433                 if (bootverbose) {
3434                         printf("(%s:%c:%d:%d): PPR Rejected. "
3435                                "Trying WDTR/SDTR\n",
3436                                ahc_name(ahc), devinfo->channel,
3437                                devinfo->target, devinfo->lun);
3438                 }
3439                 tinfo->goal.ppr_options = 0;
3440                 tinfo->curr.transport_version = 2;
3441                 tinfo->goal.transport_version = 2;
3442                 ahc->msgout_index = 0;
3443                 ahc->msgout_len = 0;
3444                 ahc_build_transfer_msg(ahc, devinfo);
3445                 ahc->msgout_index = 0;
3446                 response = 1;
3447         } else if (ahc_sent_msg(ahc, AHCMSG_EXT, MSG_EXT_WDTR, /*full*/FALSE)) {
3448
3449                 /* note 8bit xfers */
3450                 printf("(%s:%c:%d:%d): refuses WIDE negotiation.  Using "
3451                        "8bit transfers\n", ahc_name(ahc),
3452                        devinfo->channel, devinfo->target, devinfo->lun);
3453                 ahc_set_width(ahc, devinfo, MSG_EXT_WDTR_BUS_8_BIT,
3454                               AHC_TRANS_ACTIVE|AHC_TRANS_GOAL,
3455                               /*paused*/TRUE);
3456                 /*
3457                  * No need to clear the sync rate.  If the target
3458                  * did not accept the command, our syncrate is
3459                  * unaffected.  If the target started the negotiation,
3460                  * but rejected our response, we already cleared the
3461                  * sync rate before sending our WDTR.
3462                  */
3463                 if (tinfo->goal.offset != tinfo->curr.offset) {
3464
3465                         /* Start the sync negotiation */
3466                         ahc->msgout_index = 0;
3467                         ahc->msgout_len = 0;
3468                         ahc_build_transfer_msg(ahc, devinfo);
3469                         ahc->msgout_index = 0;
3470                         response = 1;
3471                 }
3472         } else if (ahc_sent_msg(ahc, AHCMSG_EXT, MSG_EXT_SDTR, /*full*/FALSE)) {
3473                 /* note asynch xfers and clear flag */
3474                 ahc_set_syncrate(ahc, devinfo, /*syncrate*/NULL, /*period*/0,
3475                                  /*offset*/0, /*ppr_options*/0,
3476                                  AHC_TRANS_ACTIVE|AHC_TRANS_GOAL,
3477                                  /*paused*/TRUE);
3478                 printf("(%s:%c:%d:%d): refuses synchronous negotiation. "
3479                        "Using asynchronous transfers\n",
3480                        ahc_name(ahc), devinfo->channel,
3481                        devinfo->target, devinfo->lun);
3482         } else if ((scb->hscb->control & MSG_SIMPLE_TASK) != 0) {
3483                 int tag_type;
3484                 int mask;
3485
3486                 tag_type = (scb->hscb->control & MSG_SIMPLE_TASK);
3487
3488                 if (tag_type == MSG_SIMPLE_TASK) {
3489                         printf("(%s:%c:%d:%d): refuses tagged commands.  "
3490                                "Performing non-tagged I/O\n", ahc_name(ahc),
3491                                devinfo->channel, devinfo->target, devinfo->lun);
3492                         ahc_set_tags(ahc, devinfo, AHC_QUEUE_NONE);
3493                         mask = ~0x23;
3494                 } else {
3495                         printf("(%s:%c:%d:%d): refuses %s tagged commands.  "
3496                                "Performing simple queue tagged I/O only\n",
3497                                ahc_name(ahc), devinfo->channel, devinfo->target,
3498                                devinfo->lun, tag_type == MSG_ORDERED_TASK
3499                                ? "ordered" : "head of queue");
3500                         ahc_set_tags(ahc, devinfo, AHC_QUEUE_BASIC);
3501                         mask = ~0x03;
3502                 }
3503
3504                 /*
3505                  * Resend the identify for this CCB as the target
3506                  * may believe that the selection is invalid otherwise.
3507                  */
3508                 ahc_outb(ahc, SCB_CONTROL,
3509                          ahc_inb(ahc, SCB_CONTROL) & mask);
3510                 scb->hscb->control &= mask;
3511                 ahc_set_transaction_tag(scb, /*enabled*/FALSE,
3512                                         /*type*/MSG_SIMPLE_TASK);
3513                 ahc_outb(ahc, MSG_OUT, MSG_IDENTIFYFLAG);
3514                 ahc_assert_atn(ahc);
3515
3516                 /*
3517                  * This transaction is now at the head of
3518                  * the untagged queue for this target.
3519                  */
3520                 if ((ahc->flags & AHC_SCB_BTT) == 0) {
3521                         struct scb_tailq *untagged_q;
3522
3523                         untagged_q =
3524                             &(ahc->untagged_queues[devinfo->target_offset]);
3525                         TAILQ_INSERT_HEAD(untagged_q, scb, links.tqe);
3526                         scb->flags |= SCB_UNTAGGEDQ;
3527                 }
3528                 ahc_busy_tcl(ahc, BUILD_TCL(scb->hscb->scsiid, devinfo->lun),
3529                              scb->hscb->tag);
3530
3531                 /*
3532                  * Requeue all tagged commands for this target
3533                  * currently in our posession so they can be
3534                  * converted to untagged commands.
3535                  */
3536                 ahc_search_qinfifo(ahc, SCB_GET_TARGET(ahc, scb),
3537                                    SCB_GET_CHANNEL(ahc, scb),
3538                                    SCB_GET_LUN(scb), /*tag*/SCB_LIST_NULL,
3539                                    ROLE_INITIATOR, CAM_REQUEUE_REQ,
3540                                    SEARCH_COMPLETE);
3541         } else {
3542                 /*
3543                  * Otherwise, we ignore it.
3544                  */
3545                 printf("%s:%c:%d: Message reject for %x -- ignored\n",
3546                        ahc_name(ahc), devinfo->channel, devinfo->target,
3547                        last_msg);
3548         }
3549         return (response);
3550 }
3551
3552 /*
3553  * Process an ingnore wide residue message.
3554  */
3555 static void
3556 ahc_handle_ign_wide_residue(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
3557 {
3558         u_int scb_index;
3559         struct scb *scb;
3560
3561         scb_index = ahc_inb(ahc, SCB_TAG);
3562         scb = ahc_lookup_scb(ahc, scb_index);
3563         /*
3564          * XXX Actually check data direction in the sequencer?
3565          * Perhaps add datadir to some spare bits in the hscb?
3566          */
3567         if ((ahc_inb(ahc, SEQ_FLAGS) & DPHASE) == 0
3568          || ahc_get_transfer_dir(scb) != CAM_DIR_IN) {
3569                 /*
3570                  * Ignore the message if we haven't
3571                  * seen an appropriate data phase yet.
3572                  */
3573         } else {
3574                 /*
3575                  * If the residual occurred on the last
3576                  * transfer and the transfer request was
3577                  * expected to end on an odd count, do
3578                  * nothing.  Otherwise, subtract a byte
3579                  * and update the residual count accordingly.
3580                  */
3581                 uint32_t sgptr;
3582
3583                 sgptr = ahc_inb(ahc, SCB_RESIDUAL_SGPTR);
3584                 if ((sgptr & SG_LIST_NULL) != 0
3585                  && (ahc_inb(ahc, SCB_LUN) & SCB_XFERLEN_ODD) != 0) {
3586                         /*
3587                          * If the residual occurred on the last
3588                          * transfer and the transfer request was
3589                          * expected to end on an odd count, do
3590                          * nothing.
3591                          */
3592                 } else {
3593                         struct ahc_dma_seg *sg;
3594                         uint32_t data_cnt;
3595                         uint32_t data_addr;
3596                         uint32_t sglen;
3597
3598                         /* Pull in all of the sgptr */
3599                         sgptr = ahc_inl(ahc, SCB_RESIDUAL_SGPTR);
3600                         data_cnt = ahc_inl(ahc, SCB_RESIDUAL_DATACNT);
3601
3602                         if ((sgptr & SG_LIST_NULL) != 0) {
3603                                 /*
3604                                  * The residual data count is not updated
3605                                  * for the command run to completion case.
3606                                  * Explicitly zero the count.
3607                                  */
3608                                 data_cnt &= ~AHC_SG_LEN_MASK;
3609                         }
3610
3611                         data_addr = ahc_inl(ahc, SHADDR);
3612
3613                         data_cnt += 1;
3614                         data_addr -= 1;
3615                         sgptr &= SG_PTR_MASK;
3616
3617                         sg = ahc_sg_bus_to_virt(scb, sgptr);
3618
3619                         /*
3620                          * The residual sg ptr points to the next S/G
3621                          * to load so we must go back one.
3622                          */
3623                         sg--;
3624                         sglen = ahc_le32toh(sg->len) & AHC_SG_LEN_MASK;
3625                         if (sg != scb->sg_list
3626                          && sglen < (data_cnt & AHC_SG_LEN_MASK)) {
3627
3628                                 sg--;
3629                                 sglen = ahc_le32toh(sg->len);
3630                                 /*
3631                                  * Preserve High Address and SG_LIST bits
3632                                  * while setting the count to 1.
3633                                  */
3634                                 data_cnt = 1 | (sglen & (~AHC_SG_LEN_MASK));
3635                                 data_addr = ahc_le32toh(sg->addr)
3636                                           + (sglen & AHC_SG_LEN_MASK) - 1;
3637
3638                                 /*
3639                                  * Increment sg so it points to the
3640                                  * "next" sg.
3641                                  */
3642                                 sg++;
3643                                 sgptr = ahc_sg_virt_to_bus(scb, sg);
3644                         }
3645                         ahc_outl(ahc, SCB_RESIDUAL_SGPTR, sgptr);
3646                         ahc_outl(ahc, SCB_RESIDUAL_DATACNT, data_cnt);
3647                         /*
3648                          * Toggle the "oddness" of the transfer length
3649                          * to handle this mid-transfer ignore wide
3650                          * residue.  This ensures that the oddness is
3651                          * correct for subsequent data transfers.
3652                          */
3653                         ahc_outb(ahc, SCB_LUN,
3654                                  ahc_inb(ahc, SCB_LUN) ^ SCB_XFERLEN_ODD);
3655                 }
3656         }
3657 }
3658
3659
3660 /*
3661  * Reinitialize the data pointers for the active transfer
3662  * based on its current residual.
3663  */
3664 static void
3665 ahc_reinitialize_dataptrs(struct ahc_softc *ahc)
3666 {
3667         struct   scb *scb;
3668         struct   ahc_dma_seg *sg;
3669         u_int    scb_index;
3670         uint32_t sgptr;
3671         uint32_t resid;
3672         uint32_t dataptr;
3673
3674         scb_index = ahc_inb(ahc, SCB_TAG);
3675         scb = ahc_lookup_scb(ahc, scb_index);
3676         sgptr = (ahc_inb(ahc, SCB_RESIDUAL_SGPTR + 3) << 24)
3677               | (ahc_inb(ahc, SCB_RESIDUAL_SGPTR + 2) << 16)
3678               | (ahc_inb(ahc, SCB_RESIDUAL_SGPTR + 1) << 8)
3679               | ahc_inb(ahc, SCB_RESIDUAL_SGPTR);
3680
3681         sgptr &= SG_PTR_MASK;
3682         sg = ahc_sg_bus_to_virt(scb, sgptr);
3683
3684         /* The residual sg_ptr always points to the next sg */
3685         sg--;
3686
3687         resid = (ahc_inb(ahc, SCB_RESIDUAL_DATACNT + 2) << 16)
3688               | (ahc_inb(ahc, SCB_RESIDUAL_DATACNT + 1) << 8)
3689               | ahc_inb(ahc, SCB_RESIDUAL_DATACNT);
3690
3691         dataptr = ahc_le32toh(sg->addr)
3692                 + (ahc_le32toh(sg->len) & AHC_SG_LEN_MASK)
3693                 - resid;
3694         if ((ahc->flags & AHC_39BIT_ADDRESSING) != 0) {
3695                 u_int dscommand1;
3696
3697                 dscommand1 = ahc_inb(ahc, DSCOMMAND1);
3698                 ahc_outb(ahc, DSCOMMAND1, dscommand1 | HADDLDSEL0);
3699                 ahc_outb(ahc, HADDR,
3700                          (ahc_le32toh(sg->len) >> 24) & SG_HIGH_ADDR_BITS);
3701                 ahc_outb(ahc, DSCOMMAND1, dscommand1);
3702         }
3703         ahc_outb(ahc, HADDR + 3, dataptr >> 24);
3704         ahc_outb(ahc, HADDR + 2, dataptr >> 16);
3705         ahc_outb(ahc, HADDR + 1, dataptr >> 8);
3706         ahc_outb(ahc, HADDR, dataptr);
3707         ahc_outb(ahc, HCNT + 2, resid >> 16);
3708         ahc_outb(ahc, HCNT + 1, resid >> 8);
3709         ahc_outb(ahc, HCNT, resid);
3710         if ((ahc->features & AHC_ULTRA2) == 0) {
3711                 ahc_outb(ahc, STCNT + 2, resid >> 16);
3712                 ahc_outb(ahc, STCNT + 1, resid >> 8);
3713                 ahc_outb(ahc, STCNT, resid);
3714         }
3715 }
3716
3717 /*
3718  * Handle the effects of issuing a bus device reset message.
3719  */
3720 static void
3721 ahc_handle_devreset(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
3722                     cam_status status, char *message, int verbose_level)
3723 {
3724 #ifdef AHC_TARGET_MODE
3725         struct ahc_tmode_tstate* tstate;
3726         u_int lun;
3727 #endif
3728         int found;
3729
3730         found = ahc_abort_scbs(ahc, devinfo->target, devinfo->channel,
3731                                CAM_LUN_WILDCARD, SCB_LIST_NULL, devinfo->role,
3732                                status);
3733
3734 #ifdef AHC_TARGET_MODE
3735         /*
3736          * Send an immediate notify ccb to all target mord peripheral
3737          * drivers affected by this action.
3738          */
3739         tstate = ahc->enabled_targets[devinfo->our_scsiid];
3740         if (tstate != NULL) {
3741                 for (lun = 0; lun < AHC_NUM_LUNS; lun++) {
3742                         struct ahc_tmode_lstate* lstate;
3743
3744                         lstate = tstate->enabled_luns[lun];
3745                         if (lstate == NULL)
3746                                 continue;
3747
3748                         ahc_queue_lstate_event(ahc, lstate, devinfo->our_scsiid,
3749                                                MSG_BUS_DEV_RESET, /*arg*/0);
3750                         ahc_send_lstate_events(ahc, lstate);
3751                 }
3752         }
3753 #endif
3754
3755         /*
3756          * Go back to async/narrow transfers and renegotiate.
3757          */
3758         ahc_set_width(ahc, devinfo, MSG_EXT_WDTR_BUS_8_BIT,
3759                       AHC_TRANS_CUR, /*paused*/TRUE);
3760         ahc_set_syncrate(ahc, devinfo, /*syncrate*/NULL,
3761                          /*period*/0, /*offset*/0, /*ppr_options*/0,
3762                          AHC_TRANS_CUR, /*paused*/TRUE);
3763         
3764         if (status != CAM_SEL_TIMEOUT)
3765                 ahc_send_async(ahc, devinfo->channel, devinfo->target,
3766                                CAM_LUN_WILDCARD, AC_SENT_BDR, NULL);
3767
3768         if (message != NULL
3769          && (verbose_level <= bootverbose))
3770                 printf("%s: %s on %c:%d. %d SCBs aborted\n", ahc_name(ahc),
3771                        message, devinfo->channel, devinfo->target, found);
3772 }
3773
3774 #ifdef AHC_TARGET_MODE
3775 static void
3776 ahc_setup_target_msgin(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
3777                        struct scb *scb)
3778 {
3779
3780         /*              
3781          * To facilitate adding multiple messages together,
3782          * each routine should increment the index and len
3783          * variables instead of setting them explicitly.
3784          */             
3785         ahc->msgout_index = 0;
3786         ahc->msgout_len = 0;
3787
3788         if (scb != NULL && (scb->flags & SCB_AUTO_NEGOTIATE) != 0)
3789                 ahc_build_transfer_msg(ahc, devinfo);
3790         else
3791                 panic("ahc_intr: AWAITING target message with no message");
3792
3793         ahc->msgout_index = 0;
3794         ahc->msg_type = MSG_TYPE_TARGET_MSGIN;
3795 }
3796 #endif
3797 /**************************** Initialization **********************************/
3798 /*
3799  * Allocate a controller structure for a new device
3800  * and perform initial initializion.
3801  */
3802 struct ahc_softc *
3803 ahc_alloc(void *platform_arg, char *name)
3804 {
3805         struct  ahc_softc *ahc;
3806         int     i;
3807
3808 #ifndef __FreeBSD__
3809         ahc = malloc(sizeof(*ahc), M_DEVBUF, M_NOWAIT);
3810         if (!ahc) {
3811                 printf("aic7xxx: cannot malloc softc!\n");
3812                 free(name, M_DEVBUF);
3813                 return NULL;
3814         }
3815 #else
3816         ahc = device_get_softc((device_t)platform_arg);
3817 #endif
3818         memset(ahc, 0, sizeof(*ahc));
3819         ahc->seep_config = malloc(sizeof(*ahc->seep_config),
3820                                   M_DEVBUF, M_NOWAIT);
3821         if (ahc->seep_config == NULL) {
3822 #ifndef __FreeBSD__
3823                 free(ahc, M_DEVBUF);
3824 #endif
3825                 free(name, M_DEVBUF);
3826                 return (NULL);
3827         }
3828         LIST_INIT(&ahc->pending_scbs);
3829         /* We don't know our unit number until the OSM sets it */
3830         ahc->name = name;
3831         ahc->unit = -1;
3832         ahc->description = NULL;
3833         ahc->channel = 'A';
3834         ahc->channel_b = 'B';
3835         ahc->chip = AHC_NONE;
3836         ahc->features = AHC_FENONE;
3837         ahc->bugs = AHC_BUGNONE;
3838         ahc->flags = AHC_FNONE;
3839         /*
3840          * Default to all error reporting enabled with the
3841          * sequencer operating at its fastest speed.
3842          * The bus attach code may modify this.
3843          */
3844         ahc->seqctl = FASTMODE;
3845
3846         for (i = 0; i < AHC_NUM_TARGETS; i++)
3847                 TAILQ_INIT(&ahc->untagged_queues[i]);
3848         if (ahc_platform_alloc(ahc, platform_arg) != 0) {
3849                 ahc_free(ahc);
3850                 ahc = NULL;
3851         }
3852         return (ahc);
3853 }
3854
3855 int
3856 ahc_softc_init(struct ahc_softc *ahc)
3857 {
3858
3859         /* The IRQMS bit is only valid on VL and EISA chips */
3860         if ((ahc->chip & AHC_PCI) == 0)
3861                 ahc->unpause = ahc_inb(ahc, HCNTRL) & IRQMS;
3862         else
3863                 ahc->unpause = 0;
3864         ahc->pause = ahc->unpause | PAUSE; 
3865         /* XXX The shared scb data stuff should be deprecated */
3866         if (ahc->scb_data == NULL) {
3867                 ahc->scb_data = malloc(sizeof(*ahc->scb_data),
3868                                        M_DEVBUF, M_NOWAIT);
3869                 if (ahc->scb_data == NULL)
3870                         return (ENOMEM);
3871                 memset(ahc->scb_data, 0, sizeof(*ahc->scb_data));
3872         }
3873
3874         return (0);
3875 }
3876
3877 void
3878 ahc_set_unit(struct ahc_softc *ahc, int unit)
3879 {
3880         ahc->unit = unit;
3881 }
3882
3883 void
3884 ahc_set_name(struct ahc_softc *ahc, char *name)
3885 {
3886         if (ahc->name != NULL)
3887                 free(ahc->name, M_DEVBUF);
3888         ahc->name = name;
3889 }
3890
3891 void
3892 ahc_free(struct ahc_softc *ahc)
3893 {
3894         int i;
3895
3896         switch (ahc->init_level) {
3897         default:
3898         case 5:
3899                 ahc_shutdown(ahc);
3900                 /* FALLTHROUGH */
3901         case 4:
3902                 ahc_dmamap_unload(ahc, ahc->shared_data_dmat,
3903                                   ahc->shared_data_dmamap);
3904                 /* FALLTHROUGH */
3905         case 3:
3906                 ahc_dmamem_free(ahc, ahc->shared_data_dmat, ahc->qoutfifo,
3907                                 ahc->shared_data_dmamap);
3908                 ahc_dmamap_destroy(ahc, ahc->shared_data_dmat,
3909                                    ahc->shared_data_dmamap);
3910                 /* FALLTHROUGH */
3911         case 2:
3912                 ahc_dma_tag_destroy(ahc, ahc->shared_data_dmat);
3913         case 1:
3914 #ifndef __linux__
3915                 ahc_dma_tag_destroy(ahc, ahc->buffer_dmat);
3916 #endif
3917                 break;
3918         case 0:
3919                 break;
3920         }
3921
3922 #ifndef __linux__
3923         ahc_dma_tag_destroy(ahc, ahc->parent_dmat);
3924 #endif
3925         ahc_platform_free(ahc);
3926         ahc_fini_scbdata(ahc);
3927         for (i = 0; i < AHC_NUM_TARGETS; i++) {
3928                 struct ahc_tmode_tstate *tstate;
3929
3930                 tstate = ahc->enabled_targets[i];
3931                 if (tstate != NULL) {
3932 #ifdef AHC_TARGET_MODE
3933                         int j;
3934
3935                         for (j = 0; j < AHC_NUM_LUNS; j++) {
3936                                 struct ahc_tmode_lstate *lstate;
3937
3938                                 lstate = tstate->enabled_luns[j];
3939                                 if (lstate != NULL) {
3940                                         xpt_free_path(lstate->path);
3941                                         free(lstate, M_DEVBUF);
3942                                 }
3943                         }
3944 #endif
3945                         free(tstate, M_DEVBUF);
3946                 }
3947         }
3948 #ifdef AHC_TARGET_MODE
3949         if (ahc->black_hole != NULL) {
3950                 xpt_free_path(ahc->black_hole->path);
3951                 free(ahc->black_hole, M_DEVBUF);
3952         }
3953 #endif
3954         if (ahc->name != NULL)
3955                 free(ahc->name, M_DEVBUF);
3956         if (ahc->seep_config != NULL)
3957                 free(ahc->seep_config, M_DEVBUF);
3958 #ifndef __FreeBSD__
3959         free(ahc, M_DEVBUF);
3960 #endif
3961         return;
3962 }
3963
3964 void
3965 ahc_shutdown(void *arg)
3966 {
3967         struct  ahc_softc *ahc;
3968         int     i;
3969
3970         ahc = (struct ahc_softc *)arg;
3971
3972         /* This will reset most registers to 0, but not all */
3973         ahc_reset(ahc, /*reinit*/FALSE);
3974         ahc_outb(ahc, SCSISEQ, 0);
3975         ahc_outb(ahc, SXFRCTL0, 0);
3976         ahc_outb(ahc, DSPCISTATUS, 0);
3977
3978         for (i = TARG_SCSIRATE; i < SCSICONF; i++)
3979                 ahc_outb(ahc, i, 0);
3980 }
3981
3982 /*
3983  * Reset the controller and record some information about it
3984  * that is only available just after a reset.  If "reinit" is
3985  * non-zero, this reset occured after initial configuration
3986  * and the caller requests that the chip be fully reinitialized
3987  * to a runable state.  Chip interrupts are *not* enabled after
3988  * a reinitialization.  The caller must enable interrupts via
3989  * ahc_intr_enable().
3990  */
3991 int
3992 ahc_reset(struct ahc_softc *ahc, int reinit)
3993 {
3994         u_int   sblkctl;
3995         u_int   sxfrctl1_a, sxfrctl1_b;
3996         int     error;
3997         int     wait;
3998         
3999         /*
4000          * Preserve the value of the SXFRCTL1 register for all channels.
4001          * It contains settings that affect termination and we don't want
4002          * to disturb the integrity of the bus.
4003          */
4004         ahc_pause(ahc);
4005         sxfrctl1_b = 0;
4006         if ((ahc->chip & AHC_CHIPID_MASK) == AHC_AIC7770) {
4007                 u_int sblkctl;
4008
4009                 /*
4010                  * Save channel B's settings in case this chip
4011                  * is setup for TWIN channel operation.
4012                  */
4013                 sblkctl = ahc_inb(ahc, SBLKCTL);
4014                 ahc_outb(ahc, SBLKCTL, sblkctl | SELBUSB);
4015                 sxfrctl1_b = ahc_inb(ahc, SXFRCTL1);
4016                 ahc_outb(ahc, SBLKCTL, sblkctl & ~SELBUSB);
4017         }
4018         sxfrctl1_a = ahc_inb(ahc, SXFRCTL1);
4019
4020         ahc_outb(ahc, HCNTRL, CHIPRST | ahc->pause);
4021
4022         /*
4023          * Ensure that the reset has finished.  We delay 1000us
4024          * prior to reading the register to make sure the chip
4025          * has sufficiently completed its reset to handle register
4026          * accesses.
4027          */
4028         wait = 1000;
4029         do {
4030                 ahc_delay(1000);
4031         } while (--wait && !(ahc_inb(ahc, HCNTRL) & CHIPRSTACK));
4032
4033         if (wait == 0) {
4034                 printf("%s: WARNING - Failed chip reset!  "
4035                        "Trying to initialize anyway.\n", ahc_name(ahc));
4036         }
4037         ahc_outb(ahc, HCNTRL, ahc->pause);
4038
4039         /* Determine channel configuration */
4040         sblkctl = ahc_inb(ahc, SBLKCTL) & (SELBUSB|SELWIDE);
4041         /* No Twin Channel PCI cards */
4042         if ((ahc->chip & AHC_PCI) != 0)
4043                 sblkctl &= ~SELBUSB;
4044         switch (sblkctl) {
4045         case 0:
4046                 /* Single Narrow Channel */
4047                 break;
4048         case 2:
4049                 /* Wide Channel */
4050                 ahc->features |= AHC_WIDE;
4051                 break;
4052         case 8:
4053                 /* Twin Channel */
4054                 ahc->features |= AHC_TWIN;
4055                 break;
4056         default:
4057                 printf(" Unsupported adapter type.  Ignoring\n");
4058                 return(-1);
4059         }
4060
4061         /*
4062          * Reload sxfrctl1.
4063          *
4064          * We must always initialize STPWEN to 1 before we
4065          * restore the saved values.  STPWEN is initialized
4066          * to a tri-state condition which can only be cleared
4067          * by turning it on.
4068          */
4069         if ((ahc->features & AHC_TWIN) != 0) {
4070                 u_int sblkctl;
4071
4072                 sblkctl = ahc_inb(ahc, SBLKCTL);
4073                 ahc_outb(ahc, SBLKCTL, sblkctl | SELBUSB);
4074                 ahc_outb(ahc, SXFRCTL1, sxfrctl1_b);
4075                 ahc_outb(ahc, SBLKCTL, sblkctl & ~SELBUSB);
4076         }
4077         ahc_outb(ahc, SXFRCTL1, sxfrctl1_a);
4078
4079         error = 0;
4080         if (reinit != 0)
4081                 /*
4082                  * If a recovery action has forced a chip reset,
4083                  * re-initialize the chip to our liking.
4084                  */
4085                 error = ahc->bus_chip_init(ahc);
4086 #ifdef AHC_DUMP_SEQ
4087         else 
4088                 ahc_dumpseq(ahc);
4089 #endif
4090
4091         return (error);
4092 }
4093
4094 /*
4095  * Determine the number of SCBs available on the controller
4096  */
4097 int
4098 ahc_probe_scbs(struct ahc_softc *ahc) {
4099         int i;
4100
4101         for (i = 0; i < AHC_SCB_MAX; i++) {
4102
4103                 ahc_outb(ahc, SCBPTR, i);
4104                 ahc_outb(ahc, SCB_BASE, i);
4105                 if (ahc_inb(ahc, SCB_BASE) != i)
4106                         break;
4107                 ahc_outb(ahc, SCBPTR, 0);
4108                 if (ahc_inb(ahc, SCB_BASE) != 0)
4109                         break;
4110         }
4111         return (i);
4112 }
4113
4114 static void
4115 ahc_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nseg, int error) 
4116 {
4117         dma_addr_t *baddr;
4118
4119         baddr = (dma_addr_t *)arg;
4120         *baddr = segs->ds_addr;
4121 }
4122
4123 static void
4124 ahc_build_free_scb_list(struct ahc_softc *ahc)
4125 {
4126         int scbsize;
4127         int i;
4128
4129         scbsize = 32;
4130         if ((ahc->flags & AHC_LSCBS_ENABLED) != 0)
4131                 scbsize = 64;
4132
4133         for (i = 0; i < ahc->scb_data->maxhscbs; i++) {
4134                 int j;
4135
4136                 ahc_outb(ahc, SCBPTR, i);
4137
4138                 /*
4139                  * Touch all SCB bytes to avoid parity errors
4140                  * should one of our debugging routines read
4141                  * an otherwise uninitiatlized byte.
4142                  */
4143                 for (j = 0; j < scbsize; j++)
4144                         ahc_outb(ahc, SCB_BASE+j, 0xFF);
4145
4146                 /* Clear the control byte. */
4147                 ahc_outb(ahc, SCB_CONTROL, 0);
4148
4149                 /* Set the next pointer */
4150                 if ((ahc->flags & AHC_PAGESCBS) != 0)
4151                         ahc_outb(ahc, SCB_NEXT, i+1);
4152                 else 
4153                         ahc_outb(ahc, SCB_NEXT, SCB_LIST_NULL);
4154
4155                 /* Make the tag number, SCSIID, and lun invalid */
4156                 ahc_outb(ahc, SCB_TAG, SCB_LIST_NULL);
4157                 ahc_outb(ahc, SCB_SCSIID, 0xFF);
4158                 ahc_outb(ahc, SCB_LUN, 0xFF);
4159         }
4160
4161         if ((ahc->flags & AHC_PAGESCBS) != 0) {
4162                 /* SCB 0 heads the free list. */
4163                 ahc_outb(ahc, FREE_SCBH, 0);
4164         } else {
4165                 /* No free list. */
4166                 ahc_outb(ahc, FREE_SCBH, SCB_LIST_NULL);
4167         }
4168
4169         /* Make sure that the last SCB terminates the free list */
4170         ahc_outb(ahc, SCBPTR, i-1);
4171         ahc_outb(ahc, SCB_NEXT, SCB_LIST_NULL);
4172 }
4173
4174 static int
4175 ahc_init_scbdata(struct ahc_softc *ahc)
4176 {
4177         struct scb_data *scb_data;
4178
4179         scb_data = ahc->scb_data;
4180         SLIST_INIT(&scb_data->free_scbs);
4181         SLIST_INIT(&scb_data->sg_maps);
4182
4183         /* Allocate SCB resources */
4184         scb_data->scbarray =
4185             (struct scb *)malloc(sizeof(struct scb) * AHC_SCB_MAX_ALLOC,
4186                                  M_DEVBUF, M_NOWAIT);
4187         if (scb_data->scbarray == NULL)
4188                 return (ENOMEM);
4189         memset(scb_data->scbarray, 0, sizeof(struct scb) * AHC_SCB_MAX_ALLOC);
4190
4191         /* Determine the number of hardware SCBs and initialize them */
4192
4193         scb_data->maxhscbs = ahc_probe_scbs(ahc);
4194         if (ahc->scb_data->maxhscbs == 0) {
4195                 printf("%s: No SCB space found\n", ahc_name(ahc));
4196                 return (ENXIO);
4197         }
4198
4199         /*
4200          * Create our DMA tags.  These tags define the kinds of device
4201          * accessible memory allocations and memory mappings we will
4202          * need to perform during normal operation.
4203          *
4204          * Unless we need to further restrict the allocation, we rely
4205          * on the restrictions of the parent dmat, hence the common
4206          * use of MAXADDR and MAXSIZE.
4207          */
4208
4209         /* DMA tag for our hardware scb structures */
4210         if (ahc_dma_tag_create(ahc, ahc->parent_dmat, /*alignment*/1,
4211                                /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
4212                                /*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
4213                                /*highaddr*/BUS_SPACE_MAXADDR,
4214                                /*filter*/NULL, /*filterarg*/NULL,
4215                                AHC_SCB_MAX_ALLOC * sizeof(struct hardware_scb),
4216                                /*nsegments*/1,
4217                                /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
4218                                /*flags*/0, &scb_data->hscb_dmat) != 0) {
4219                 goto error_exit;
4220         }
4221
4222         scb_data->init_level++;
4223
4224         /* Allocation for our hscbs */
4225         if (ahc_dmamem_alloc(ahc, scb_data->hscb_dmat,
4226                              (void **)&scb_data->hscbs,
4227                              BUS_DMA_NOWAIT, &scb_data->hscb_dmamap) != 0) {
4228                 goto error_exit;
4229         }
4230
4231         scb_data->init_level++;
4232
4233         /* And permanently map them */
4234         ahc_dmamap_load(ahc, scb_data->hscb_dmat, scb_data->hscb_dmamap,
4235                         scb_data->hscbs,
4236                         AHC_SCB_MAX_ALLOC * sizeof(struct hardware_scb),
4237                         ahc_dmamap_cb, &scb_data->hscb_busaddr, /*flags*/0);
4238
4239         scb_data->init_level++;
4240
4241         /* DMA tag for our sense buffers */
4242         if (ahc_dma_tag_create(ahc, ahc->parent_dmat, /*alignment*/1,
4243                                /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
4244                                /*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
4245                                /*highaddr*/BUS_SPACE_MAXADDR,
4246                                /*filter*/NULL, /*filterarg*/NULL,
4247                                AHC_SCB_MAX_ALLOC * sizeof(struct scsi_sense_data),
4248                                /*nsegments*/1,
4249                                /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
4250                                /*flags*/0, &scb_data->sense_dmat) != 0) {
4251                 goto error_exit;
4252         }
4253
4254         scb_data->init_level++;
4255
4256         /* Allocate them */
4257         if (ahc_dmamem_alloc(ahc, scb_data->sense_dmat,
4258                              (void **)&scb_data->sense,
4259                              BUS_DMA_NOWAIT, &scb_data->sense_dmamap) != 0) {
4260                 goto error_exit;
4261         }
4262
4263         scb_data->init_level++;
4264
4265         /* And permanently map them */
4266         ahc_dmamap_load(ahc, scb_data->sense_dmat, scb_data->sense_dmamap,
4267                         scb_data->sense,
4268                         AHC_SCB_MAX_ALLOC * sizeof(struct scsi_sense_data),
4269                         ahc_dmamap_cb, &scb_data->sense_busaddr, /*flags*/0);
4270
4271         scb_data->init_level++;
4272
4273         /* DMA tag for our S/G structures.  We allocate in page sized chunks */
4274         if (ahc_dma_tag_create(ahc, ahc->parent_dmat, /*alignment*/8,
4275                                /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
4276                                /*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
4277                                /*highaddr*/BUS_SPACE_MAXADDR,
4278                                /*filter*/NULL, /*filterarg*/NULL,
4279                                PAGE_SIZE, /*nsegments*/1,
4280                                /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
4281                                /*flags*/0, &scb_data->sg_dmat) != 0) {
4282                 goto error_exit;
4283         }
4284
4285         scb_data->init_level++;
4286
4287         /* Perform initial CCB allocation */
4288         memset(scb_data->hscbs, 0,
4289                AHC_SCB_MAX_ALLOC * sizeof(struct hardware_scb));
4290         ahc_alloc_scbs(ahc);
4291
4292         if (scb_data->numscbs == 0) {
4293                 printf("%s: ahc_init_scbdata - "
4294                        "Unable to allocate initial scbs\n",
4295                        ahc_name(ahc));
4296                 goto error_exit;
4297         }
4298
4299         /*
4300          * Reserve the next queued SCB.
4301          */
4302         ahc->next_queued_scb = ahc_get_scb(ahc);
4303
4304         /*
4305          * Note that we were successfull
4306          */
4307         return (0); 
4308
4309 error_exit:
4310
4311         return (ENOMEM);
4312 }
4313
4314 static void
4315 ahc_fini_scbdata(struct ahc_softc *ahc)
4316 {
4317         struct scb_data *scb_data;
4318
4319         scb_data = ahc->scb_data;
4320         if (scb_data == NULL)
4321                 return;
4322
4323         switch (scb_data->init_level) {
4324         default:
4325         case 7:
4326         {
4327                 struct sg_map_node *sg_map;
4328
4329                 while ((sg_map = SLIST_FIRST(&scb_data->sg_maps))!= NULL) {
4330                         SLIST_REMOVE_HEAD(&scb_data->sg_maps, links);
4331                         ahc_dmamap_unload(ahc, scb_data->sg_dmat,
4332                                           sg_map->sg_dmamap);
4333                         ahc_dmamem_free(ahc, scb_data->sg_dmat,
4334                                         sg_map->sg_vaddr,
4335                                         sg_map->sg_dmamap);
4336                         free(sg_map, M_DEVBUF);
4337                 }
4338                 ahc_dma_tag_destroy(ahc, scb_data->sg_dmat);
4339         }
4340         case 6:
4341                 ahc_dmamap_unload(ahc, scb_data->sense_dmat,
4342                                   scb_data->sense_dmamap);
4343         case 5:
4344                 ahc_dmamem_free(ahc, scb_data->sense_dmat, scb_data->sense,
4345                                 scb_data->sense_dmamap);
4346                 ahc_dmamap_destroy(ahc, scb_data->sense_dmat,
4347                                    scb_data->sense_dmamap);
4348         case 4:
4349                 ahc_dma_tag_destroy(ahc, scb_data->sense_dmat);
4350         case 3:
4351                 ahc_dmamap_unload(ahc, scb_data->hscb_dmat,
4352                                   scb_data->hscb_dmamap);
4353         case 2:
4354                 ahc_dmamem_free(ahc, scb_data->hscb_dmat, scb_data->hscbs,
4355                                 scb_data->hscb_dmamap);
4356                 ahc_dmamap_destroy(ahc, scb_data->hscb_dmat,
4357                                    scb_data->hscb_dmamap);
4358         case 1:
4359                 ahc_dma_tag_destroy(ahc, scb_data->hscb_dmat);
4360                 break;
4361         case 0:
4362                 break;
4363         }
4364         if (scb_data->scbarray != NULL)
4365                 free(scb_data->scbarray, M_DEVBUF);
4366 }
4367
4368 void
4369 ahc_alloc_scbs(struct ahc_softc *ahc)
4370 {
4371         struct scb_data *scb_data;
4372         struct scb *next_scb;
4373         struct sg_map_node *sg_map;
4374         dma_addr_t physaddr;
4375         struct ahc_dma_seg *segs;
4376         int newcount;
4377         int i;
4378
4379         scb_data = ahc->scb_data;
4380         if (scb_data->numscbs >= AHC_SCB_MAX_ALLOC)
4381                 /* Can't allocate any more */
4382                 return;
4383
4384         next_scb = &scb_data->scbarray[scb_data->numscbs];
4385
4386         sg_map = malloc(sizeof(*sg_map), M_DEVBUF, M_NOWAIT);
4387
4388         if (sg_map == NULL)
4389                 return;
4390
4391         /* Allocate S/G space for the next batch of SCBS */
4392         if (ahc_dmamem_alloc(ahc, scb_data->sg_dmat,
4393                              (void **)&sg_map->sg_vaddr,
4394                              BUS_DMA_NOWAIT, &sg_map->sg_dmamap) != 0) {
4395                 free(sg_map, M_DEVBUF);
4396                 return;
4397         }
4398
4399         SLIST_INSERT_HEAD(&scb_data->sg_maps, sg_map, links);
4400
4401         ahc_dmamap_load(ahc, scb_data->sg_dmat, sg_map->sg_dmamap,
4402                         sg_map->sg_vaddr, PAGE_SIZE, ahc_dmamap_cb,
4403                         &sg_map->sg_physaddr, /*flags*/0);
4404
4405         segs = sg_map->sg_vaddr;
4406         physaddr = sg_map->sg_physaddr;
4407
4408         newcount = (PAGE_SIZE / (AHC_NSEG * sizeof(struct ahc_dma_seg)));
4409         newcount = MIN(newcount, (AHC_SCB_MAX_ALLOC - scb_data->numscbs));
4410         for (i = 0; i < newcount; i++) {
4411                 struct scb_platform_data *pdata;
4412 #ifndef __linux__
4413                 int error;
4414 #endif
4415                 pdata = (struct scb_platform_data *)malloc(sizeof(*pdata),
4416                                                            M_DEVBUF, M_NOWAIT);
4417                 if (pdata == NULL)
4418                         break;
4419                 next_scb->platform_data = pdata;
4420                 next_scb->sg_map = sg_map;
4421                 next_scb->sg_list = segs;
4422                 /*
4423                  * The sequencer always starts with the second entry.
4424                  * The first entry is embedded in the scb.
4425                  */
4426                 next_scb->sg_list_phys = physaddr + sizeof(struct ahc_dma_seg);
4427                 next_scb->ahc_softc = ahc;
4428                 next_scb->flags = SCB_FREE;
4429 #ifndef __linux__
4430                 error = ahc_dmamap_create(ahc, ahc->buffer_dmat, /*flags*/0,
4431                                           &next_scb->dmamap);
4432                 if (error != 0)
4433                         break;
4434 #endif
4435                 next_scb->hscb = &scb_data->hscbs[scb_data->numscbs];
4436                 next_scb->hscb->tag = ahc->scb_data->numscbs;
4437                 SLIST_INSERT_HEAD(&ahc->scb_data->free_scbs,
4438                                   next_scb, links.sle);
4439                 segs += AHC_NSEG;
4440                 physaddr += (AHC_NSEG * sizeof(struct ahc_dma_seg));
4441                 next_scb++;
4442                 ahc->scb_data->numscbs++;
4443         }
4444 }
4445
4446 void
4447 ahc_controller_info(struct ahc_softc *ahc, char *buf)
4448 {
4449         int len;
4450
4451         len = sprintf(buf, "%s: ", ahc_chip_names[ahc->chip & AHC_CHIPID_MASK]);
4452         buf += len;
4453         if ((ahc->features & AHC_TWIN) != 0)
4454                 len = sprintf(buf, "Twin Channel, A SCSI Id=%d, "
4455                               "B SCSI Id=%d, primary %c, ",
4456                               ahc->our_id, ahc->our_id_b,
4457                               (ahc->flags & AHC_PRIMARY_CHANNEL) + 'A');
4458         else {
4459                 const char *speed;
4460                 const char *type;
4461
4462                 speed = "";
4463                 if ((ahc->features & AHC_ULTRA) != 0) {
4464                         speed = "Ultra ";
4465                 } else if ((ahc->features & AHC_DT) != 0) {
4466                         speed = "Ultra160 ";
4467                 } else if ((ahc->features & AHC_ULTRA2) != 0) {
4468                         speed = "Ultra2 ";
4469                 }
4470                 if ((ahc->features & AHC_WIDE) != 0) {
4471                         type = "Wide";
4472                 } else {
4473                         type = "Single";
4474                 }
4475                 len = sprintf(buf, "%s%s Channel %c, SCSI Id=%d, ",
4476                               speed, type, ahc->channel, ahc->our_id);
4477         }
4478         buf += len;
4479
4480         if ((ahc->flags & AHC_PAGESCBS) != 0)
4481                 sprintf(buf, "%d/%d SCBs",
4482                         ahc->scb_data->maxhscbs, AHC_MAX_QUEUE);
4483         else
4484                 sprintf(buf, "%d SCBs", ahc->scb_data->maxhscbs);
4485 }
4486
4487 int
4488 ahc_chip_init(struct ahc_softc *ahc)
4489 {
4490         int      term;
4491         int      error;
4492         u_int    i;
4493         u_int    scsi_conf;
4494         u_int    scsiseq_template;
4495         uint32_t physaddr;
4496
4497         ahc_outb(ahc, SEQ_FLAGS, 0);
4498         ahc_outb(ahc, SEQ_FLAGS2, 0);
4499
4500         /* Set the SCSI Id, SXFRCTL0, SXFRCTL1, and SIMODE1, for both channels*/
4501         if (ahc->features & AHC_TWIN) {
4502
4503                 /*
4504                  * Setup Channel B first.
4505                  */
4506                 ahc_outb(ahc, SBLKCTL, ahc_inb(ahc, SBLKCTL) | SELBUSB);
4507                 term = (ahc->flags & AHC_TERM_ENB_B) != 0 ? STPWEN : 0;
4508                 ahc_outb(ahc, SCSIID, ahc->our_id_b);
4509                 scsi_conf = ahc_inb(ahc, SCSICONF + 1);
4510                 ahc_outb(ahc, SXFRCTL1, (scsi_conf & (ENSPCHK|STIMESEL))
4511                                         |term|ahc->seltime_b|ENSTIMER|ACTNEGEN);
4512                 if ((ahc->features & AHC_ULTRA2) != 0)
4513                         ahc_outb(ahc, SIMODE0, ahc_inb(ahc, SIMODE0)|ENIOERR);
4514                 ahc_outb(ahc, SIMODE1, ENSELTIMO|ENSCSIRST|ENSCSIPERR);
4515                 ahc_outb(ahc, SXFRCTL0, DFON|SPIOEN);
4516
4517                 /* Select Channel A */
4518                 ahc_outb(ahc, SBLKCTL, ahc_inb(ahc, SBLKCTL) & ~SELBUSB);
4519         }
4520         term = (ahc->flags & AHC_TERM_ENB_A) != 0 ? STPWEN : 0;
4521         if ((ahc->features & AHC_ULTRA2) != 0)
4522                 ahc_outb(ahc, SCSIID_ULTRA2, ahc->our_id);
4523         else
4524                 ahc_outb(ahc, SCSIID, ahc->our_id);
4525         scsi_conf = ahc_inb(ahc, SCSICONF);
4526         ahc_outb(ahc, SXFRCTL1, (scsi_conf & (ENSPCHK|STIMESEL))
4527                                 |term|ahc->seltime
4528                                 |ENSTIMER|ACTNEGEN);
4529         if ((ahc->features & AHC_ULTRA2) != 0)
4530                 ahc_outb(ahc, SIMODE0, ahc_inb(ahc, SIMODE0)|ENIOERR);
4531         ahc_outb(ahc, SIMODE1, ENSELTIMO|ENSCSIRST|ENSCSIPERR);
4532         ahc_outb(ahc, SXFRCTL0, DFON|SPIOEN);
4533
4534         /* There are no untagged SCBs active yet. */
4535         for (i = 0; i < 16; i++) {
4536                 ahc_unbusy_tcl(ahc, BUILD_TCL(i << 4, 0));
4537                 if ((ahc->flags & AHC_SCB_BTT) != 0) {
4538                         int lun;
4539
4540                         /*
4541                          * The SCB based BTT allows an entry per
4542                          * target and lun pair.
4543                          */
4544                         for (lun = 1; lun < AHC_NUM_LUNS; lun++)
4545                                 ahc_unbusy_tcl(ahc, BUILD_TCL(i << 4, lun));
4546                 }
4547         }
4548
4549         /* All of our queues are empty */
4550         for (i = 0; i < 256; i++)
4551                 ahc->qoutfifo[i] = SCB_LIST_NULL;
4552         ahc_sync_qoutfifo(ahc, BUS_DMASYNC_PREREAD);
4553
4554         for (i = 0; i < 256; i++)
4555                 ahc->qinfifo[i] = SCB_LIST_NULL;
4556
4557         if ((ahc->features & AHC_MULTI_TID) != 0) {
4558                 ahc_outb(ahc, TARGID, 0);
4559                 ahc_outb(ahc, TARGID + 1, 0);
4560         }
4561
4562         /*
4563          * Tell the sequencer where it can find our arrays in memory.
4564          */
4565         physaddr = ahc->scb_data->hscb_busaddr;
4566         ahc_outb(ahc, HSCB_ADDR, physaddr & 0xFF);
4567         ahc_outb(ahc, HSCB_ADDR + 1, (physaddr >> 8) & 0xFF);
4568         ahc_outb(ahc, HSCB_ADDR + 2, (physaddr >> 16) & 0xFF);
4569         ahc_outb(ahc, HSCB_ADDR + 3, (physaddr >> 24) & 0xFF);
4570
4571         physaddr = ahc->shared_data_busaddr;
4572         ahc_outb(ahc, SHARED_DATA_ADDR, physaddr & 0xFF);
4573         ahc_outb(ahc, SHARED_DATA_ADDR + 1, (physaddr >> 8) & 0xFF);
4574         ahc_outb(ahc, SHARED_DATA_ADDR + 2, (physaddr >> 16) & 0xFF);
4575         ahc_outb(ahc, SHARED_DATA_ADDR + 3, (physaddr >> 24) & 0xFF);
4576
4577         /*
4578          * Initialize the group code to command length table.
4579          * This overrides the values in TARG_SCSIRATE, so only
4580          * setup the table after we have processed that information.
4581          */
4582         ahc_outb(ahc, CMDSIZE_TABLE, 5);
4583         ahc_outb(ahc, CMDSIZE_TABLE + 1, 9);
4584         ahc_outb(ahc, CMDSIZE_TABLE + 2, 9);
4585         ahc_outb(ahc, CMDSIZE_TABLE + 3, 0);
4586         ahc_outb(ahc, CMDSIZE_TABLE + 4, 15);
4587         ahc_outb(ahc, CMDSIZE_TABLE + 5, 11);
4588         ahc_outb(ahc, CMDSIZE_TABLE + 6, 0);
4589         ahc_outb(ahc, CMDSIZE_TABLE + 7, 0);
4590                 
4591         if ((ahc->features & AHC_HS_MAILBOX) != 0)
4592                 ahc_outb(ahc, HS_MAILBOX, 0);
4593
4594         /* Tell the sequencer of our initial queue positions */
4595         if ((ahc->features & AHC_TARGETMODE) != 0) {
4596                 ahc->tqinfifonext = 1;
4597                 ahc_outb(ahc, KERNEL_TQINPOS, ahc->tqinfifonext - 1);
4598                 ahc_outb(ahc, TQINPOS, ahc->tqinfifonext);
4599         }
4600         ahc->qinfifonext = 0;
4601         ahc->qoutfifonext = 0;
4602         if ((ahc->features & AHC_QUEUE_REGS) != 0) {
4603                 ahc_outb(ahc, QOFF_CTLSTA, SCB_QSIZE_256);
4604                 ahc_outb(ahc, HNSCB_QOFF, ahc->qinfifonext);
4605                 ahc_outb(ahc, SNSCB_QOFF, ahc->qinfifonext);
4606                 ahc_outb(ahc, SDSCB_QOFF, 0);
4607         } else {
4608                 ahc_outb(ahc, KERNEL_QINPOS, ahc->qinfifonext);
4609                 ahc_outb(ahc, QINPOS, ahc->qinfifonext);
4610                 ahc_outb(ahc, QOUTPOS, ahc->qoutfifonext);
4611         }
4612
4613         /* We don't have any waiting selections */
4614         ahc_outb(ahc, WAITING_SCBH, SCB_LIST_NULL);
4615
4616         /* Our disconnection list is empty too */
4617         ahc_outb(ahc, DISCONNECTED_SCBH, SCB_LIST_NULL);
4618
4619         /* Message out buffer starts empty */
4620         ahc_outb(ahc, MSG_OUT, MSG_NOOP);
4621
4622         /*
4623          * Setup the allowed SCSI Sequences based on operational mode.
4624          * If we are a target, we'll enalbe select in operations once
4625          * we've had a lun enabled.
4626          */
4627         scsiseq_template = ENSELO|ENAUTOATNO|ENAUTOATNP;
4628         if ((ahc->flags & AHC_INITIATORROLE) != 0)
4629                 scsiseq_template |= ENRSELI;
4630         ahc_outb(ahc, SCSISEQ_TEMPLATE, scsiseq_template);
4631
4632         /* Initialize our list of free SCBs. */
4633         ahc_build_free_scb_list(ahc);
4634
4635         /*
4636          * Tell the sequencer which SCB will be the next one it receives.
4637          */
4638         ahc_outb(ahc, NEXT_QUEUED_SCB, ahc->next_queued_scb->hscb->tag);
4639
4640         /*
4641          * Load the Sequencer program and Enable the adapter
4642          * in "fast" mode.
4643          */
4644         if (bootverbose)
4645                 printf("%s: Downloading Sequencer Program...",
4646                        ahc_name(ahc));
4647
4648         error = ahc_loadseq(ahc);
4649         if (error != 0)
4650                 return (error);
4651
4652         if ((ahc->features & AHC_ULTRA2) != 0) {
4653                 int wait;
4654
4655                 /*
4656                  * Wait for up to 500ms for our transceivers
4657                  * to settle.  If the adapter does not have
4658                  * a cable attached, the transceivers may
4659                  * never settle, so don't complain if we
4660                  * fail here.
4661                  */
4662                 for (wait = 5000;
4663                      (ahc_inb(ahc, SBLKCTL) & (ENAB40|ENAB20)) == 0 && wait;
4664                      wait--)
4665                         ahc_delay(100);
4666         }
4667         ahc_restart(ahc);
4668         return (0);
4669 }
4670
4671 /*
4672  * Start the board, ready for normal operation
4673  */
4674 int
4675 ahc_init(struct ahc_softc *ahc)
4676 {
4677         int      max_targ;
4678         u_int    i;
4679         u_int    scsi_conf;
4680         u_int    ultraenb;
4681         u_int    discenable;
4682         u_int    tagenable;
4683         size_t   driver_data_size;
4684
4685 #ifdef AHC_DEBUG
4686         if ((ahc_debug & AHC_DEBUG_SEQUENCER) != 0)
4687                 ahc->flags |= AHC_SEQUENCER_DEBUG;
4688 #endif
4689
4690 #ifdef AHC_PRINT_SRAM
4691         printf("Scratch Ram:");
4692         for (i = 0x20; i < 0x5f; i++) {
4693                 if (((i % 8) == 0) && (i != 0)) {
4694                         printf ("\n              ");
4695                 }
4696                 printf (" 0x%x", ahc_inb(ahc, i));
4697         }
4698         if ((ahc->features & AHC_MORE_SRAM) != 0) {
4699                 for (i = 0x70; i < 0x7f; i++) {
4700                         if (((i % 8) == 0) && (i != 0)) {
4701                                 printf ("\n              ");
4702                         }
4703                         printf (" 0x%x", ahc_inb(ahc, i));
4704                 }
4705         }
4706         printf ("\n");
4707         /*
4708          * Reading uninitialized scratch ram may
4709          * generate parity errors.
4710          */
4711         ahc_outb(ahc, CLRINT, CLRPARERR);
4712         ahc_outb(ahc, CLRINT, CLRBRKADRINT);
4713 #endif
4714         max_targ = 15;
4715
4716         /*
4717          * Assume we have a board at this stage and it has been reset.
4718          */
4719         if ((ahc->flags & AHC_USEDEFAULTS) != 0)
4720                 ahc->our_id = ahc->our_id_b = 7;
4721         
4722         /*
4723          * Default to allowing initiator operations.
4724          */
4725         ahc->flags |= AHC_INITIATORROLE;
4726
4727         /*
4728          * Only allow target mode features if this unit has them enabled.
4729          */
4730         if ((AHC_TMODE_ENABLE & (0x1 << ahc->unit)) == 0)
4731                 ahc->features &= ~AHC_TARGETMODE;
4732
4733 #ifndef __linux__
4734         /* DMA tag for mapping buffers into device visible space. */
4735         if (ahc_dma_tag_create(ahc, ahc->parent_dmat, /*alignment*/1,
4736                                /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
4737                                /*lowaddr*/ahc->flags & AHC_39BIT_ADDRESSING
4738                                         ? (dma_addr_t)0x7FFFFFFFFFULL
4739                                         : BUS_SPACE_MAXADDR_32BIT,
4740                                /*highaddr*/BUS_SPACE_MAXADDR,
4741                                /*filter*/NULL, /*filterarg*/NULL,
4742                                /*maxsize*/(AHC_NSEG - 1) * PAGE_SIZE,
4743                                /*nsegments*/AHC_NSEG,
4744                                /*maxsegsz*/AHC_MAXTRANSFER_SIZE,
4745                                /*flags*/BUS_DMA_ALLOCNOW,
4746                                &ahc->buffer_dmat) != 0) {
4747                 return (ENOMEM);
4748         }
4749 #endif
4750
4751         ahc->init_level++;
4752
4753         /*
4754          * DMA tag for our command fifos and other data in system memory
4755          * the card's sequencer must be able to access.  For initiator
4756          * roles, we need to allocate space for the qinfifo and qoutfifo.
4757          * The qinfifo and qoutfifo are composed of 256 1 byte elements. 
4758          * When providing for the target mode role, we must additionally
4759          * provide space for the incoming target command fifo and an extra
4760          * byte to deal with a dma bug in some chip versions.
4761          */
4762         driver_data_size = 2 * 256 * sizeof(uint8_t);
4763         if ((ahc->features & AHC_TARGETMODE) != 0)
4764                 driver_data_size += AHC_TMODE_CMDS * sizeof(struct target_cmd)
4765                                  + /*DMA WideOdd Bug Buffer*/1;
4766         if (ahc_dma_tag_create(ahc, ahc->parent_dmat, /*alignment*/1,
4767                                /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
4768                                /*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
4769                                /*highaddr*/BUS_SPACE_MAXADDR,
4770                                /*filter*/NULL, /*filterarg*/NULL,
4771                                driver_data_size,
4772                                /*nsegments*/1,
4773                                /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
4774                                /*flags*/0, &ahc->shared_data_dmat) != 0) {
4775                 return (ENOMEM);
4776         }
4777
4778         ahc->init_level++;
4779
4780         /* Allocation of driver data */
4781         if (ahc_dmamem_alloc(ahc, ahc->shared_data_dmat,
4782                              (void **)&ahc->qoutfifo,
4783                              BUS_DMA_NOWAIT, &ahc->shared_data_dmamap) != 0) {
4784                 return (ENOMEM);
4785         }
4786
4787         ahc->init_level++;
4788
4789         /* And permanently map it in */
4790         ahc_dmamap_load(ahc, ahc->shared_data_dmat, ahc->shared_data_dmamap,
4791                         ahc->qoutfifo, driver_data_size, ahc_dmamap_cb,
4792                         &ahc->shared_data_busaddr, /*flags*/0);
4793
4794         if ((ahc->features & AHC_TARGETMODE) != 0) {
4795                 ahc->targetcmds = (struct target_cmd *)ahc->qoutfifo;
4796                 ahc->qoutfifo = (uint8_t *)&ahc->targetcmds[AHC_TMODE_CMDS];
4797                 ahc->dma_bug_buf = ahc->shared_data_busaddr
4798                                  + driver_data_size - 1;
4799                 /* All target command blocks start out invalid. */
4800                 for (i = 0; i < AHC_TMODE_CMDS; i++)
4801                         ahc->targetcmds[i].cmd_valid = 0;
4802                 ahc_sync_tqinfifo(ahc, BUS_DMASYNC_PREREAD);
4803                 ahc->qoutfifo = (uint8_t *)&ahc->targetcmds[256];
4804         }
4805         ahc->qinfifo = &ahc->qoutfifo[256];
4806
4807         ahc->init_level++;
4808
4809         /* Allocate SCB data now that buffer_dmat is initialized */
4810         if (ahc->scb_data->maxhscbs == 0)
4811                 if (ahc_init_scbdata(ahc) != 0)
4812                         return (ENOMEM);
4813
4814         /*
4815          * Allocate a tstate to house information for our
4816          * initiator presence on the bus as well as the user
4817          * data for any target mode initiator.
4818          */
4819         if (ahc_alloc_tstate(ahc, ahc->our_id, 'A') == NULL) {
4820                 printf("%s: unable to allocate ahc_tmode_tstate.  "
4821                        "Failing attach\n", ahc_name(ahc));
4822                 return (ENOMEM);
4823         }
4824
4825         if ((ahc->features & AHC_TWIN) != 0) {
4826                 if (ahc_alloc_tstate(ahc, ahc->our_id_b, 'B') == NULL) {
4827                         printf("%s: unable to allocate ahc_tmode_tstate.  "
4828                                "Failing attach\n", ahc_name(ahc));
4829                         return (ENOMEM);
4830                 }
4831         }
4832
4833         if (ahc->scb_data->maxhscbs < AHC_SCB_MAX_ALLOC) {
4834                 ahc->flags |= AHC_PAGESCBS;
4835         } else {
4836                 ahc->flags &= ~AHC_PAGESCBS;
4837         }
4838
4839 #ifdef AHC_DEBUG
4840         if (ahc_debug & AHC_SHOW_MISC) {
4841                 printf("%s: hardware scb %u bytes; kernel scb %u bytes; "
4842                        "ahc_dma %u bytes\n",
4843                         ahc_name(ahc),
4844                         (u_int)sizeof(struct hardware_scb),
4845                         (u_int)sizeof(struct scb),
4846                         (u_int)sizeof(struct ahc_dma_seg));
4847         }
4848 #endif /* AHC_DEBUG */
4849
4850         /*
4851          * Look at the information that board initialization or
4852          * the board bios has left us.
4853          */
4854         if (ahc->features & AHC_TWIN) {
4855                 scsi_conf = ahc_inb(ahc, SCSICONF + 1);
4856                 if ((scsi_conf & RESET_SCSI) != 0
4857                  && (ahc->flags & AHC_INITIATORROLE) != 0)
4858                         ahc->flags |= AHC_RESET_BUS_B;
4859         }
4860
4861         scsi_conf = ahc_inb(ahc, SCSICONF);
4862         if ((scsi_conf & RESET_SCSI) != 0
4863          && (ahc->flags & AHC_INITIATORROLE) != 0)
4864                 ahc->flags |= AHC_RESET_BUS_A;
4865
4866         ultraenb = 0;   
4867         tagenable = ALL_TARGETS_MASK;
4868
4869         /* Grab the disconnection disable table and invert it for our needs */
4870         if ((ahc->flags & AHC_USEDEFAULTS) != 0) {
4871                 printf("%s: Host Adapter Bios disabled.  Using default SCSI "
4872                         "device parameters\n", ahc_name(ahc));
4873                 ahc->flags |= AHC_EXTENDED_TRANS_A|AHC_EXTENDED_TRANS_B|
4874                               AHC_TERM_ENB_A|AHC_TERM_ENB_B;
4875                 discenable = ALL_TARGETS_MASK;
4876                 if ((ahc->features & AHC_ULTRA) != 0)
4877                         ultraenb = ALL_TARGETS_MASK;
4878         } else {
4879                 discenable = ~((ahc_inb(ahc, DISC_DSB + 1) << 8)
4880                            | ahc_inb(ahc, DISC_DSB));
4881                 if ((ahc->features & (AHC_ULTRA|AHC_ULTRA2)) != 0)
4882                         ultraenb = (ahc_inb(ahc, ULTRA_ENB + 1) << 8)
4883                                       | ahc_inb(ahc, ULTRA_ENB);
4884         }
4885
4886         if ((ahc->features & (AHC_WIDE|AHC_TWIN)) == 0)
4887                 max_targ = 7;
4888
4889         for (i = 0; i <= max_targ; i++) {
4890                 struct ahc_initiator_tinfo *tinfo;
4891                 struct ahc_tmode_tstate *tstate;
4892                 u_int our_id;
4893                 u_int target_id;
4894                 char channel;
4895
4896                 channel = 'A';
4897                 our_id = ahc->our_id;
4898                 target_id = i;
4899                 if (i > 7 && (ahc->features & AHC_TWIN) != 0) {
4900                         channel = 'B';
4901                         our_id = ahc->our_id_b;
4902                         target_id = i % 8;
4903                 }
4904                 tinfo = ahc_fetch_transinfo(ahc, channel, our_id,
4905                                             target_id, &tstate);
4906                 /* Default to async narrow across the board */
4907                 memset(tinfo, 0, sizeof(*tinfo));
4908                 if (ahc->flags & AHC_USEDEFAULTS) {
4909                         if ((ahc->features & AHC_WIDE) != 0)
4910                                 tinfo->user.width = MSG_EXT_WDTR_BUS_16_BIT;
4911
4912                         /*
4913                          * These will be truncated when we determine the
4914                          * connection type we have with the target.
4915                          */
4916                         tinfo->user.period = ahc_syncrates->period;
4917                         tinfo->user.offset = MAX_OFFSET;
4918                 } else {
4919                         u_int scsirate;
4920                         uint16_t mask;
4921
4922                         /* Take the settings leftover in scratch RAM. */
4923                         scsirate = ahc_inb(ahc, TARG_SCSIRATE + i);
4924                         mask = (0x01 << i);
4925                         if ((ahc->features & AHC_ULTRA2) != 0) {
4926                                 u_int offset;
4927                                 u_int maxsync;
4928
4929                                 if ((scsirate & SOFS) == 0x0F) {
4930                                         /*
4931                                          * Haven't negotiated yet,
4932                                          * so the format is different.
4933                                          */
4934                                         scsirate = (scsirate & SXFR) >> 4
4935                                                  | (ultraenb & mask)
4936                                                   ? 0x08 : 0x0
4937                                                  | (scsirate & WIDEXFER);
4938                                         offset = MAX_OFFSET_ULTRA2;
4939                                 } else
4940                                         offset = ahc_inb(ahc, TARG_OFFSET + i);
4941                                 if ((scsirate & ~WIDEXFER) == 0 && offset != 0)
4942                                         /* Set to the lowest sync rate, 5MHz */
4943                                         scsirate |= 0x1c;
4944                                 maxsync = AHC_SYNCRATE_ULTRA2;
4945                                 if ((ahc->features & AHC_DT) != 0)
4946                                         maxsync = AHC_SYNCRATE_DT;
4947                                 tinfo->user.period =
4948                                     ahc_find_period(ahc, scsirate, maxsync);
4949                                 if (offset == 0)
4950                                         tinfo->user.period = 0;
4951                                 else
4952                                         tinfo->user.offset = MAX_OFFSET;
4953                                 if ((scsirate & SXFR_ULTRA2) <= 8/*10MHz*/
4954                                  && (ahc->features & AHC_DT) != 0)
4955                                         tinfo->user.ppr_options =
4956                                             MSG_EXT_PPR_DT_REQ;
4957                         } else if ((scsirate & SOFS) != 0) {
4958                                 if ((scsirate & SXFR) == 0x40
4959                                  && (ultraenb & mask) != 0) {
4960                                         /* Treat 10MHz as a non-ultra speed */
4961                                         scsirate &= ~SXFR;
4962                                         ultraenb &= ~mask;
4963                                 }
4964                                 tinfo->user.period = 
4965                                     ahc_find_period(ahc, scsirate,
4966                                                     (ultraenb & mask)
4967                                                    ? AHC_SYNCRATE_ULTRA
4968                                                    : AHC_SYNCRATE_FAST);
4969                                 if (tinfo->user.period != 0)
4970                                         tinfo->user.offset = MAX_OFFSET;
4971                         }
4972                         if (tinfo->user.period == 0)
4973                                 tinfo->user.offset = 0;
4974                         if ((scsirate & WIDEXFER) != 0
4975                          && (ahc->features & AHC_WIDE) != 0)
4976                                 tinfo->user.width = MSG_EXT_WDTR_BUS_16_BIT;
4977                         tinfo->user.protocol_version = 4;
4978                         if ((ahc->features & AHC_DT) != 0)
4979                                 tinfo->user.transport_version = 3;
4980                         else
4981                                 tinfo->user.transport_version = 2;
4982                         tinfo->goal.protocol_version = 2;
4983                         tinfo->goal.transport_version = 2;
4984                         tinfo->curr.protocol_version = 2;
4985                         tinfo->curr.transport_version = 2;
4986                 }
4987                 tstate->ultraenb = 0;
4988         }
4989         ahc->user_discenable = discenable;
4990         ahc->user_tagenable = tagenable;
4991
4992         return (ahc->bus_chip_init(ahc));
4993 }
4994
4995 void
4996 ahc_intr_enable(struct ahc_softc *ahc, int enable)
4997 {
4998         u_int hcntrl;
4999
5000         hcntrl = ahc_inb(ahc, HCNTRL);
5001         hcntrl &= ~INTEN;
5002         ahc->pause &= ~INTEN;
5003         ahc->unpause &= ~INTEN;
5004         if (enable) {
5005                 hcntrl |= INTEN;
5006                 ahc->pause |= INTEN;
5007                 ahc->unpause |= INTEN;
5008         }
5009         ahc_outb(ahc, HCNTRL, hcntrl);
5010 }
5011
5012 /*
5013  * Ensure that the card is paused in a location
5014  * outside of all critical sections and that all
5015  * pending work is completed prior to returning.
5016  * This routine should only be called from outside
5017  * an interrupt context.
5018  */
5019 void
5020 ahc_pause_and_flushwork(struct ahc_softc *ahc)
5021 {
5022         int intstat;
5023         int maxloops;
5024         int paused;
5025
5026         maxloops = 1000;
5027         ahc->flags |= AHC_ALL_INTERRUPTS;
5028         paused = FALSE;
5029         do {
5030                 if (paused) {
5031                         ahc_unpause(ahc);
5032                         /*
5033                          * Give the sequencer some time to service
5034                          * any active selections.
5035                          */
5036                         ahc_delay(500);
5037                 }
5038                 ahc_intr(ahc);
5039                 ahc_pause(ahc);
5040                 paused = TRUE;
5041                 ahc_outb(ahc, SCSISEQ, ahc_inb(ahc, SCSISEQ) & ~ENSELO);
5042                 intstat = ahc_inb(ahc, INTSTAT);
5043                 if ((intstat & INT_PEND) == 0) {
5044                         ahc_clear_critical_section(ahc);
5045                         intstat = ahc_inb(ahc, INTSTAT);
5046                 }
5047         } while (--maxloops
5048               && (intstat != 0xFF || (ahc->features & AHC_REMOVABLE) == 0)
5049               && ((intstat & INT_PEND) != 0
5050                || (ahc_inb(ahc, SSTAT0) & (SELDO|SELINGO)) != 0));
5051         if (maxloops == 0) {
5052                 printf("Infinite interrupt loop, INTSTAT = %x",
5053                        ahc_inb(ahc, INTSTAT));
5054         }
5055         ahc_platform_flushwork(ahc);
5056         ahc->flags &= ~AHC_ALL_INTERRUPTS;
5057 }
5058
5059 int
5060 ahc_suspend(struct ahc_softc *ahc)
5061 {
5062
5063         ahc_pause_and_flushwork(ahc);
5064
5065         if (LIST_FIRST(&ahc->pending_scbs) != NULL) {
5066                 ahc_unpause(ahc);
5067                 return (EBUSY);
5068         }
5069
5070 #ifdef AHC_TARGET_MODE
5071         /*
5072          * XXX What about ATIOs that have not yet been serviced?
5073          * Perhaps we should just refuse to be suspended if we
5074          * are acting in a target role.
5075          */
5076         if (ahc->pending_device != NULL) {
5077                 ahc_unpause(ahc);
5078                 return (EBUSY);
5079         }
5080 #endif
5081         ahc_shutdown(ahc);
5082         return (0);
5083 }
5084
5085 int
5086 ahc_resume(struct ahc_softc *ahc)
5087 {
5088
5089         ahc_reset(ahc, /*reinit*/TRUE);
5090         ahc_intr_enable(ahc, TRUE); 
5091         ahc_restart(ahc);
5092         return (0);
5093 }
5094
5095 /************************** Busy Target Table *********************************/
5096 /*
5097  * Return the untagged transaction id for a given target/channel lun.
5098  * Optionally, clear the entry.
5099  */
5100 u_int
5101 ahc_index_busy_tcl(struct ahc_softc *ahc, u_int tcl)
5102 {
5103         u_int scbid;
5104         u_int target_offset;
5105
5106         if ((ahc->flags & AHC_SCB_BTT) != 0) {
5107                 u_int saved_scbptr;
5108                 
5109                 saved_scbptr = ahc_inb(ahc, SCBPTR);
5110                 ahc_outb(ahc, SCBPTR, TCL_LUN(tcl));
5111                 scbid = ahc_inb(ahc, SCB_64_BTT + TCL_TARGET_OFFSET(tcl));
5112                 ahc_outb(ahc, SCBPTR, saved_scbptr);
5113         } else {
5114                 target_offset = TCL_TARGET_OFFSET(tcl);
5115                 scbid = ahc_inb(ahc, BUSY_TARGETS + target_offset);
5116         }
5117
5118         return (scbid);
5119 }
5120
5121 void
5122 ahc_unbusy_tcl(struct ahc_softc *ahc, u_int tcl)
5123 {
5124         u_int target_offset;
5125
5126         if ((ahc->flags & AHC_SCB_BTT) != 0) {
5127                 u_int saved_scbptr;
5128                 
5129                 saved_scbptr = ahc_inb(ahc, SCBPTR);
5130                 ahc_outb(ahc, SCBPTR, TCL_LUN(tcl));
5131                 ahc_outb(ahc, SCB_64_BTT+TCL_TARGET_OFFSET(tcl), SCB_LIST_NULL);
5132                 ahc_outb(ahc, SCBPTR, saved_scbptr);
5133         } else {
5134                 target_offset = TCL_TARGET_OFFSET(tcl);
5135                 ahc_outb(ahc, BUSY_TARGETS + target_offset, SCB_LIST_NULL);
5136         }
5137 }
5138
5139 void
5140 ahc_busy_tcl(struct ahc_softc *ahc, u_int tcl, u_int scbid)
5141 {
5142         u_int target_offset;
5143
5144         if ((ahc->flags & AHC_SCB_BTT) != 0) {
5145                 u_int saved_scbptr;
5146                 
5147                 saved_scbptr = ahc_inb(ahc, SCBPTR);
5148                 ahc_outb(ahc, SCBPTR, TCL_LUN(tcl));
5149                 ahc_outb(ahc, SCB_64_BTT + TCL_TARGET_OFFSET(tcl), scbid);
5150                 ahc_outb(ahc, SCBPTR, saved_scbptr);
5151         } else {
5152                 target_offset = TCL_TARGET_OFFSET(tcl);
5153                 ahc_outb(ahc, BUSY_TARGETS + target_offset, scbid);
5154         }
5155 }
5156
5157 /************************** SCB and SCB queue management **********************/
5158 int
5159 ahc_match_scb(struct ahc_softc *ahc, struct scb *scb, int target,
5160               char channel, int lun, u_int tag, role_t role)
5161 {
5162         int targ = SCB_GET_TARGET(ahc, scb);
5163         char chan = SCB_GET_CHANNEL(ahc, scb);
5164         int slun = SCB_GET_LUN(scb);
5165         int match;
5166
5167         match = ((chan == channel) || (channel == ALL_CHANNELS));
5168         if (match != 0)
5169                 match = ((targ == target) || (target == CAM_TARGET_WILDCARD));
5170         if (match != 0)
5171                 match = ((lun == slun) || (lun == CAM_LUN_WILDCARD));
5172         if (match != 0) {
5173 #ifdef AHC_TARGET_MODE
5174                 int group;
5175
5176                 group = XPT_FC_GROUP(scb->io_ctx->ccb_h.func_code);
5177                 if (role == ROLE_INITIATOR) {
5178                         match = (group != XPT_FC_GROUP_TMODE)
5179                               && ((tag == scb->hscb->tag)
5180                                || (tag == SCB_LIST_NULL));
5181                 } else if (role == ROLE_TARGET) {
5182                         match = (group == XPT_FC_GROUP_TMODE)
5183                               && ((tag == scb->io_ctx->csio.tag_id)
5184                                || (tag == SCB_LIST_NULL));
5185                 }
5186 #else /* !AHC_TARGET_MODE */
5187                 match = ((tag == scb->hscb->tag) || (tag == SCB_LIST_NULL));
5188 #endif /* AHC_TARGET_MODE */
5189         }
5190
5191         return match;
5192 }
5193
5194 void
5195 ahc_freeze_devq(struct ahc_softc *ahc, struct scb *scb)
5196 {
5197         int     target;
5198         char    channel;
5199         int     lun;
5200
5201         target = SCB_GET_TARGET(ahc, scb);
5202         lun = SCB_GET_LUN(scb);
5203         channel = SCB_GET_CHANNEL(ahc, scb);
5204         
5205         ahc_search_qinfifo(ahc, target, channel, lun,
5206                            /*tag*/SCB_LIST_NULL, ROLE_UNKNOWN,
5207                            CAM_REQUEUE_REQ, SEARCH_COMPLETE);
5208
5209         ahc_platform_freeze_devq(ahc, scb);
5210 }
5211
5212 void
5213 ahc_qinfifo_requeue_tail(struct ahc_softc *ahc, struct scb *scb)
5214 {
5215         struct scb *prev_scb;
5216
5217         prev_scb = NULL;
5218         if (ahc_qinfifo_count(ahc) != 0) {
5219                 u_int prev_tag;
5220                 uint8_t prev_pos;
5221
5222                 prev_pos = ahc->qinfifonext - 1;
5223                 prev_tag = ahc->qinfifo[prev_pos];
5224                 prev_scb = ahc_lookup_scb(ahc, prev_tag);
5225         }
5226         ahc_qinfifo_requeue(ahc, prev_scb, scb);
5227         if ((ahc->features & AHC_QUEUE_REGS) != 0) {
5228                 ahc_outb(ahc, HNSCB_QOFF, ahc->qinfifonext);
5229         } else {
5230                 ahc_outb(ahc, KERNEL_QINPOS, ahc->qinfifonext);
5231         }
5232 }
5233
5234 static void
5235 ahc_qinfifo_requeue(struct ahc_softc *ahc, struct scb *prev_scb,
5236                     struct scb *scb)
5237 {
5238         if (prev_scb == NULL) {
5239                 ahc_outb(ahc, NEXT_QUEUED_SCB, scb->hscb->tag);
5240         } else {
5241                 prev_scb->hscb->next = scb->hscb->tag;
5242                 ahc_sync_scb(ahc, prev_scb, 
5243                              BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
5244         }
5245         ahc->qinfifo[ahc->qinfifonext++] = scb->hscb->tag;
5246         scb->hscb->next = ahc->next_queued_scb->hscb->tag;
5247         ahc_sync_scb(ahc, scb, BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
5248 }
5249
5250 static int
5251 ahc_qinfifo_count(struct ahc_softc *ahc)
5252 {
5253         uint8_t qinpos;
5254         uint8_t diff;
5255
5256         if ((ahc->features & AHC_QUEUE_REGS) != 0) {
5257                 qinpos = ahc_inb(ahc, SNSCB_QOFF);
5258                 ahc_outb(ahc, SNSCB_QOFF, qinpos);
5259         } else
5260                 qinpos = ahc_inb(ahc, QINPOS);
5261         diff = ahc->qinfifonext - qinpos;
5262         return (diff);
5263 }
5264
5265 int
5266 ahc_search_qinfifo(struct ahc_softc *ahc, int target, char channel,
5267                    int lun, u_int tag, role_t role, uint32_t status,
5268                    ahc_search_action action)
5269 {
5270         struct  scb *scb;
5271         struct  scb *prev_scb;
5272         uint8_t qinstart;
5273         uint8_t qinpos;
5274         uint8_t qintail;
5275         uint8_t next;
5276         uint8_t prev;
5277         uint8_t curscbptr;
5278         int     found;
5279         int     have_qregs;
5280
5281         qintail = ahc->qinfifonext;
5282         have_qregs = (ahc->features & AHC_QUEUE_REGS) != 0;
5283         if (have_qregs) {
5284                 qinstart = ahc_inb(ahc, SNSCB_QOFF);
5285                 ahc_outb(ahc, SNSCB_QOFF, qinstart);
5286         } else
5287                 qinstart = ahc_inb(ahc, QINPOS);
5288         qinpos = qinstart;
5289         found = 0;
5290         prev_scb = NULL;
5291
5292         if (action == SEARCH_COMPLETE) {
5293                 /*
5294                  * Don't attempt to run any queued untagged transactions
5295                  * until we are done with the abort process.
5296                  */
5297                 ahc_freeze_untagged_queues(ahc);
5298         }
5299
5300         /*
5301          * Start with an empty queue.  Entries that are not chosen
5302          * for removal will be re-added to the queue as we go.
5303          */
5304         ahc->qinfifonext = qinpos;
5305         ahc_outb(ahc, NEXT_QUEUED_SCB, ahc->next_queued_scb->hscb->tag);
5306
5307         while (qinpos != qintail) {
5308                 scb = ahc_lookup_scb(ahc, ahc->qinfifo[qinpos]);
5309                 if (scb == NULL) {
5310                         printf("qinpos = %d, SCB index = %d\n",
5311                                 qinpos, ahc->qinfifo[qinpos]);
5312                         panic("Loop 1\n");
5313                 }
5314
5315                 if (ahc_match_scb(ahc, scb, target, channel, lun, tag, role)) {
5316                         /*
5317                          * We found an scb that needs to be acted on.
5318                          */
5319                         found++;
5320                         switch (action) {
5321                         case SEARCH_COMPLETE:
5322                         {
5323                                 cam_status ostat;
5324                                 cam_status cstat;
5325
5326                                 ostat = ahc_get_transaction_status(scb);
5327                                 if (ostat == CAM_REQ_INPROG)
5328                                         ahc_set_transaction_status(scb, status);
5329                                 cstat = ahc_get_transaction_status(scb);
5330                                 if (cstat != CAM_REQ_CMP)
5331                                         ahc_freeze_scb(scb);
5332                                 if ((scb->flags & SCB_ACTIVE) == 0)
5333                                         printf("Inactive SCB in qinfifo\n");
5334                                 ahc_done(ahc, scb);
5335
5336                                 /* FALLTHROUGH */
5337                         }
5338                         case SEARCH_REMOVE:
5339                                 break;
5340                         case SEARCH_COUNT:
5341                                 ahc_qinfifo_requeue(ahc, prev_scb, scb);
5342                                 prev_scb = scb;
5343                                 break;
5344                         }
5345                 } else {
5346                         ahc_qinfifo_requeue(ahc, prev_scb, scb);
5347                         prev_scb = scb;
5348                 }
5349                 qinpos++;
5350         }
5351
5352         if ((ahc->features & AHC_QUEUE_REGS) != 0) {
5353                 ahc_outb(ahc, HNSCB_QOFF, ahc->qinfifonext);
5354         } else {
5355                 ahc_outb(ahc, KERNEL_QINPOS, ahc->qinfifonext);
5356         }
5357
5358         if (action != SEARCH_COUNT
5359          && (found != 0)
5360          && (qinstart != ahc->qinfifonext)) {
5361                 /*
5362                  * The sequencer may be in the process of dmaing
5363                  * down the SCB at the beginning of the queue.
5364                  * This could be problematic if either the first,
5365                  * or the second SCB is removed from the queue
5366                  * (the first SCB includes a pointer to the "next"
5367                  * SCB to dma). If we have removed any entries, swap
5368                  * the first element in the queue with the next HSCB
5369                  * so the sequencer will notice that NEXT_QUEUED_SCB
5370                  * has changed during its dma attempt and will retry
5371                  * the DMA.
5372                  */
5373                 scb = ahc_lookup_scb(ahc, ahc->qinfifo[qinstart]);
5374
5375                 if (scb == NULL) {
5376                         printf("found = %d, qinstart = %d, qinfifionext = %d\n",
5377                                 found, qinstart, ahc->qinfifonext);
5378                         panic("First/Second Qinfifo fixup\n");
5379                 }
5380                 /*
5381                  * ahc_swap_with_next_hscb forces our next pointer to
5382                  * point to the reserved SCB for future commands.  Save
5383                  * and restore our original next pointer to maintain
5384                  * queue integrity.
5385                  */
5386                 next = scb->hscb->next;
5387                 ahc->scb_data->scbindex[scb->hscb->tag] = NULL;
5388                 ahc_swap_with_next_hscb(ahc, scb);
5389                 scb->hscb->next = next;
5390                 ahc->qinfifo[qinstart] = scb->hscb->tag;
5391
5392                 /* Tell the card about the new head of the qinfifo. */
5393                 ahc_outb(ahc, NEXT_QUEUED_SCB, scb->hscb->tag);
5394
5395                 /* Fixup the tail "next" pointer. */
5396                 qintail = ahc->qinfifonext - 1;
5397                 scb = ahc_lookup_scb(ahc, ahc->qinfifo[qintail]);
5398                 scb->hscb->next = ahc->next_queued_scb->hscb->tag;
5399         }
5400
5401         /*
5402          * Search waiting for selection list.
5403          */
5404         curscbptr = ahc_inb(ahc, SCBPTR);
5405         next = ahc_inb(ahc, WAITING_SCBH);  /* Start at head of list. */
5406         prev = SCB_LIST_NULL;
5407
5408         while (next != SCB_LIST_NULL) {
5409                 uint8_t scb_index;
5410
5411                 ahc_outb(ahc, SCBPTR, next);
5412                 scb_index = ahc_inb(ahc, SCB_TAG);
5413                 if (scb_index >= ahc->scb_data->numscbs) {
5414                         printf("Waiting List inconsistency. "
5415                                "SCB index == %d, yet numscbs == %d.",
5416                                scb_index, ahc->scb_data->numscbs);
5417                         ahc_dump_card_state(ahc);
5418                         panic("for safety");
5419                 }
5420                 scb = ahc_lookup_scb(ahc, scb_index);
5421                 if (scb == NULL) {
5422                         printf("scb_index = %d, next = %d\n",
5423                                 scb_index, next);
5424                         panic("Waiting List traversal\n");
5425                 }
5426                 if (ahc_match_scb(ahc, scb, target, channel,
5427                                   lun, SCB_LIST_NULL, role)) {
5428                         /*
5429                          * We found an scb that needs to be acted on.
5430                          */
5431                         found++;
5432                         switch (action) {
5433                         case SEARCH_COMPLETE:
5434                         {
5435                                 cam_status ostat;
5436                                 cam_status cstat;
5437
5438                                 ostat = ahc_get_transaction_status(scb);
5439                                 if (ostat == CAM_REQ_INPROG)
5440                                         ahc_set_transaction_status(scb,
5441                                                                    status);
5442                                 cstat = ahc_get_transaction_status(scb);
5443                                 if (cstat != CAM_REQ_CMP)
5444                                         ahc_freeze_scb(scb);
5445                                 if ((scb->flags & SCB_ACTIVE) == 0)
5446                                         printf("Inactive SCB in Waiting List\n");
5447                                 ahc_done(ahc, scb);
5448                                 /* FALLTHROUGH */
5449                         }
5450                         case SEARCH_REMOVE:
5451                                 next = ahc_rem_wscb(ahc, next, prev);
5452                                 break;
5453                         case SEARCH_COUNT:
5454                                 prev = next;
5455                                 next = ahc_inb(ahc, SCB_NEXT);
5456                                 break;
5457                         }
5458                 } else {
5459                         
5460                         prev = next;
5461                         next = ahc_inb(ahc, SCB_NEXT);
5462                 }
5463         }
5464         ahc_outb(ahc, SCBPTR, curscbptr);
5465
5466         found += ahc_search_untagged_queues(ahc, /*ahc_io_ctx_t*/NULL, target,
5467                                             channel, lun, status, action);
5468
5469         if (action == SEARCH_COMPLETE)
5470                 ahc_release_untagged_queues(ahc);
5471         return (found);
5472 }
5473
5474 int
5475 ahc_search_untagged_queues(struct ahc_softc *ahc, ahc_io_ctx_t ctx,
5476                            int target, char channel, int lun, uint32_t status,
5477                            ahc_search_action action)
5478 {
5479         struct  scb *scb;
5480         int     maxtarget;
5481         int     found;
5482         int     i;
5483
5484         if (action == SEARCH_COMPLETE) {
5485                 /*
5486                  * Don't attempt to run any queued untagged transactions
5487                  * until we are done with the abort process.
5488                  */
5489                 ahc_freeze_untagged_queues(ahc);
5490         }
5491
5492         found = 0;
5493         i = 0;
5494         if ((ahc->flags & AHC_SCB_BTT) == 0) {
5495
5496                 maxtarget = 16;
5497                 if (target != CAM_TARGET_WILDCARD) {
5498
5499                         i = target;
5500                         if (channel == 'B')
5501                                 i += 8;
5502                         maxtarget = i + 1;
5503                 }
5504         } else {
5505                 maxtarget = 0;
5506         }
5507
5508         for (; i < maxtarget; i++) {
5509                 struct scb_tailq *untagged_q;
5510                 struct scb *next_scb;
5511
5512                 untagged_q = &(ahc->untagged_queues[i]);
5513                 next_scb = TAILQ_FIRST(untagged_q);
5514                 while (next_scb != NULL) {
5515
5516                         scb = next_scb;
5517                         next_scb = TAILQ_NEXT(scb, links.tqe);
5518
5519                         /*
5520                          * The head of the list may be the currently
5521                          * active untagged command for a device.
5522                          * We're only searching for commands that
5523                          * have not been started.  A transaction
5524                          * marked active but still in the qinfifo
5525                          * is removed by the qinfifo scanning code
5526                          * above.
5527                          */
5528                         if ((scb->flags & SCB_ACTIVE) != 0)
5529                                 continue;
5530
5531                         if (ahc_match_scb(ahc, scb, target, channel, lun,
5532                                           SCB_LIST_NULL, ROLE_INITIATOR) == 0
5533                          || (ctx != NULL && ctx != scb->io_ctx))
5534                                 continue;
5535
5536                         /*
5537                          * We found an scb that needs to be acted on.
5538                          */
5539                         found++;
5540                         switch (action) {
5541                         case SEARCH_COMPLETE:
5542                         {
5543                                 cam_status ostat;
5544                                 cam_status cstat;
5545
5546                                 ostat = ahc_get_transaction_status(scb);
5547                                 if (ostat == CAM_REQ_INPROG)
5548                                         ahc_set_transaction_status(scb, status);
5549                                 cstat = ahc_get_transaction_status(scb);
5550                                 if (cstat != CAM_REQ_CMP)
5551                                         ahc_freeze_scb(scb);
5552                                 if ((scb->flags & SCB_ACTIVE) == 0)
5553                                         printf("Inactive SCB in untaggedQ\n");
5554                                 ahc_done(ahc, scb);
5555                                 break;
5556                         }
5557                         case SEARCH_REMOVE:
5558                                 scb->flags &= ~SCB_UNTAGGEDQ;
5559                                 TAILQ_REMOVE(untagged_q, scb, links.tqe);
5560                                 break;
5561                         case SEARCH_COUNT:
5562                                 break;
5563                         }
5564                 }
5565         }
5566
5567         if (action == SEARCH_COMPLETE)
5568                 ahc_release_untagged_queues(ahc);
5569         return (found);
5570 }
5571
5572 int
5573 ahc_search_disc_list(struct ahc_softc *ahc, int target, char channel,
5574                      int lun, u_int tag, int stop_on_first, int remove,
5575                      int save_state)
5576 {
5577         struct  scb *scbp;
5578         u_int   next;
5579         u_int   prev;
5580         u_int   count;
5581         u_int   active_scb;
5582
5583         count = 0;
5584         next = ahc_inb(ahc, DISCONNECTED_SCBH);
5585         prev = SCB_LIST_NULL;
5586
5587         if (save_state) {
5588                 /* restore this when we're done */
5589                 active_scb = ahc_inb(ahc, SCBPTR);
5590         } else
5591                 /* Silence compiler */
5592                 active_scb = SCB_LIST_NULL;
5593
5594         while (next != SCB_LIST_NULL) {
5595                 u_int scb_index;
5596
5597                 ahc_outb(ahc, SCBPTR, next);
5598                 scb_index = ahc_inb(ahc, SCB_TAG);
5599                 if (scb_index >= ahc->scb_data->numscbs) {
5600                         printf("Disconnected List inconsistency. "
5601                                "SCB index == %d, yet numscbs == %d.",
5602                                scb_index, ahc->scb_data->numscbs);
5603                         ahc_dump_card_state(ahc);
5604                         panic("for safety");
5605                 }
5606
5607                 if (next == prev) {
5608                         panic("Disconnected List Loop. "
5609                               "cur SCBPTR == %x, prev SCBPTR == %x.",
5610                               next, prev);
5611                 }
5612                 scbp = ahc_lookup_scb(ahc, scb_index);
5613                 if (ahc_match_scb(ahc, scbp, target, channel, lun,
5614                                   tag, ROLE_INITIATOR)) {
5615                         count++;
5616                         if (remove) {
5617                                 next =
5618                                     ahc_rem_scb_from_disc_list(ahc, prev, next);
5619                         } else {
5620                                 prev = next;
5621                                 next = ahc_inb(ahc, SCB_NEXT);
5622                         }
5623                         if (stop_on_first)
5624                                 break;
5625                 } else {
5626                         prev = next;
5627                         next = ahc_inb(ahc, SCB_NEXT);
5628                 }
5629         }
5630         if (save_state)
5631                 ahc_outb(ahc, SCBPTR, active_scb);
5632         return (count);
5633 }
5634
5635 /*
5636  * Remove an SCB from the on chip list of disconnected transactions.
5637  * This is empty/unused if we are not performing SCB paging.
5638  */
5639 static u_int
5640 ahc_rem_scb_from_disc_list(struct ahc_softc *ahc, u_int prev, u_int scbptr)
5641 {
5642         u_int next;
5643
5644         ahc_outb(ahc, SCBPTR, scbptr);
5645         next = ahc_inb(ahc, SCB_NEXT);
5646
5647         ahc_outb(ahc, SCB_CONTROL, 0);
5648
5649         ahc_add_curscb_to_free_list(ahc);
5650
5651         if (prev != SCB_LIST_NULL) {
5652                 ahc_outb(ahc, SCBPTR, prev);
5653                 ahc_outb(ahc, SCB_NEXT, next);
5654         } else
5655                 ahc_outb(ahc, DISCONNECTED_SCBH, next);
5656
5657         return (next);
5658 }
5659
5660 /*
5661  * Add the SCB as selected by SCBPTR onto the on chip list of
5662  * free hardware SCBs.  This list is empty/unused if we are not
5663  * performing SCB paging.
5664  */
5665 static void
5666 ahc_add_curscb_to_free_list(struct ahc_softc *ahc)
5667 {
5668         /*
5669          * Invalidate the tag so that our abort
5670          * routines don't think it's active.
5671          */
5672         ahc_outb(ahc, SCB_TAG, SCB_LIST_NULL);
5673
5674         if ((ahc->flags & AHC_PAGESCBS) != 0) {
5675                 ahc_outb(ahc, SCB_NEXT, ahc_inb(ahc, FREE_SCBH));
5676                 ahc_outb(ahc, FREE_SCBH, ahc_inb(ahc, SCBPTR));
5677         }
5678 }
5679
5680 /*
5681  * Manipulate the waiting for selection list and return the
5682  * scb that follows the one that we remove.
5683  */
5684 static u_int
5685 ahc_rem_wscb(struct ahc_softc *ahc, u_int scbpos, u_int prev)
5686 {       
5687         u_int curscb, next;
5688
5689         /*
5690          * Select the SCB we want to abort and
5691          * pull the next pointer out of it.
5692          */
5693         curscb = ahc_inb(ahc, SCBPTR);
5694         ahc_outb(ahc, SCBPTR, scbpos);
5695         next = ahc_inb(ahc, SCB_NEXT);
5696
5697         /* Clear the necessary fields */
5698         ahc_outb(ahc, SCB_CONTROL, 0);
5699
5700         ahc_add_curscb_to_free_list(ahc);
5701
5702         /* update the waiting list */
5703         if (prev == SCB_LIST_NULL) {
5704                 /* First in the list */
5705                 ahc_outb(ahc, WAITING_SCBH, next); 
5706
5707                 /*
5708                  * Ensure we aren't attempting to perform
5709                  * selection for this entry.
5710                  */
5711                 ahc_outb(ahc, SCSISEQ, (ahc_inb(ahc, SCSISEQ) & ~ENSELO));
5712         } else {
5713                 /*
5714                  * Select the scb that pointed to us 
5715                  * and update its next pointer.
5716                  */
5717                 ahc_outb(ahc, SCBPTR, prev);
5718                 ahc_outb(ahc, SCB_NEXT, next);
5719         }
5720
5721         /*
5722          * Point us back at the original scb position.
5723          */
5724         ahc_outb(ahc, SCBPTR, curscb);
5725         return next;
5726 }
5727
5728 /******************************** Error Handling ******************************/
5729 /*
5730  * Abort all SCBs that match the given description (target/channel/lun/tag),
5731  * setting their status to the passed in status if the status has not already
5732  * been modified from CAM_REQ_INPROG.  This routine assumes that the sequencer
5733  * is paused before it is called.
5734  */
5735 int
5736 ahc_abort_scbs(struct ahc_softc *ahc, int target, char channel,
5737                int lun, u_int tag, role_t role, uint32_t status)
5738 {
5739         struct  scb *scbp;
5740         struct  scb *scbp_next;
5741         u_int   active_scb;
5742         int     i, j;
5743         int     maxtarget;
5744         int     minlun;
5745         int     maxlun;
5746
5747         int     found;
5748
5749         /*
5750          * Don't attempt to run any queued untagged transactions
5751          * until we are done with the abort process.
5752          */
5753         ahc_freeze_untagged_queues(ahc);
5754
5755         /* restore this when we're done */
5756         active_scb = ahc_inb(ahc, SCBPTR);
5757
5758         found = ahc_search_qinfifo(ahc, target, channel, lun, SCB_LIST_NULL,
5759                                    role, CAM_REQUEUE_REQ, SEARCH_COMPLETE);
5760
5761         /*
5762          * Clean out the busy target table for any untagged commands.
5763          */
5764         i = 0;
5765         maxtarget = 16;
5766         if (target != CAM_TARGET_WILDCARD) {
5767                 i = target;
5768                 if (channel == 'B')
5769                         i += 8;
5770                 maxtarget = i + 1;
5771         }
5772
5773         if (lun == CAM_LUN_WILDCARD) {
5774
5775                 /*
5776                  * Unless we are using an SCB based
5777                  * busy targets table, there is only
5778                  * one table entry for all luns of
5779                  * a target.
5780                  */
5781                 minlun = 0;
5782                 maxlun = 1;
5783                 if ((ahc->flags & AHC_SCB_BTT) != 0)
5784                         maxlun = AHC_NUM_LUNS;
5785         } else {
5786                 minlun = lun;
5787                 maxlun = lun + 1;
5788         }
5789
5790         if (role != ROLE_TARGET) {
5791                 for (;i < maxtarget; i++) {
5792                         for (j = minlun;j < maxlun; j++) {
5793                                 u_int scbid;
5794                                 u_int tcl;
5795
5796                                 tcl = BUILD_TCL(i << 4, j);
5797                                 scbid = ahc_index_busy_tcl(ahc, tcl);
5798                                 scbp = ahc_lookup_scb(ahc, scbid);
5799                                 if (scbp == NULL
5800                                  || ahc_match_scb(ahc, scbp, target, channel,
5801                                                   lun, tag, role) == 0)
5802                                         continue;
5803                                 ahc_unbusy_tcl(ahc, BUILD_TCL(i << 4, j));
5804                         }
5805                 }
5806
5807                 /*
5808                  * Go through the disconnected list and remove any entries we
5809                  * have queued for completion, 0'ing their control byte too.
5810                  * We save the active SCB and restore it ourselves, so there
5811                  * is no reason for this search to restore it too.
5812                  */
5813                 ahc_search_disc_list(ahc, target, channel, lun, tag,
5814                                      /*stop_on_first*/FALSE, /*remove*/TRUE,
5815                                      /*save_state*/FALSE);
5816         }
5817
5818         /*
5819          * Go through the hardware SCB array looking for commands that
5820          * were active but not on any list.  In some cases, these remnants
5821          * might not still have mappings in the scbindex array (e.g. unexpected
5822          * bus free with the same scb queued for an abort).  Don't hold this
5823          * against them.
5824          */
5825         for (i = 0; i < ahc->scb_data->maxhscbs; i++) {
5826                 u_int scbid;
5827
5828                 ahc_outb(ahc, SCBPTR, i);
5829                 scbid = ahc_inb(ahc, SCB_TAG);
5830                 scbp = ahc_lookup_scb(ahc, scbid);
5831                 if ((scbp == NULL && scbid != SCB_LIST_NULL)
5832                  || (scbp != NULL
5833                   && ahc_match_scb(ahc, scbp, target, channel, lun, tag, role)))
5834                         ahc_add_curscb_to_free_list(ahc);
5835         }
5836
5837         /*
5838          * Go through the pending CCB list and look for
5839          * commands for this target that are still active.
5840          * These are other tagged commands that were
5841          * disconnected when the reset occurred.
5842          */
5843         scbp_next = LIST_FIRST(&ahc->pending_scbs);
5844         while (scbp_next != NULL) {
5845                 scbp = scbp_next;
5846                 scbp_next = LIST_NEXT(scbp, pending_links);
5847                 if (ahc_match_scb(ahc, scbp, target, channel, lun, tag, role)) {
5848                         cam_status ostat;
5849
5850                         ostat = ahc_get_transaction_status(scbp);
5851                         if (ostat == CAM_REQ_INPROG)
5852                                 ahc_set_transaction_status(scbp, status);
5853                         if (ahc_get_transaction_status(scbp) != CAM_REQ_CMP)
5854                                 ahc_freeze_scb(scbp);
5855                         if ((scbp->flags & SCB_ACTIVE) == 0)
5856                                 printf("Inactive SCB on pending list\n");
5857                         ahc_done(ahc, scbp);
5858                         found++;
5859                 }
5860         }
5861         ahc_outb(ahc, SCBPTR, active_scb);
5862         ahc_platform_abort_scbs(ahc, target, channel, lun, tag, role, status);
5863         ahc_release_untagged_queues(ahc);
5864         return found;
5865 }
5866
5867 static void
5868 ahc_reset_current_bus(struct ahc_softc *ahc)
5869 {
5870         uint8_t scsiseq;
5871
5872         ahc_outb(ahc, SIMODE1, ahc_inb(ahc, SIMODE1) & ~ENSCSIRST);
5873         scsiseq = ahc_inb(ahc, SCSISEQ);
5874         ahc_outb(ahc, SCSISEQ, scsiseq | SCSIRSTO);
5875         ahc_flush_device_writes(ahc);
5876         ahc_delay(AHC_BUSRESET_DELAY);
5877         /* Turn off the bus reset */
5878         ahc_outb(ahc, SCSISEQ, scsiseq & ~SCSIRSTO);
5879
5880         ahc_clear_intstat(ahc);
5881
5882         /* Re-enable reset interrupts */
5883         ahc_outb(ahc, SIMODE1, ahc_inb(ahc, SIMODE1) | ENSCSIRST);
5884 }
5885
5886 int
5887 ahc_reset_channel(struct ahc_softc *ahc, char channel, int initiate_reset)
5888 {
5889         struct  ahc_devinfo devinfo;
5890         u_int   initiator, target, max_scsiid;
5891         u_int   sblkctl;
5892         u_int   scsiseq;
5893         u_int   simode1;
5894         int     found;
5895         int     restart_needed;
5896         char    cur_channel;
5897
5898         ahc->pending_device = NULL;
5899
5900         ahc_compile_devinfo(&devinfo,
5901                             CAM_TARGET_WILDCARD,
5902                             CAM_TARGET_WILDCARD,
5903                             CAM_LUN_WILDCARD,
5904                             channel, ROLE_UNKNOWN);
5905         ahc_pause(ahc);
5906
5907         /* Make sure the sequencer is in a safe location. */
5908         ahc_clear_critical_section(ahc);
5909
5910         /*
5911          * Run our command complete fifos to ensure that we perform
5912          * completion processing on any commands that 'completed'
5913          * before the reset occurred.
5914          */
5915         ahc_run_qoutfifo(ahc);
5916 #ifdef AHC_TARGET_MODE
5917         /*
5918          * XXX - In Twin mode, the tqinfifo may have commands
5919          *       for an unaffected channel in it.  However, if
5920          *       we have run out of ATIO resources to drain that
5921          *       queue, we may not get them all out here.  Further,
5922          *       the blocked transactions for the reset channel
5923          *       should just be killed off, irrespecitve of whether
5924          *       we are blocked on ATIO resources.  Write a routine
5925          *       to compact the tqinfifo appropriately.
5926          */
5927         if ((ahc->flags & AHC_TARGETROLE) != 0) {
5928                 ahc_run_tqinfifo(ahc, /*paused*/TRUE);
5929         }
5930 #endif
5931
5932         /*
5933          * Reset the bus if we are initiating this reset
5934          */
5935         sblkctl = ahc_inb(ahc, SBLKCTL);
5936         cur_channel = 'A';
5937         if ((ahc->features & AHC_TWIN) != 0
5938          && ((sblkctl & SELBUSB) != 0))
5939             cur_channel = 'B';
5940         scsiseq = ahc_inb(ahc, SCSISEQ_TEMPLATE);
5941         if (cur_channel != channel) {
5942                 /* Case 1: Command for another bus is active
5943                  * Stealthily reset the other bus without
5944                  * upsetting the current bus.
5945                  */
5946                 ahc_outb(ahc, SBLKCTL, sblkctl ^ SELBUSB);
5947                 simode1 = ahc_inb(ahc, SIMODE1) & ~(ENBUSFREE|ENSCSIRST);
5948 #ifdef AHC_TARGET_MODE
5949                 /*
5950                  * Bus resets clear ENSELI, so we cannot
5951                  * defer re-enabling bus reset interrupts
5952                  * if we are in target mode.
5953                  */
5954                 if ((ahc->flags & AHC_TARGETROLE) != 0)
5955                         simode1 |= ENSCSIRST;
5956 #endif
5957                 ahc_outb(ahc, SIMODE1, simode1);
5958                 if (initiate_reset)
5959                         ahc_reset_current_bus(ahc);
5960                 ahc_clear_intstat(ahc);
5961                 ahc_outb(ahc, SCSISEQ, scsiseq & (ENSELI|ENRSELI|ENAUTOATNP));
5962                 ahc_outb(ahc, SBLKCTL, sblkctl);
5963                 restart_needed = FALSE;
5964         } else {
5965                 /* Case 2: A command from this bus is active or we're idle */
5966                 simode1 = ahc_inb(ahc, SIMODE1) & ~(ENBUSFREE|ENSCSIRST);
5967 #ifdef AHC_TARGET_MODE
5968                 /*
5969                  * Bus resets clear ENSELI, so we cannot
5970                  * defer re-enabling bus reset interrupts
5971                  * if we are in target mode.
5972                  */
5973                 if ((ahc->flags & AHC_TARGETROLE) != 0)
5974                         simode1 |= ENSCSIRST;
5975 #endif
5976                 ahc_outb(ahc, SIMODE1, simode1);
5977                 if (initiate_reset)
5978                         ahc_reset_current_bus(ahc);
5979                 ahc_clear_intstat(ahc);
5980                 ahc_outb(ahc, SCSISEQ, scsiseq & (ENSELI|ENRSELI|ENAUTOATNP));
5981                 restart_needed = TRUE;
5982         }
5983
5984         /*
5985          * Clean up all the state information for the
5986          * pending transactions on this bus.
5987          */
5988         found = ahc_abort_scbs(ahc, CAM_TARGET_WILDCARD, channel,
5989                                CAM_LUN_WILDCARD, SCB_LIST_NULL,
5990                                ROLE_UNKNOWN, CAM_SCSI_BUS_RESET);
5991
5992         max_scsiid = (ahc->features & AHC_WIDE) ? 15 : 7;
5993
5994 #ifdef AHC_TARGET_MODE
5995         /*
5996          * Send an immediate notify ccb to all target more peripheral
5997          * drivers affected by this action.
5998          */
5999         for (target = 0; target <= max_scsiid; target++) {
6000                 struct ahc_tmode_tstate* tstate;
6001                 u_int lun;
6002
6003                 tstate = ahc->enabled_targets[target];
6004                 if (tstate == NULL)
6005                         continue;
6006                 for (lun = 0; lun < AHC_NUM_LUNS; lun++) {
6007                         struct ahc_tmode_lstate* lstate;
6008
6009                         lstate = tstate->enabled_luns[lun];
6010                         if (lstate == NULL)
6011                                 continue;
6012
6013                         ahc_queue_lstate_event(ahc, lstate, CAM_TARGET_WILDCARD,
6014                                                EVENT_TYPE_BUS_RESET, /*arg*/0);
6015                         ahc_send_lstate_events(ahc, lstate);
6016                 }
6017         }
6018 #endif
6019         /* Notify the XPT that a bus reset occurred */
6020         ahc_send_async(ahc, devinfo.channel, CAM_TARGET_WILDCARD,
6021                        CAM_LUN_WILDCARD, AC_BUS_RESET, NULL);
6022
6023         /*
6024          * Revert to async/narrow transfers until we renegotiate.
6025          */
6026         for (target = 0; target <= max_scsiid; target++) {
6027
6028                 if (ahc->enabled_targets[target] == NULL)
6029                         continue;
6030                 for (initiator = 0; initiator <= max_scsiid; initiator++) {
6031                         struct ahc_devinfo devinfo;
6032
6033                         ahc_compile_devinfo(&devinfo, target, initiator,
6034                                             CAM_LUN_WILDCARD,
6035                                             channel, ROLE_UNKNOWN);
6036                         ahc_set_width(ahc, &devinfo, MSG_EXT_WDTR_BUS_8_BIT,
6037                                       AHC_TRANS_CUR, /*paused*/TRUE);
6038                         ahc_set_syncrate(ahc, &devinfo, /*syncrate*/NULL,
6039                                          /*period*/0, /*offset*/0,
6040                                          /*ppr_options*/0, AHC_TRANS_CUR,
6041                                          /*paused*/TRUE);
6042                 }
6043         }
6044
6045         if (restart_needed)
6046                 ahc_restart(ahc);
6047         else
6048                 ahc_unpause(ahc);
6049         return found;
6050 }
6051
6052
6053 /***************************** Residual Processing ****************************/
6054 /*
6055  * Calculate the residual for a just completed SCB.
6056  */
6057 void
6058 ahc_calc_residual(struct ahc_softc *ahc, struct scb *scb)
6059 {
6060         struct hardware_scb *hscb;
6061         struct status_pkt *spkt;
6062         uint32_t sgptr;
6063         uint32_t resid_sgptr;
6064         uint32_t resid;
6065
6066         /*
6067          * 5 cases.
6068          * 1) No residual.
6069          *    SG_RESID_VALID clear in sgptr.
6070          * 2) Transferless command
6071          * 3) Never performed any transfers.
6072          *    sgptr has SG_FULL_RESID set.
6073          * 4) No residual but target did not
6074          *    save data pointers after the
6075          *    last transfer, so sgptr was
6076          *    never updated.
6077          * 5) We have a partial residual.
6078          *    Use residual_sgptr to determine
6079          *    where we are.
6080          */
6081
6082         hscb = scb->hscb;
6083         sgptr = ahc_le32toh(hscb->sgptr);
6084         if ((sgptr & SG_RESID_VALID) == 0)
6085                 /* Case 1 */
6086                 return;
6087         sgptr &= ~SG_RESID_VALID;
6088
6089         if ((sgptr & SG_LIST_NULL) != 0)
6090                 /* Case 2 */
6091                 return;
6092
6093         spkt = &hscb->shared_data.status;
6094         resid_sgptr = ahc_le32toh(spkt->residual_sg_ptr);
6095         if ((sgptr & SG_FULL_RESID) != 0) {
6096                 /* Case 3 */
6097                 resid = ahc_get_transfer_length(scb);
6098         } else if ((resid_sgptr & SG_LIST_NULL) != 0) {
6099                 /* Case 4 */
6100                 return;
6101         } else if ((resid_sgptr & ~SG_PTR_MASK) != 0) {
6102                 panic("Bogus resid sgptr value 0x%x\n", resid_sgptr);
6103         } else {
6104                 struct ahc_dma_seg *sg;
6105
6106                 /*
6107                  * Remainder of the SG where the transfer
6108                  * stopped.  
6109                  */
6110                 resid = ahc_le32toh(spkt->residual_datacnt) & AHC_SG_LEN_MASK;
6111                 sg = ahc_sg_bus_to_virt(scb, resid_sgptr & SG_PTR_MASK);
6112
6113                 /* The residual sg_ptr always points to the next sg */
6114                 sg--;
6115
6116                 /*
6117                  * Add up the contents of all residual
6118                  * SG segments that are after the SG where
6119                  * the transfer stopped.
6120                  */
6121                 while ((ahc_le32toh(sg->len) & AHC_DMA_LAST_SEG) == 0) {
6122                         sg++;
6123                         resid += ahc_le32toh(sg->len) & AHC_SG_LEN_MASK;
6124                 }
6125         }
6126         if ((scb->flags & SCB_SENSE) == 0)
6127                 ahc_set_residual(scb, resid);
6128         else
6129                 ahc_set_sense_residual(scb, resid);
6130
6131 #ifdef AHC_DEBUG
6132         if ((ahc_debug & AHC_SHOW_MISC) != 0) {
6133                 ahc_print_path(ahc, scb);
6134                 printf("Handled %sResidual of %d bytes\n",
6135                        (scb->flags & SCB_SENSE) ? "Sense " : "", resid);
6136         }
6137 #endif
6138 }
6139
6140 /******************************* Target Mode **********************************/
6141 #ifdef AHC_TARGET_MODE
6142 /*
6143  * Add a target mode event to this lun's queue
6144  */
6145 static void
6146 ahc_queue_lstate_event(struct ahc_softc *ahc, struct ahc_tmode_lstate *lstate,
6147                        u_int initiator_id, u_int event_type, u_int event_arg)
6148 {
6149         struct ahc_tmode_event *event;
6150         int pending;
6151
6152         xpt_freeze_devq(lstate->path, /*count*/1);
6153         if (lstate->event_w_idx >= lstate->event_r_idx)
6154                 pending = lstate->event_w_idx - lstate->event_r_idx;
6155         else
6156                 pending = AHC_TMODE_EVENT_BUFFER_SIZE + 1
6157                         - (lstate->event_r_idx - lstate->event_w_idx);
6158
6159         if (event_type == EVENT_TYPE_BUS_RESET
6160          || event_type == MSG_BUS_DEV_RESET) {
6161                 /*
6162                  * Any earlier events are irrelevant, so reset our buffer.
6163                  * This has the effect of allowing us to deal with reset
6164                  * floods (an external device holding down the reset line)
6165                  * without losing the event that is really interesting.
6166                  */
6167                 lstate->event_r_idx = 0;
6168                 lstate->event_w_idx = 0;
6169                 xpt_release_devq(lstate->path, pending, /*runqueue*/FALSE);
6170         }
6171
6172         if (pending == AHC_TMODE_EVENT_BUFFER_SIZE) {
6173                 xpt_print_path(lstate->path);
6174                 printf("immediate event %x:%x lost\n",
6175                        lstate->event_buffer[lstate->event_r_idx].event_type,
6176                        lstate->event_buffer[lstate->event_r_idx].event_arg);
6177                 lstate->event_r_idx++;
6178                 if (lstate->event_r_idx == AHC_TMODE_EVENT_BUFFER_SIZE)
6179                         lstate->event_r_idx = 0;
6180                 xpt_release_devq(lstate->path, /*count*/1, /*runqueue*/FALSE);
6181         }
6182
6183         event = &lstate->event_buffer[lstate->event_w_idx];
6184         event->initiator_id = initiator_id;
6185         event->event_type = event_type;
6186         event->event_arg = event_arg;
6187         lstate->event_w_idx++;
6188         if (lstate->event_w_idx == AHC_TMODE_EVENT_BUFFER_SIZE)
6189                 lstate->event_w_idx = 0;
6190 }
6191
6192 /*
6193  * Send any target mode events queued up waiting
6194  * for immediate notify resources.
6195  */
6196 void
6197 ahc_send_lstate_events(struct ahc_softc *ahc, struct ahc_tmode_lstate *lstate)
6198 {
6199         struct ccb_hdr *ccbh;
6200         struct ccb_immed_notify *inot;
6201
6202         while (lstate->event_r_idx != lstate->event_w_idx
6203             && (ccbh = SLIST_FIRST(&lstate->immed_notifies)) != NULL) {
6204                 struct ahc_tmode_event *event;
6205
6206                 event = &lstate->event_buffer[lstate->event_r_idx];
6207                 SLIST_REMOVE_HEAD(&lstate->immed_notifies, sim_links.sle);
6208                 inot = (struct ccb_immed_notify *)ccbh;
6209                 switch (event->event_type) {
6210                 case EVENT_TYPE_BUS_RESET:
6211                         ccbh->status = CAM_SCSI_BUS_RESET|CAM_DEV_QFRZN;
6212                         break;
6213                 default:
6214                         ccbh->status = CAM_MESSAGE_RECV|CAM_DEV_QFRZN;
6215                         inot->message_args[0] = event->event_type;
6216                         inot->message_args[1] = event->event_arg;
6217                         break;
6218                 }
6219                 inot->initiator_id = event->initiator_id;
6220                 inot->sense_len = 0;
6221                 xpt_done((union ccb *)inot);
6222                 lstate->event_r_idx++;
6223                 if (lstate->event_r_idx == AHC_TMODE_EVENT_BUFFER_SIZE)
6224                         lstate->event_r_idx = 0;
6225         }
6226 }
6227 #endif
6228
6229 /******************** Sequencer Program Patching/Download *********************/
6230
6231 #ifdef AHC_DUMP_SEQ
6232 void
6233 ahc_dumpseq(struct ahc_softc* ahc)
6234 {
6235         int i;
6236
6237         ahc_outb(ahc, SEQCTL, PERRORDIS|FAILDIS|FASTMODE|LOADRAM);
6238         ahc_outb(ahc, SEQADDR0, 0);
6239         ahc_outb(ahc, SEQADDR1, 0);
6240         for (i = 0; i < ahc->instruction_ram_size; i++) {
6241                 uint8_t ins_bytes[4];
6242
6243                 ahc_insb(ahc, SEQRAM, ins_bytes, 4);
6244                 printf("0x%08x\n", ins_bytes[0] << 24
6245                                  | ins_bytes[1] << 16
6246                                  | ins_bytes[2] << 8
6247                                  | ins_bytes[3]);
6248         }
6249 }
6250 #endif
6251
6252 static int
6253 ahc_loadseq(struct ahc_softc *ahc)
6254 {
6255         struct  cs cs_table[num_critical_sections];
6256         u_int   begin_set[num_critical_sections];
6257         u_int   end_set[num_critical_sections];
6258         struct  patch *cur_patch;
6259         u_int   cs_count;
6260         u_int   cur_cs;
6261         u_int   i;
6262         u_int   skip_addr;
6263         u_int   sg_prefetch_cnt;
6264         int     downloaded;
6265         uint8_t download_consts[7];
6266
6267         /*
6268          * Start out with 0 critical sections
6269          * that apply to this firmware load.
6270          */
6271         cs_count = 0;
6272         cur_cs = 0;
6273         memset(begin_set, 0, sizeof(begin_set));
6274         memset(end_set, 0, sizeof(end_set));
6275
6276         /* Setup downloadable constant table */
6277         download_consts[QOUTFIFO_OFFSET] = 0;
6278         if (ahc->targetcmds != NULL)
6279                 download_consts[QOUTFIFO_OFFSET] += 32;
6280         download_consts[QINFIFO_OFFSET] = download_consts[QOUTFIFO_OFFSET] + 1;
6281         download_consts[CACHESIZE_MASK] = ahc->pci_cachesize - 1;
6282         download_consts[INVERTED_CACHESIZE_MASK] = ~(ahc->pci_cachesize - 1);
6283         sg_prefetch_cnt = ahc->pci_cachesize;
6284         if (sg_prefetch_cnt < (2 * sizeof(struct ahc_dma_seg)))
6285                 sg_prefetch_cnt = 2 * sizeof(struct ahc_dma_seg);
6286         download_consts[SG_PREFETCH_CNT] = sg_prefetch_cnt;
6287         download_consts[SG_PREFETCH_ALIGN_MASK] = ~(sg_prefetch_cnt - 1);
6288         download_consts[SG_PREFETCH_ADDR_MASK] = (sg_prefetch_cnt - 1);
6289
6290         cur_patch = patches;
6291         downloaded = 0;
6292         skip_addr = 0;
6293         ahc_outb(ahc, SEQCTL, PERRORDIS|FAILDIS|FASTMODE|LOADRAM);
6294         ahc_outb(ahc, SEQADDR0, 0);
6295         ahc_outb(ahc, SEQADDR1, 0);
6296
6297         for (i = 0; i < sizeof(seqprog)/4; i++) {
6298                 if (ahc_check_patch(ahc, &cur_patch, i, &skip_addr) == 0) {
6299                         /*
6300                          * Don't download this instruction as it
6301                          * is in a patch that was removed.
6302                          */
6303                         continue;
6304                 }
6305
6306                 if (downloaded == ahc->instruction_ram_size) {
6307                         /*
6308                          * We're about to exceed the instruction
6309                          * storage capacity for this chip.  Fail
6310                          * the load.
6311                          */
6312                         printf("\n%s: Program too large for instruction memory "
6313                                "size of %d!\n", ahc_name(ahc),
6314                                ahc->instruction_ram_size);
6315                         return (ENOMEM);
6316                 }
6317
6318                 /*
6319                  * Move through the CS table until we find a CS
6320                  * that might apply to this instruction.
6321                  */
6322                 for (; cur_cs < num_critical_sections; cur_cs++) {
6323                         if (critical_sections[cur_cs].end <= i) {
6324                                 if (begin_set[cs_count] == TRUE
6325                                  && end_set[cs_count] == FALSE) {
6326                                         cs_table[cs_count].end = downloaded;
6327                                         end_set[cs_count] = TRUE;
6328                                         cs_count++;
6329                                 }
6330                                 continue;
6331                         }
6332                         if (critical_sections[cur_cs].begin <= i
6333                          && begin_set[cs_count] == FALSE) {
6334                                 cs_table[cs_count].begin = downloaded;
6335                                 begin_set[cs_count] = TRUE;
6336                         }
6337                         break;
6338                 }
6339                 ahc_download_instr(ahc, i, download_consts);
6340                 downloaded++;
6341         }
6342
6343         ahc->num_critical_sections = cs_count;
6344         if (cs_count != 0) {
6345
6346                 cs_count *= sizeof(struct cs);
6347                 ahc->critical_sections = malloc(cs_count, M_DEVBUF, M_NOWAIT);
6348                 if (ahc->critical_sections == NULL)
6349                         panic("ahc_loadseq: Could not malloc");
6350                 memcpy(ahc->critical_sections, cs_table, cs_count);
6351         }
6352         ahc_outb(ahc, SEQCTL, PERRORDIS|FAILDIS|FASTMODE);
6353
6354         if (bootverbose) {
6355                 printf(" %d instructions downloaded\n", downloaded);
6356                 printf("%s: Features 0x%x, Bugs 0x%x, Flags 0x%x\n",
6357                        ahc_name(ahc), ahc->features, ahc->bugs, ahc->flags);
6358         }
6359         return (0);
6360 }
6361
6362 static int
6363 ahc_check_patch(struct ahc_softc *ahc, struct patch **start_patch,
6364                 u_int start_instr, u_int *skip_addr)
6365 {
6366         struct  patch *cur_patch;
6367         struct  patch *last_patch;
6368         u_int   num_patches;
6369
6370         num_patches = sizeof(patches)/sizeof(struct patch);
6371         last_patch = &patches[num_patches];
6372         cur_patch = *start_patch;
6373
6374         while (cur_patch < last_patch && start_instr == cur_patch->begin) {
6375
6376                 if (cur_patch->patch_func(ahc) == 0) {
6377
6378                         /* Start rejecting code */
6379                         *skip_addr = start_instr + cur_patch->skip_instr;
6380                         cur_patch += cur_patch->skip_patch;
6381                 } else {
6382                         /* Accepted this patch.  Advance to the next
6383                          * one and wait for our intruction pointer to
6384                          * hit this point.
6385                          */
6386                         cur_patch++;
6387                 }
6388         }
6389
6390         *start_patch = cur_patch;
6391         if (start_instr < *skip_addr)
6392                 /* Still skipping */
6393                 return (0);
6394
6395         return (1);
6396 }
6397
6398 static void
6399 ahc_download_instr(struct ahc_softc *ahc, u_int instrptr, uint8_t *dconsts)
6400 {
6401         union   ins_formats instr;
6402         struct  ins_format1 *fmt1_ins;
6403         struct  ins_format3 *fmt3_ins;
6404         u_int   opcode;
6405
6406         /*
6407          * The firmware is always compiled into a little endian format.
6408          */
6409         instr.integer = ahc_le32toh(*(uint32_t*)&seqprog[instrptr * 4]);
6410
6411         fmt1_ins = &instr.format1;
6412         fmt3_ins = NULL;
6413
6414         /* Pull the opcode */
6415         opcode = instr.format1.opcode;
6416         switch (opcode) {
6417         case AIC_OP_JMP:
6418         case AIC_OP_JC:
6419         case AIC_OP_JNC:
6420         case AIC_OP_CALL:
6421         case AIC_OP_JNE:
6422         case AIC_OP_JNZ:
6423         case AIC_OP_JE:
6424         case AIC_OP_JZ:
6425         {
6426                 struct patch *cur_patch;
6427                 int address_offset;
6428                 u_int address;
6429                 u_int skip_addr;
6430                 u_int i;
6431
6432                 fmt3_ins = &instr.format3;
6433                 address_offset = 0;
6434                 address = fmt3_ins->address;
6435                 cur_patch = patches;
6436                 skip_addr = 0;
6437
6438                 for (i = 0; i < address;) {
6439
6440                         ahc_check_patch(ahc, &cur_patch, i, &skip_addr);
6441
6442                         if (skip_addr > i) {
6443                                 int end_addr;
6444
6445                                 end_addr = MIN(address, skip_addr);
6446                                 address_offset += end_addr - i;
6447                                 i = skip_addr;
6448                         } else {
6449                                 i++;
6450                         }
6451                 }
6452                 address -= address_offset;
6453                 fmt3_ins->address = address;
6454                 /* FALLTHROUGH */
6455         }
6456         case AIC_OP_OR:
6457         case AIC_OP_AND:
6458         case AIC_OP_XOR:
6459         case AIC_OP_ADD:
6460         case AIC_OP_ADC:
6461         case AIC_OP_BMOV:
6462                 if (fmt1_ins->parity != 0) {
6463                         fmt1_ins->immediate = dconsts[fmt1_ins->immediate];
6464                 }
6465                 fmt1_ins->parity = 0;
6466                 if ((ahc->features & AHC_CMD_CHAN) == 0
6467                  && opcode == AIC_OP_BMOV) {
6468                         /*
6469                          * Block move was added at the same time
6470                          * as the command channel.  Verify that
6471                          * this is only a move of a single element
6472                          * and convert the BMOV to a MOV
6473                          * (AND with an immediate of FF).
6474                          */
6475                         if (fmt1_ins->immediate != 1)
6476                                 panic("%s: BMOV not supported\n",
6477                                       ahc_name(ahc));
6478                         fmt1_ins->opcode = AIC_OP_AND;
6479                         fmt1_ins->immediate = 0xff;
6480                 }
6481                 /* FALLTHROUGH */
6482         case AIC_OP_ROL:
6483                 if ((ahc->features & AHC_ULTRA2) != 0) {
6484                         int i, count;
6485
6486                         /* Calculate odd parity for the instruction */
6487                         for (i = 0, count = 0; i < 31; i++) {
6488                                 uint32_t mask;
6489
6490                                 mask = 0x01 << i;
6491                                 if ((instr.integer & mask) != 0)
6492                                         count++;
6493                         }
6494                         if ((count & 0x01) == 0)
6495                                 instr.format1.parity = 1;
6496                 } else {
6497                         /* Compress the instruction for older sequencers */
6498                         if (fmt3_ins != NULL) {
6499                                 instr.integer =
6500                                         fmt3_ins->immediate
6501                                       | (fmt3_ins->source << 8)
6502                                       | (fmt3_ins->address << 16)
6503                                       | (fmt3_ins->opcode << 25);
6504                         } else {
6505                                 instr.integer =
6506                                         fmt1_ins->immediate
6507                                       | (fmt1_ins->source << 8)
6508                                       | (fmt1_ins->destination << 16)
6509                                       | (fmt1_ins->ret << 24)
6510                                       | (fmt1_ins->opcode << 25);
6511                         }
6512                 }
6513                 /* The sequencer is a little endian cpu */
6514                 instr.integer = ahc_htole32(instr.integer);
6515                 ahc_outsb(ahc, SEQRAM, instr.bytes, 4);
6516                 break;
6517         default:
6518                 panic("Unknown opcode encountered in seq program");
6519                 break;
6520         }
6521 }
6522
6523 int
6524 ahc_print_register(ahc_reg_parse_entry_t *table, u_int num_entries,
6525                    const char *name, u_int address, u_int value,
6526                    u_int *cur_column, u_int wrap_point)
6527 {
6528         int     printed;
6529         u_int   printed_mask;
6530
6531         if (cur_column != NULL && *cur_column >= wrap_point) {
6532                 printf("\n");
6533                 *cur_column = 0;
6534         }
6535         printed = printf("%s[0x%x]", name, value);
6536         if (table == NULL) {
6537                 printed += printf(" ");
6538                 *cur_column += printed;
6539                 return (printed);
6540         }
6541         printed_mask = 0;
6542         while (printed_mask != 0xFF) {
6543                 int entry;
6544
6545                 for (entry = 0; entry < num_entries; entry++) {
6546                         if (((value & table[entry].mask)
6547                           != table[entry].value)
6548                          || ((printed_mask & table[entry].mask)
6549                           == table[entry].mask))
6550                                 continue;
6551
6552                         printed += printf("%s%s",
6553                                           printed_mask == 0 ? ":(" : "|",
6554                                           table[entry].name);
6555                         printed_mask |= table[entry].mask;
6556                         
6557                         break;
6558                 }
6559                 if (entry >= num_entries)
6560                         break;
6561         }
6562         if (printed_mask != 0)
6563                 printed += printf(") ");
6564         else
6565                 printed += printf(" ");
6566         if (cur_column != NULL)
6567                 *cur_column += printed;
6568         return (printed);
6569 }
6570
6571 void
6572 ahc_dump_card_state(struct ahc_softc *ahc)
6573 {
6574         struct  scb *scb;
6575         struct  scb_tailq *untagged_q;
6576         u_int   cur_col;
6577         int     paused;
6578         int     target;
6579         int     maxtarget;
6580         int     i;
6581         uint8_t last_phase;
6582         uint8_t qinpos;
6583         uint8_t qintail;
6584         uint8_t qoutpos;
6585         uint8_t scb_index;
6586         uint8_t saved_scbptr;
6587
6588         if (ahc_is_paused(ahc)) {
6589                 paused = 1;
6590         } else {
6591                 paused = 0;
6592                 ahc_pause(ahc);
6593         }
6594
6595         saved_scbptr = ahc_inb(ahc, SCBPTR);
6596         last_phase = ahc_inb(ahc, LASTPHASE);
6597         printf(">>>>>>>>>>>>>>>>>> Dump Card State Begins <<<<<<<<<<<<<<<<<\n"
6598                "%s: Dumping Card State %s, at SEQADDR 0x%x\n",
6599                ahc_name(ahc), ahc_lookup_phase_entry(last_phase)->phasemsg,
6600                ahc_inb(ahc, SEQADDR0) | (ahc_inb(ahc, SEQADDR1) << 8));
6601         if (paused)
6602                 printf("Card was paused\n");
6603         printf("ACCUM = 0x%x, SINDEX = 0x%x, DINDEX = 0x%x, ARG_2 = 0x%x\n",
6604                ahc_inb(ahc, ACCUM), ahc_inb(ahc, SINDEX), ahc_inb(ahc, DINDEX),
6605                ahc_inb(ahc, ARG_2));
6606         printf("HCNT = 0x%x SCBPTR = 0x%x\n", ahc_inb(ahc, HCNT),
6607                ahc_inb(ahc, SCBPTR));
6608         cur_col = 0;
6609         if ((ahc->features & AHC_DT) != 0)
6610                 ahc_scsiphase_print(ahc_inb(ahc, SCSIPHASE), &cur_col, 50);
6611         ahc_scsisigi_print(ahc_inb(ahc, SCSISIGI), &cur_col, 50);
6612         ahc_error_print(ahc_inb(ahc, ERROR), &cur_col, 50);
6613         ahc_scsibusl_print(ahc_inb(ahc, SCSIBUSL), &cur_col, 50);
6614         ahc_lastphase_print(ahc_inb(ahc, LASTPHASE), &cur_col, 50);
6615         ahc_scsiseq_print(ahc_inb(ahc, SCSISEQ), &cur_col, 50);
6616         ahc_sblkctl_print(ahc_inb(ahc, SBLKCTL), &cur_col, 50);
6617         ahc_scsirate_print(ahc_inb(ahc, SCSIRATE), &cur_col, 50);
6618         ahc_seqctl_print(ahc_inb(ahc, SEQCTL), &cur_col, 50);
6619         ahc_seq_flags_print(ahc_inb(ahc, SEQ_FLAGS), &cur_col, 50);
6620         ahc_sstat0_print(ahc_inb(ahc, SSTAT0), &cur_col, 50);
6621         ahc_sstat1_print(ahc_inb(ahc, SSTAT1), &cur_col, 50);
6622         ahc_sstat2_print(ahc_inb(ahc, SSTAT2), &cur_col, 50);
6623         ahc_sstat3_print(ahc_inb(ahc, SSTAT3), &cur_col, 50);
6624         ahc_simode0_print(ahc_inb(ahc, SIMODE0), &cur_col, 50);
6625         ahc_simode1_print(ahc_inb(ahc, SIMODE1), &cur_col, 50);
6626         ahc_sxfrctl0_print(ahc_inb(ahc, SXFRCTL0), &cur_col, 50);
6627         ahc_dfcntrl_print(ahc_inb(ahc, DFCNTRL), &cur_col, 50);
6628         ahc_dfstatus_print(ahc_inb(ahc, DFSTATUS), &cur_col, 50);
6629         if (cur_col != 0)
6630                 printf("\n");
6631         printf("STACK:");
6632         for (i = 0; i < STACK_SIZE; i++)
6633                printf(" 0x%x", ahc_inb(ahc, STACK)|(ahc_inb(ahc, STACK) << 8));
6634         printf("\nSCB count = %d\n", ahc->scb_data->numscbs);
6635         printf("Kernel NEXTQSCB = %d\n", ahc->next_queued_scb->hscb->tag);
6636         printf("Card NEXTQSCB = %d\n", ahc_inb(ahc, NEXT_QUEUED_SCB));
6637         /* QINFIFO */
6638         printf("QINFIFO entries: ");
6639         if ((ahc->features & AHC_QUEUE_REGS) != 0) {
6640                 qinpos = ahc_inb(ahc, SNSCB_QOFF);
6641                 ahc_outb(ahc, SNSCB_QOFF, qinpos);
6642         } else
6643                 qinpos = ahc_inb(ahc, QINPOS);
6644         qintail = ahc->qinfifonext;
6645         while (qinpos != qintail) {
6646                 printf("%d ", ahc->qinfifo[qinpos]);
6647                 qinpos++;
6648         }
6649         printf("\n");
6650
6651         printf("Waiting Queue entries: ");
6652         scb_index = ahc_inb(ahc, WAITING_SCBH);
6653         i = 0;
6654         while (scb_index != SCB_LIST_NULL && i++ < 256) {
6655                 ahc_outb(ahc, SCBPTR, scb_index);
6656                 printf("%d:%d ", scb_index, ahc_inb(ahc, SCB_TAG));
6657                 scb_index = ahc_inb(ahc, SCB_NEXT);
6658         }
6659         printf("\n");
6660
6661         printf("Disconnected Queue entries: ");
6662         scb_index = ahc_inb(ahc, DISCONNECTED_SCBH);
6663         i = 0;
6664         while (scb_index != SCB_LIST_NULL && i++ < 256) {
6665                 ahc_outb(ahc, SCBPTR, scb_index);
6666                 printf("%d:%d ", scb_index, ahc_inb(ahc, SCB_TAG));
6667                 scb_index = ahc_inb(ahc, SCB_NEXT);
6668         }
6669         printf("\n");
6670                 
6671         ahc_sync_qoutfifo(ahc, BUS_DMASYNC_POSTREAD);
6672         printf("QOUTFIFO entries: ");
6673         qoutpos = ahc->qoutfifonext;
6674         i = 0;
6675         while (ahc->qoutfifo[qoutpos] != SCB_LIST_NULL && i++ < 256) {
6676                 printf("%d ", ahc->qoutfifo[qoutpos]);
6677                 qoutpos++;
6678         }
6679         printf("\n");
6680
6681         printf("Sequencer Free SCB List: ");
6682         scb_index = ahc_inb(ahc, FREE_SCBH);
6683         i = 0;
6684         while (scb_index != SCB_LIST_NULL && i++ < 256) {
6685                 ahc_outb(ahc, SCBPTR, scb_index);
6686                 printf("%d ", scb_index);
6687                 scb_index = ahc_inb(ahc, SCB_NEXT);
6688         }
6689         printf("\n");
6690
6691         printf("Sequencer SCB Info: ");
6692         for (i = 0; i < ahc->scb_data->maxhscbs; i++) {
6693                 ahc_outb(ahc, SCBPTR, i);
6694                 cur_col = printf("\n%3d ", i);
6695
6696                 ahc_scb_control_print(ahc_inb(ahc, SCB_CONTROL), &cur_col, 60);
6697                 ahc_scb_scsiid_print(ahc_inb(ahc, SCB_SCSIID), &cur_col, 60);
6698                 ahc_scb_lun_print(ahc_inb(ahc, SCB_LUN), &cur_col, 60);
6699                 ahc_scb_tag_print(ahc_inb(ahc, SCB_TAG), &cur_col, 60);
6700         }
6701         printf("\n");
6702
6703         printf("Pending list: ");
6704         i = 0;
6705         LIST_FOREACH(scb, &ahc->pending_scbs, pending_links) {
6706                 if (i++ > 256)
6707                         break;
6708                 cur_col = printf("\n%3d ", scb->hscb->tag);
6709                 ahc_scb_control_print(scb->hscb->control, &cur_col, 60);
6710                 ahc_scb_scsiid_print(scb->hscb->scsiid, &cur_col, 60);
6711                 ahc_scb_lun_print(scb->hscb->lun, &cur_col, 60);
6712                 if ((ahc->flags & AHC_PAGESCBS) == 0) {
6713                         ahc_outb(ahc, SCBPTR, scb->hscb->tag);
6714                         printf("(");
6715                         ahc_scb_control_print(ahc_inb(ahc, SCB_CONTROL),
6716                                               &cur_col, 60);
6717                         ahc_scb_tag_print(ahc_inb(ahc, SCB_TAG), &cur_col, 60);
6718                         printf(")");
6719                 }
6720         }
6721         printf("\n");
6722
6723         printf("Kernel Free SCB list: ");
6724         i = 0;
6725         SLIST_FOREACH(scb, &ahc->scb_data->free_scbs, links.sle) {
6726                 if (i++ > 256)
6727                         break;
6728                 printf("%d ", scb->hscb->tag);
6729         }
6730         printf("\n");
6731
6732         maxtarget = (ahc->features & (AHC_WIDE|AHC_TWIN)) ? 15 : 7;
6733         for (target = 0; target <= maxtarget; target++) {
6734                 untagged_q = &ahc->untagged_queues[target];
6735                 if (TAILQ_FIRST(untagged_q) == NULL)
6736                         continue;
6737                 printf("Untagged Q(%d): ", target);
6738                 i = 0;
6739                 TAILQ_FOREACH(scb, untagged_q, links.tqe) {
6740                         if (i++ > 256)
6741                                 break;
6742                         printf("%d ", scb->hscb->tag);
6743                 }
6744                 printf("\n");
6745         }
6746
6747         ahc_platform_dump_card_state(ahc);
6748         printf("\n<<<<<<<<<<<<<<<<< Dump Card State Ends >>>>>>>>>>>>>>>>>>\n");
6749         ahc_outb(ahc, SCBPTR, saved_scbptr);
6750         if (paused == 0)
6751                 ahc_unpause(ahc);
6752 }
6753
6754 /************************* Target Mode ****************************************/
6755 #ifdef AHC_TARGET_MODE
6756 cam_status
6757 ahc_find_tmode_devs(struct ahc_softc *ahc, struct cam_sim *sim, union ccb *ccb,
6758                     struct ahc_tmode_tstate **tstate,
6759                     struct ahc_tmode_lstate **lstate,
6760                     int notfound_failure)
6761 {
6762
6763         if ((ahc->features & AHC_TARGETMODE) == 0)
6764                 return (CAM_REQ_INVALID);
6765
6766         /*
6767          * Handle the 'black hole' device that sucks up
6768          * requests to unattached luns on enabled targets.
6769          */
6770         if (ccb->ccb_h.target_id == CAM_TARGET_WILDCARD
6771          && ccb->ccb_h.target_lun == CAM_LUN_WILDCARD) {
6772                 *tstate = NULL;
6773                 *lstate = ahc->black_hole;
6774         } else {
6775                 u_int max_id;
6776
6777                 max_id = (ahc->features & AHC_WIDE) ? 15 : 7;
6778                 if (ccb->ccb_h.target_id > max_id)
6779                         return (CAM_TID_INVALID);
6780
6781                 if (ccb->ccb_h.target_lun >= AHC_NUM_LUNS)
6782                         return (CAM_LUN_INVALID);
6783
6784                 *tstate = ahc->enabled_targets[ccb->ccb_h.target_id];
6785                 *lstate = NULL;
6786                 if (*tstate != NULL)
6787                         *lstate =
6788                             (*tstate)->enabled_luns[ccb->ccb_h.target_lun];
6789         }
6790
6791         if (notfound_failure != 0 && *lstate == NULL)
6792                 return (CAM_PATH_INVALID);
6793
6794         return (CAM_REQ_CMP);
6795 }
6796
6797 void
6798 ahc_handle_en_lun(struct ahc_softc *ahc, struct cam_sim *sim, union ccb *ccb)
6799 {
6800         struct     ahc_tmode_tstate *tstate;
6801         struct     ahc_tmode_lstate *lstate;
6802         struct     ccb_en_lun *cel;
6803         cam_status status;
6804         u_long     s;
6805         u_int      target;
6806         u_int      lun;
6807         u_int      target_mask;
6808         u_int      our_id;
6809         int        error;
6810         char       channel;
6811
6812         status = ahc_find_tmode_devs(ahc, sim, ccb, &tstate, &lstate,
6813                                      /*notfound_failure*/FALSE);
6814
6815         if (status != CAM_REQ_CMP) {
6816                 ccb->ccb_h.status = status;
6817                 return;
6818         }
6819
6820         if (cam_sim_bus(sim) == 0)
6821                 our_id = ahc->our_id;
6822         else
6823                 our_id = ahc->our_id_b;
6824
6825         if (ccb->ccb_h.target_id != our_id) {
6826                 /*
6827                  * our_id represents our initiator ID, or
6828                  * the ID of the first target to have an
6829                  * enabled lun in target mode.  There are
6830                  * two cases that may preclude enabling a
6831                  * target id other than our_id.
6832                  *
6833                  *   o our_id is for an active initiator role.
6834                  *     Since the hardware does not support
6835                  *     reselections to the initiator role at
6836                  *     anything other than our_id, and our_id
6837                  *     is used by the hardware to indicate the
6838                  *     ID to use for both select-out and
6839                  *     reselect-out operations, the only target
6840                  *     ID we can support in this mode is our_id.
6841                  *
6842                  *   o The MULTARGID feature is not available and
6843                  *     a previous target mode ID has been enabled.
6844                  */
6845                 if ((ahc->features & AHC_MULTIROLE) != 0) {
6846
6847                         if ((ahc->features & AHC_MULTI_TID) != 0
6848                          && (ahc->flags & AHC_INITIATORROLE) != 0) {
6849                                 /*
6850                                  * Only allow additional targets if
6851                                  * the initiator role is disabled.
6852                                  * The hardware cannot handle a re-select-in
6853                                  * on the initiator id during a re-select-out
6854                                  * on a different target id.
6855                                  */
6856                                 status = CAM_TID_INVALID;
6857                         } else if ((ahc->flags & AHC_INITIATORROLE) != 0
6858                                 || ahc->enabled_luns > 0) {
6859                                 /*
6860                                  * Only allow our target id to change
6861                                  * if the initiator role is not configured
6862                                  * and there are no enabled luns which
6863                                  * are attached to the currently registered
6864                                  * scsi id.
6865                                  */
6866                                 status = CAM_TID_INVALID;
6867                         }
6868                 } else if ((ahc->features & AHC_MULTI_TID) == 0
6869                         && ahc->enabled_luns > 0) {
6870
6871                         status = CAM_TID_INVALID;
6872                 }
6873         }
6874
6875         if (status != CAM_REQ_CMP) {
6876                 ccb->ccb_h.status = status;
6877                 return;
6878         }
6879
6880         /*
6881          * We now have an id that is valid.
6882          * If we aren't in target mode, switch modes.
6883          */
6884         if ((ahc->flags & AHC_TARGETROLE) == 0
6885          && ccb->ccb_h.target_id != CAM_TARGET_WILDCARD) {
6886                 u_long   s;
6887                 ahc_flag saved_flags;
6888
6889                 printf("Configuring Target Mode\n");
6890                 ahc_lock(ahc, &s);
6891                 if (LIST_FIRST(&ahc->pending_scbs) != NULL) {
6892                         ccb->ccb_h.status = CAM_BUSY;
6893                         ahc_unlock(ahc, &s);
6894                         return;
6895                 }
6896                 saved_flags = ahc->flags;
6897                 ahc->flags |= AHC_TARGETROLE;
6898                 if ((ahc->features & AHC_MULTIROLE) == 0)
6899                         ahc->flags &= ~AHC_INITIATORROLE;
6900                 ahc_pause(ahc);
6901                 error = ahc_loadseq(ahc);
6902                 if (error != 0) {
6903                         /*
6904                          * Restore original configuration and notify
6905                          * the caller that we cannot support target mode.
6906                          * Since the adapter started out in this
6907                          * configuration, the firmware load will succeed,
6908                          * so there is no point in checking ahc_loadseq's
6909                          * return value.
6910                          */
6911                         ahc->flags = saved_flags;
6912                         (void)ahc_loadseq(ahc);
6913                         ahc_restart(ahc);
6914                         ahc_unlock(ahc, &s);
6915                         ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
6916                         return;
6917                 }
6918                 ahc_restart(ahc);
6919                 ahc_unlock(ahc, &s);
6920         }
6921         cel = &ccb->cel;
6922         target = ccb->ccb_h.target_id;
6923         lun = ccb->ccb_h.target_lun;
6924         channel = SIM_CHANNEL(ahc, sim);
6925         target_mask = 0x01 << target;
6926         if (channel == 'B')
6927                 target_mask <<= 8;
6928
6929         if (cel->enable != 0) {
6930                 u_int scsiseq;
6931
6932                 /* Are we already enabled?? */
6933                 if (lstate != NULL) {
6934                         xpt_print_path(ccb->ccb_h.path);
6935                         printf("Lun already enabled\n");
6936                         ccb->ccb_h.status = CAM_LUN_ALRDY_ENA;
6937                         return;
6938                 }
6939
6940                 if (cel->grp6_len != 0
6941                  || cel->grp7_len != 0) {
6942                         /*
6943                          * Don't (yet?) support vendor
6944                          * specific commands.
6945                          */
6946                         ccb->ccb_h.status = CAM_REQ_INVALID;
6947                         printf("Non-zero Group Codes\n");
6948                         return;
6949                 }
6950
6951                 /*
6952                  * Seems to be okay.
6953                  * Setup our data structures.
6954                  */
6955                 if (target != CAM_TARGET_WILDCARD && tstate == NULL) {
6956                         tstate = ahc_alloc_tstate(ahc, target, channel);
6957                         if (tstate == NULL) {
6958                                 xpt_print_path(ccb->ccb_h.path);
6959                                 printf("Couldn't allocate tstate\n");
6960                                 ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
6961                                 return;
6962                         }
6963                 }
6964                 lstate = malloc(sizeof(*lstate), M_DEVBUF, M_NOWAIT);
6965                 if (lstate == NULL) {
6966                         xpt_print_path(ccb->ccb_h.path);
6967                         printf("Couldn't allocate lstate\n");
6968                         ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
6969                         return;
6970                 }
6971                 memset(lstate, 0, sizeof(*lstate));
6972                 status = xpt_create_path(&lstate->path, /*periph*/NULL,
6973                                          xpt_path_path_id(ccb->ccb_h.path),
6974                                          xpt_path_target_id(ccb->ccb_h.path),
6975                                          xpt_path_lun_id(ccb->ccb_h.path));
6976                 if (status != CAM_REQ_CMP) {
6977                         free(lstate, M_DEVBUF);
6978                         xpt_print_path(ccb->ccb_h.path);
6979                         printf("Couldn't allocate path\n");
6980                         ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
6981                         return;
6982                 }
6983                 SLIST_INIT(&lstate->accept_tios);
6984                 SLIST_INIT(&lstate->immed_notifies);
6985                 ahc_lock(ahc, &s);
6986                 ahc_pause(ahc);
6987                 if (target != CAM_TARGET_WILDCARD) {
6988                         tstate->enabled_luns[lun] = lstate;
6989                         ahc->enabled_luns++;
6990
6991                         if ((ahc->features & AHC_MULTI_TID) != 0) {
6992                                 u_int targid_mask;
6993
6994                                 targid_mask = ahc_inb(ahc, TARGID)
6995                                             | (ahc_inb(ahc, TARGID + 1) << 8);
6996
6997                                 targid_mask |= target_mask;
6998                                 ahc_outb(ahc, TARGID, targid_mask);
6999                                 ahc_outb(ahc, TARGID+1, (targid_mask >> 8));
7000                                 
7001                                 ahc_update_scsiid(ahc, targid_mask);
7002                         } else {
7003                                 u_int our_id;
7004                                 char  channel;
7005
7006                                 channel = SIM_CHANNEL(ahc, sim);
7007                                 our_id = SIM_SCSI_ID(ahc, sim);
7008
7009                                 /*
7010                                  * This can only happen if selections
7011                                  * are not enabled
7012                                  */
7013                                 if (target != our_id) {
7014                                         u_int sblkctl;
7015                                         char  cur_channel;
7016                                         int   swap;
7017
7018                                         sblkctl = ahc_inb(ahc, SBLKCTL);
7019                                         cur_channel = (sblkctl & SELBUSB)
7020                                                     ? 'B' : 'A';
7021                                         if ((ahc->features & AHC_TWIN) == 0)
7022                                                 cur_channel = 'A';
7023                                         swap = cur_channel != channel;
7024                                         if (channel == 'A')
7025                                                 ahc->our_id = target;
7026                                         else
7027                                                 ahc->our_id_b = target;
7028
7029                                         if (swap)
7030                                                 ahc_outb(ahc, SBLKCTL,
7031                                                          sblkctl ^ SELBUSB);
7032
7033                                         ahc_outb(ahc, SCSIID, target);
7034
7035                                         if (swap)
7036                                                 ahc_outb(ahc, SBLKCTL, sblkctl);
7037                                 }
7038                         }
7039                 } else
7040                         ahc->black_hole = lstate;
7041                 /* Allow select-in operations */
7042                 if (ahc->black_hole != NULL && ahc->enabled_luns > 0) {
7043                         scsiseq = ahc_inb(ahc, SCSISEQ_TEMPLATE);
7044                         scsiseq |= ENSELI;
7045                         ahc_outb(ahc, SCSISEQ_TEMPLATE, scsiseq);
7046                         scsiseq = ahc_inb(ahc, SCSISEQ);
7047                         scsiseq |= ENSELI;
7048                         ahc_outb(ahc, SCSISEQ, scsiseq);
7049                 }
7050                 ahc_unpause(ahc);
7051                 ahc_unlock(ahc, &s);
7052                 ccb->ccb_h.status = CAM_REQ_CMP;
7053                 xpt_print_path(ccb->ccb_h.path);
7054                 printf("Lun now enabled for target mode\n");
7055         } else {
7056                 struct scb *scb;
7057                 int i, empty;
7058
7059                 if (lstate == NULL) {
7060                         ccb->ccb_h.status = CAM_LUN_INVALID;
7061                         return;
7062                 }
7063
7064                 ahc_lock(ahc, &s);
7065                 
7066                 ccb->ccb_h.status = CAM_REQ_CMP;
7067                 LIST_FOREACH(scb, &ahc->pending_scbs, pending_links) {
7068                         struct ccb_hdr *ccbh;
7069
7070                         ccbh = &scb->io_ctx->ccb_h;
7071                         if (ccbh->func_code == XPT_CONT_TARGET_IO
7072                          && !xpt_path_comp(ccbh->path, ccb->ccb_h.path)){
7073                                 printf("CTIO pending\n");
7074                                 ccb->ccb_h.status = CAM_REQ_INVALID;
7075                                 ahc_unlock(ahc, &s);
7076                                 return;
7077                         }
7078                 }
7079
7080                 if (SLIST_FIRST(&lstate->accept_tios) != NULL) {
7081                         printf("ATIOs pending\n");
7082                         ccb->ccb_h.status = CAM_REQ_INVALID;
7083                 }
7084
7085                 if (SLIST_FIRST(&lstate->immed_notifies) != NULL) {
7086                         printf("INOTs pending\n");
7087                         ccb->ccb_h.status = CAM_REQ_INVALID;
7088                 }
7089
7090                 if (ccb->ccb_h.status != CAM_REQ_CMP) {
7091                         ahc_unlock(ahc, &s);
7092                         return;
7093                 }
7094
7095                 xpt_print_path(ccb->ccb_h.path);
7096                 printf("Target mode disabled\n");
7097                 xpt_free_path(lstate->path);
7098                 free(lstate, M_DEVBUF);
7099
7100                 ahc_pause(ahc);
7101                 /* Can we clean up the target too? */
7102                 if (target != CAM_TARGET_WILDCARD) {
7103                         tstate->enabled_luns[lun] = NULL;
7104                         ahc->enabled_luns--;
7105                         for (empty = 1, i = 0; i < 8; i++)
7106                                 if (tstate->enabled_luns[i] != NULL) {
7107                                         empty = 0;
7108                                         break;
7109                                 }
7110
7111                         if (empty) {
7112                                 ahc_free_tstate(ahc, target, channel,
7113                                                 /*force*/FALSE);
7114                                 if (ahc->features & AHC_MULTI_TID) {
7115                                         u_int targid_mask;
7116
7117                                         targid_mask = ahc_inb(ahc, TARGID)
7118                                                     | (ahc_inb(ahc, TARGID + 1)
7119                                                        << 8);
7120
7121                                         targid_mask &= ~target_mask;
7122                                         ahc_outb(ahc, TARGID, targid_mask);
7123                                         ahc_outb(ahc, TARGID+1,
7124                                                  (targid_mask >> 8));
7125                                         ahc_update_scsiid(ahc, targid_mask);
7126                                 }
7127                         }
7128                 } else {
7129
7130                         ahc->black_hole = NULL;
7131
7132                         /*
7133                          * We can't allow selections without
7134                          * our black hole device.
7135                          */
7136                         empty = TRUE;
7137                 }
7138                 if (ahc->enabled_luns == 0) {
7139                         /* Disallow select-in */
7140                         u_int scsiseq;
7141
7142                         scsiseq = ahc_inb(ahc, SCSISEQ_TEMPLATE);
7143                         scsiseq &= ~ENSELI;
7144                         ahc_outb(ahc, SCSISEQ_TEMPLATE, scsiseq);
7145                         scsiseq = ahc_inb(ahc, SCSISEQ);
7146                         scsiseq &= ~ENSELI;
7147                         ahc_outb(ahc, SCSISEQ, scsiseq);
7148
7149                         if ((ahc->features & AHC_MULTIROLE) == 0) {
7150                                 printf("Configuring Initiator Mode\n");
7151                                 ahc->flags &= ~AHC_TARGETROLE;
7152                                 ahc->flags |= AHC_INITIATORROLE;
7153                                 /*
7154                                  * Returning to a configuration that
7155                                  * fit previously will always succeed.
7156                                  */
7157                                 (void)ahc_loadseq(ahc);
7158                                 ahc_restart(ahc);
7159                                 /*
7160                                  * Unpaused.  The extra unpause
7161                                  * that follows is harmless.
7162                                  */
7163                         }
7164                 }
7165                 ahc_unpause(ahc);
7166                 ahc_unlock(ahc, &s);
7167         }
7168 }
7169
7170 static void
7171 ahc_update_scsiid(struct ahc_softc *ahc, u_int targid_mask)
7172 {
7173         u_int scsiid_mask;
7174         u_int scsiid;
7175
7176         if ((ahc->features & AHC_MULTI_TID) == 0)
7177                 panic("ahc_update_scsiid called on non-multitid unit\n");
7178
7179         /*
7180          * Since we will rely on the TARGID mask
7181          * for selection enables, ensure that OID
7182          * in SCSIID is not set to some other ID
7183          * that we don't want to allow selections on.
7184          */
7185         if ((ahc->features & AHC_ULTRA2) != 0)
7186                 scsiid = ahc_inb(ahc, SCSIID_ULTRA2);
7187         else
7188                 scsiid = ahc_inb(ahc, SCSIID);
7189         scsiid_mask = 0x1 << (scsiid & OID);
7190         if ((targid_mask & scsiid_mask) == 0) {
7191                 u_int our_id;
7192
7193                 /* ffs counts from 1 */
7194                 our_id = ffs(targid_mask);
7195                 if (our_id == 0)
7196                         our_id = ahc->our_id;
7197                 else
7198                         our_id--;
7199                 scsiid &= TID;
7200                 scsiid |= our_id;
7201         }
7202         if ((ahc->features & AHC_ULTRA2) != 0)
7203                 ahc_outb(ahc, SCSIID_ULTRA2, scsiid);
7204         else
7205                 ahc_outb(ahc, SCSIID, scsiid);
7206 }
7207
7208 void
7209 ahc_run_tqinfifo(struct ahc_softc *ahc, int paused)
7210 {
7211         struct target_cmd *cmd;
7212
7213         /*
7214          * If the card supports auto-access pause,
7215          * we can access the card directly regardless
7216          * of whether it is paused or not.
7217          */
7218         if ((ahc->features & AHC_AUTOPAUSE) != 0)
7219                 paused = TRUE;
7220
7221         ahc_sync_tqinfifo(ahc, BUS_DMASYNC_POSTREAD);
7222         while ((cmd = &ahc->targetcmds[ahc->tqinfifonext])->cmd_valid != 0) {
7223
7224                 /*
7225                  * Only advance through the queue if we
7226                  * have the resources to process the command.
7227                  */
7228                 if (ahc_handle_target_cmd(ahc, cmd) != 0)
7229                         break;
7230
7231                 cmd->cmd_valid = 0;
7232                 ahc_dmamap_sync(ahc, ahc->shared_data_dmat,
7233                                 ahc->shared_data_dmamap,
7234                                 ahc_targetcmd_offset(ahc, ahc->tqinfifonext),
7235                                 sizeof(struct target_cmd),
7236                                 BUS_DMASYNC_PREREAD);
7237                 ahc->tqinfifonext++;
7238
7239                 /*
7240                  * Lazily update our position in the target mode incoming
7241                  * command queue as seen by the sequencer.
7242                  */
7243                 if ((ahc->tqinfifonext & (HOST_TQINPOS - 1)) == 1) {
7244                         if ((ahc->features & AHC_HS_MAILBOX) != 0) {
7245                                 u_int hs_mailbox;
7246
7247                                 hs_mailbox = ahc_inb(ahc, HS_MAILBOX);
7248                                 hs_mailbox &= ~HOST_TQINPOS;
7249                                 hs_mailbox |= ahc->tqinfifonext & HOST_TQINPOS;
7250                                 ahc_outb(ahc, HS_MAILBOX, hs_mailbox);
7251                         } else {
7252                                 if (!paused)
7253                                         ahc_pause(ahc); 
7254                                 ahc_outb(ahc, KERNEL_TQINPOS,
7255                                          ahc->tqinfifonext & HOST_TQINPOS);
7256                                 if (!paused)
7257                                         ahc_unpause(ahc);
7258                         }
7259                 }
7260         }
7261 }
7262
7263 static int
7264 ahc_handle_target_cmd(struct ahc_softc *ahc, struct target_cmd *cmd)
7265 {
7266         struct    ahc_tmode_tstate *tstate;
7267         struct    ahc_tmode_lstate *lstate;
7268         struct    ccb_accept_tio *atio;
7269         uint8_t *byte;
7270         int       initiator;
7271         int       target;
7272         int       lun;
7273
7274         initiator = SCSIID_TARGET(ahc, cmd->scsiid);
7275         target = SCSIID_OUR_ID(cmd->scsiid);
7276         lun    = (cmd->identify & MSG_IDENTIFY_LUNMASK);
7277
7278         byte = cmd->bytes;
7279         tstate = ahc->enabled_targets[target];
7280         lstate = NULL;
7281         if (tstate != NULL)
7282                 lstate = tstate->enabled_luns[lun];
7283
7284         /*
7285          * Commands for disabled luns go to the black hole driver.
7286          */
7287         if (lstate == NULL)
7288                 lstate = ahc->black_hole;
7289
7290         atio = (struct ccb_accept_tio*)SLIST_FIRST(&lstate->accept_tios);
7291         if (atio == NULL) {
7292                 ahc->flags |= AHC_TQINFIFO_BLOCKED;
7293                 /*
7294                  * Wait for more ATIOs from the peripheral driver for this lun.
7295                  */
7296                 if (bootverbose)
7297                         printf("%s: ATIOs exhausted\n", ahc_name(ahc));
7298                 return (1);
7299         } else
7300                 ahc->flags &= ~AHC_TQINFIFO_BLOCKED;
7301 #if 0
7302         printf("Incoming command from %d for %d:%d%s\n",
7303                initiator, target, lun,
7304                lstate == ahc->black_hole ? "(Black Holed)" : "");
7305 #endif
7306         SLIST_REMOVE_HEAD(&lstate->accept_tios, sim_links.sle);
7307
7308         if (lstate == ahc->black_hole) {
7309                 /* Fill in the wildcards */
7310                 atio->ccb_h.target_id = target;
7311                 atio->ccb_h.target_lun = lun;
7312         }
7313
7314         /*
7315          * Package it up and send it off to
7316          * whomever has this lun enabled.
7317          */
7318         atio->sense_len = 0;
7319         atio->init_id = initiator;
7320         if (byte[0] != 0xFF) {
7321                 /* Tag was included */
7322                 atio->tag_action = *byte++;
7323                 atio->tag_id = *byte++;
7324                 atio->ccb_h.flags = CAM_TAG_ACTION_VALID;
7325         } else {
7326                 atio->ccb_h.flags = 0;
7327         }
7328         byte++;
7329
7330         /* Okay.  Now determine the cdb size based on the command code */
7331         switch (*byte >> CMD_GROUP_CODE_SHIFT) {
7332         case 0:
7333                 atio->cdb_len = 6;
7334                 break;
7335         case 1:
7336         case 2:
7337                 atio->cdb_len = 10;
7338                 break;
7339         case 4:
7340                 atio->cdb_len = 16;
7341                 break;
7342         case 5:
7343                 atio->cdb_len = 12;
7344                 break;
7345         case 3:
7346         default:
7347                 /* Only copy the opcode. */
7348                 atio->cdb_len = 1;
7349                 printf("Reserved or VU command code type encountered\n");
7350                 break;
7351         }
7352         
7353         memcpy(atio->cdb_io.cdb_bytes, byte, atio->cdb_len);
7354
7355         atio->ccb_h.status |= CAM_CDB_RECVD;
7356
7357         if ((cmd->identify & MSG_IDENTIFY_DISCFLAG) == 0) {
7358                 /*
7359                  * We weren't allowed to disconnect.
7360                  * We're hanging on the bus until a
7361                  * continue target I/O comes in response
7362                  * to this accept tio.
7363                  */
7364 #if 0
7365                 printf("Received Immediate Command %d:%d:%d - %p\n",
7366                        initiator, target, lun, ahc->pending_device);
7367 #endif
7368                 ahc->pending_device = lstate;
7369                 ahc_freeze_ccb((union ccb *)atio);
7370                 atio->ccb_h.flags |= CAM_DIS_DISCONNECT;
7371         }
7372         xpt_done((union ccb*)atio);
7373         return (0);
7374 }
7375
7376 #endif