a5bc56d3e6b63a452270f485ff8c8f138e30d341
[dragonfly.git] / sys / dev / disk / aic7xxx / aic7xxx.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  * $FreeBSD: src/sys/dev/aic7xxx/aic7xxx.c,v 1.101 2004/08/13 21:39:14 gibbs Exp $
43  * $DragonFly: src/sys/dev/disk/aic7xxx/aic7xxx.c,v 1.18 2007/07/06 02:44:30 pavalos Exp $
44  */
45
46 #include "aic7xxx_osm.h"
47 #include "aic7xxx_inline.h"
48 #include "aicasm/aicasm_insformat.h"
49
50 /****************************** Softc Data ************************************/
51 struct ahc_softc_tailq ahc_tailq = TAILQ_HEAD_INITIALIZER(ahc_tailq);
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 error;
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 referenced" },
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 static int              ahc_other_scb_timeout(struct ahc_softc *ahc,
230                                               struct scb *scb,
231                                               struct scb *other_scb);
232 #ifdef AHC_TARGET_MODE
233 static void             ahc_queue_lstate_event(struct ahc_softc *ahc,
234                                                struct ahc_tmode_lstate *lstate,
235                                                u_int initiator_id,
236                                                u_int event_type,
237                                                u_int event_arg);
238 static void             ahc_update_scsiid(struct ahc_softc *ahc,
239                                           u_int targid_mask);
240 static int              ahc_handle_target_cmd(struct ahc_softc *ahc,
241                                               struct target_cmd *cmd);
242 #endif
243 /************************* Sequencer Execution Control ************************/
244 /*
245  * Restart the sequencer program from address zero
246  */
247 void
248 ahc_restart(struct ahc_softc *ahc)
249 {
250
251         ahc_pause(ahc);
252
253         /* No more pending messages. */
254         ahc_clear_msg_state(ahc);
255
256         ahc_outb(ahc, SCSISIGO, 0);             /* De-assert BSY */
257         ahc_outb(ahc, MSG_OUT, MSG_NOOP);       /* No message to send */
258         ahc_outb(ahc, SXFRCTL1, ahc_inb(ahc, SXFRCTL1) & ~BITBUCKET);
259         ahc_outb(ahc, LASTPHASE, P_BUSFREE);
260         ahc_outb(ahc, SAVED_SCSIID, 0xFF);
261         ahc_outb(ahc, SAVED_LUN, 0xFF);
262
263         /*
264          * Ensure that the sequencer's idea of TQINPOS
265          * matches our own.  The sequencer increments TQINPOS
266          * only after it sees a DMA complete and a reset could
267          * occur before the increment leaving the kernel to believe
268          * the command arrived but the sequencer to not.
269          */
270         ahc_outb(ahc, TQINPOS, ahc->tqinfifonext);
271
272         /* Always allow reselection */
273         ahc_outb(ahc, SCSISEQ,
274                  ahc_inb(ahc, SCSISEQ_TEMPLATE) & (ENSELI|ENRSELI|ENAUTOATNP));
275         if ((ahc->features & AHC_CMD_CHAN) != 0) {
276                 /* Ensure that no DMA operations are in progress */
277                 ahc_outb(ahc, CCSCBCNT, 0);
278                 ahc_outb(ahc, CCSGCTL, 0);
279                 ahc_outb(ahc, CCSCBCTL, 0);
280         }
281         /*
282          * If we were in the process of DMA'ing SCB data into
283          * an SCB, replace that SCB on the free list.  This prevents
284          * an SCB leak.
285          */
286         if ((ahc_inb(ahc, SEQ_FLAGS2) & SCB_DMA) != 0) {
287                 ahc_add_curscb_to_free_list(ahc);
288                 ahc_outb(ahc, SEQ_FLAGS2,
289                          ahc_inb(ahc, SEQ_FLAGS2) & ~SCB_DMA);
290         }
291
292         /*
293          * Clear any pending sequencer interrupt.  It is no
294          * longer relevant since we're resetting the Program
295          * Counter.
296          */
297         ahc_outb(ahc, CLRINT, CLRSEQINT);
298
299         ahc_outb(ahc, MWI_RESIDUAL, 0);
300         ahc_outb(ahc, SEQCTL, ahc->seqctl);
301         ahc_outb(ahc, SEQADDR0, 0);
302         ahc_outb(ahc, SEQADDR1, 0);
303
304         ahc_unpause(ahc);
305 }
306
307 /************************* Input/Output Queues ********************************/
308 void
309 ahc_run_qoutfifo(struct ahc_softc *ahc)
310 {
311         struct scb *scb;
312         u_int  scb_index;
313
314         ahc_sync_qoutfifo(ahc, BUS_DMASYNC_POSTREAD);
315         while (ahc->qoutfifo[ahc->qoutfifonext] != SCB_LIST_NULL) {
316
317                 scb_index = ahc->qoutfifo[ahc->qoutfifonext];
318                 if ((ahc->qoutfifonext & 0x03) == 0x03) {
319                         u_int modnext;
320
321                         /*
322                          * Clear 32bits of QOUTFIFO at a time
323                          * so that we don't clobber an incoming
324                          * byte DMA to the array on architectures
325                          * that only support 32bit load and store
326                          * operations.
327                          */
328                         modnext = ahc->qoutfifonext & ~0x3;
329                         *((uint32_t *)(&ahc->qoutfifo[modnext])) = 0xFFFFFFFFUL;
330                         aic_dmamap_sync(ahc, ahc->shared_data_dmat,
331                                         ahc->shared_data_dmamap,
332                                         /*offset*/modnext, /*len*/4,
333                                         BUS_DMASYNC_PREREAD);
334                 }
335                 ahc->qoutfifonext++;
336
337                 scb = ahc_lookup_scb(ahc, scb_index);
338                 if (scb == NULL) {
339                         kprintf("%s: WARNING no command for scb %d "
340                                "(cmdcmplt)\nQOUTPOS = %d\n",
341                                ahc_name(ahc), scb_index,
342                                (ahc->qoutfifonext - 1) & 0xFF);
343                         continue;
344                 }
345
346                 /*
347                  * Save off the residual
348                  * if there is one.
349                  */
350                 ahc_update_residual(ahc, scb);
351                 ahc_done(ahc, scb);
352         }
353 }
354
355 void
356 ahc_run_untagged_queues(struct ahc_softc *ahc)
357 {
358         int i;
359
360         for (i = 0; i < 16; i++)
361                 ahc_run_untagged_queue(ahc, &ahc->untagged_queues[i]);
362 }
363
364 void
365 ahc_run_untagged_queue(struct ahc_softc *ahc, struct scb_tailq *queue)
366 {
367         struct scb *scb;
368
369         if (ahc->untagged_queue_lock != 0)
370                 return;
371
372         if ((scb = TAILQ_FIRST(queue)) != NULL
373          && (scb->flags & SCB_ACTIVE) == 0) {
374                 scb->flags |= SCB_ACTIVE;
375                 aic_scb_timer_start(scb);
376                 ahc_queue_scb(ahc, scb);
377         }
378 }
379
380 /************************* Interrupt Handling *********************************/
381 void
382 ahc_handle_brkadrint(struct ahc_softc *ahc)
383 {
384         /*
385          * We upset the sequencer :-(
386          * Lookup the error message
387          */
388         int i;
389         int error;
390
391         error = ahc_inb(ahc, ERROR);
392         for (i = 0; error != 1 && i < num_errors; i++)
393                 error >>= 1;
394         kprintf("%s: brkadrint, %s at seqaddr = 0x%x\n",
395                ahc_name(ahc), ahc_hard_errors[i].errmesg,
396                ahc_inb(ahc, SEQADDR0) |
397                (ahc_inb(ahc, SEQADDR1) << 8));
398
399         ahc_dump_card_state(ahc);
400
401         /* Tell everyone that this HBA is no longer available */
402         ahc_abort_scbs(ahc, CAM_TARGET_WILDCARD, ALL_CHANNELS,
403                        CAM_LUN_WILDCARD, SCB_LIST_NULL, ROLE_UNKNOWN,
404                        CAM_NO_HBA);
405
406         /* Disable all interrupt sources by resetting the controller */
407         ahc_shutdown(ahc);
408 }
409
410 void
411 ahc_handle_seqint(struct ahc_softc *ahc, u_int intstat)
412 {
413         struct scb *scb;
414         struct ahc_devinfo devinfo;
415         
416         ahc_fetch_devinfo(ahc, &devinfo);
417
418         /*
419          * Clear the upper byte that holds SEQINT status
420          * codes and clear the SEQINT bit. We will unpause
421          * the sequencer, if appropriate, after servicing
422          * the request.
423          */
424         ahc_outb(ahc, CLRINT, CLRSEQINT);
425         switch (intstat & SEQINT_MASK) {
426         case BAD_STATUS:
427         {
428                 u_int  scb_index;
429                 struct hardware_scb *hscb;
430
431                 /*
432                  * Set the default return value to 0 (don't
433                  * send sense).  The sense code will change
434                  * this if needed.
435                  */
436                 ahc_outb(ahc, RETURN_1, 0);
437
438                 /*
439                  * The sequencer will notify us when a command
440                  * has an error that would be of interest to
441                  * the kernel.  This allows us to leave the sequencer
442                  * running in the common case of command completes
443                  * without error.  The sequencer will already have
444                  * dma'd the SCB back up to us, so we can reference
445                  * the in kernel copy directly.
446                  */
447                 scb_index = ahc_inb(ahc, SCB_TAG);
448                 scb = ahc_lookup_scb(ahc, scb_index);
449                 if (scb == NULL) {
450                         ahc_print_devinfo(ahc, &devinfo);
451                         kprintf("ahc_intr - referenced scb "
452                                "not valid during seqint 0x%x scb(%d)\n",
453                                intstat, scb_index);
454                         ahc_dump_card_state(ahc);
455                         panic("for safety");
456                         goto unpause;
457                 }
458
459                 hscb = scb->hscb; 
460
461                 /* Don't want to clobber the original sense code */
462                 if ((scb->flags & SCB_SENSE) != 0) {
463                         /*
464                          * Clear the SCB_SENSE Flag and have
465                          * the sequencer do a normal command
466                          * complete.
467                          */
468                         scb->flags &= ~SCB_SENSE;
469                         aic_set_transaction_status(scb, CAM_AUTOSENSE_FAIL);
470                         break;
471                 }
472                 aic_set_transaction_status(scb, CAM_SCSI_STATUS_ERROR);
473                 /* Freeze the queue until the client sees the error. */
474                 ahc_freeze_devq(ahc, scb);
475                 aic_freeze_scb(scb);
476                 aic_set_scsi_status(scb, hscb->shared_data.status.scsi_status);
477                 switch (hscb->shared_data.status.scsi_status) {
478                 case SCSI_STATUS_OK:
479                         kprintf("%s: Interrupted for staus of 0???\n",
480                                ahc_name(ahc));
481                         break;
482                 case SCSI_STATUS_CMD_TERMINATED:
483                 case SCSI_STATUS_CHECK_COND:
484                 {
485                         struct ahc_dma_seg *sg;
486                         struct scsi_sense *sc;
487                         struct ahc_initiator_tinfo *targ_info;
488                         struct ahc_tmode_tstate *tstate;
489                         struct ahc_transinfo *tinfo;
490 #ifdef AHC_DEBUG
491                         if (ahc_debug & AHC_SHOW_SENSE) {
492                                 ahc_print_path(ahc, scb);
493                                 kprintf("SCB %d: requests Check Status\n",
494                                        scb->hscb->tag);
495                         }
496 #endif
497
498                         if (aic_perform_autosense(scb) == 0)
499                                 break;
500
501                         targ_info = ahc_fetch_transinfo(ahc,
502                                                         devinfo.channel,
503                                                         devinfo.our_scsiid,
504                                                         devinfo.target,
505                                                         &tstate);
506                         tinfo = &targ_info->curr;
507                         sg = scb->sg_list;
508                         sc = (struct scsi_sense *)(&hscb->shared_data.cdb); 
509                         /*
510                          * Save off the residual if there is one.
511                          */
512                         ahc_update_residual(ahc, scb);
513 #ifdef AHC_DEBUG
514                         if (ahc_debug & AHC_SHOW_SENSE) {
515                                 ahc_print_path(ahc, scb);
516                                 kprintf("Sending Sense\n");
517                         }
518 #endif
519                         sg->addr = ahc_get_sense_bufaddr(ahc, scb);
520                         sg->len = aic_get_sense_bufsize(ahc, scb);
521                         sg->len |= AHC_DMA_LAST_SEG;
522
523                         /* Fixup byte order */
524                         sg->addr = aic_htole32(sg->addr);
525                         sg->len = aic_htole32(sg->len);
526
527                         sc->opcode = REQUEST_SENSE;
528                         sc->byte2 = 0;
529                         if (tinfo->protocol_version <= SCSI_REV_2
530                          && SCB_GET_LUN(scb) < 8)
531                                 sc->byte2 = SCB_GET_LUN(scb) << 5;
532                         sc->unused[0] = 0;
533                         sc->unused[1] = 0;
534                         sc->length = sg->len;
535                         sc->control = 0;
536
537                         /*
538                          * We can't allow the target to disconnect.
539                          * This will be an untagged transaction and
540                          * having the target disconnect will make this
541                          * transaction indestinguishable from outstanding
542                          * tagged transactions.
543                          */
544                         hscb->control = 0;
545
546                         /*
547                          * This request sense could be because the
548                          * the device lost power or in some other
549                          * way has lost our transfer negotiations.
550                          * Renegotiate if appropriate.  Unit attention
551                          * errors will be reported before any data
552                          * phases occur.
553                          */
554                         if (aic_get_residual(scb) 
555                          == aic_get_transfer_length(scb)) {
556                                 ahc_update_neg_request(ahc, &devinfo,
557                                                        tstate, targ_info,
558                                                        AHC_NEG_IF_NON_ASYNC);
559                         }
560                         if (tstate->auto_negotiate & devinfo.target_mask) {
561                                 hscb->control |= MK_MESSAGE;
562                                 scb->flags &= ~SCB_NEGOTIATE;
563                                 scb->flags |= SCB_AUTO_NEGOTIATE;
564                         }
565                         hscb->cdb_len = sizeof(*sc);
566                         hscb->dataptr = sg->addr; 
567                         hscb->datacnt = sg->len;
568                         hscb->sgptr = scb->sg_list_phys | SG_FULL_RESID;
569                         hscb->sgptr = aic_htole32(hscb->sgptr);
570                         scb->sg_count = 1;
571                         scb->flags |= SCB_SENSE;
572                         ahc_qinfifo_requeue_tail(ahc, scb);
573                         ahc_outb(ahc, RETURN_1, SEND_SENSE);
574                         /*
575                          * Ensure we have enough time to actually
576                          * retrieve the sense.
577                          */
578                         aic_scb_timer_reset(scb, 5 * 1000000);
579                         break;
580                 }
581                 default:
582                         break;
583                 }
584                 break;
585         }
586         case NO_MATCH:
587         {
588                 /* Ensure we don't leave the selection hardware on */
589                 ahc_outb(ahc, SCSISEQ,
590                          ahc_inb(ahc, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP));
591
592                 kprintf("%s:%c:%d: no active SCB for reconnecting "
593                        "target - issuing BUS DEVICE RESET\n",
594                        ahc_name(ahc), devinfo.channel, devinfo.target);
595                 kprintf("SAVED_SCSIID == 0x%x, SAVED_LUN == 0x%x, "
596                        "ARG_1 == 0x%x ACCUM = 0x%x\n",
597                        ahc_inb(ahc, SAVED_SCSIID), ahc_inb(ahc, SAVED_LUN),
598                        ahc_inb(ahc, ARG_1), ahc_inb(ahc, ACCUM));
599                 kprintf("SEQ_FLAGS == 0x%x, SCBPTR == 0x%x, BTT == 0x%x, "
600                        "SINDEX == 0x%x\n",
601                        ahc_inb(ahc, SEQ_FLAGS), ahc_inb(ahc, SCBPTR),
602                        ahc_index_busy_tcl(ahc,
603                             BUILD_TCL(ahc_inb(ahc, SAVED_SCSIID),
604                                       ahc_inb(ahc, SAVED_LUN))),
605                        ahc_inb(ahc, SINDEX));
606                 kprintf("SCSIID == 0x%x, SCB_SCSIID == 0x%x, SCB_LUN == 0x%x, "
607                        "SCB_TAG == 0x%x, SCB_CONTROL == 0x%x\n",
608                        ahc_inb(ahc, SCSIID), ahc_inb(ahc, SCB_SCSIID),
609                        ahc_inb(ahc, SCB_LUN), ahc_inb(ahc, SCB_TAG),
610                        ahc_inb(ahc, SCB_CONTROL));
611                 kprintf("SCSIBUSL == 0x%x, SCSISIGI == 0x%x\n",
612                        ahc_inb(ahc, SCSIBUSL), ahc_inb(ahc, SCSISIGI));
613                 kprintf("SXFRCTL0 == 0x%x\n", ahc_inb(ahc, SXFRCTL0));
614                 kprintf("SEQCTL == 0x%x\n", ahc_inb(ahc, SEQCTL));
615                 ahc_dump_card_state(ahc);
616                 ahc->msgout_buf[0] = MSG_BUS_DEV_RESET;
617                 ahc->msgout_len = 1;
618                 ahc->msgout_index = 0;
619                 ahc->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
620                 ahc_outb(ahc, MSG_OUT, HOST_MSG);
621                 ahc_assert_atn(ahc);
622                 break;
623         }
624         case SEND_REJECT: 
625         {
626                 u_int rejbyte = ahc_inb(ahc, ACCUM);
627                 kprintf("%s:%c:%d: Warning - unknown message received from "
628                        "target (0x%x).  Rejecting\n", 
629                        ahc_name(ahc), devinfo.channel, devinfo.target, rejbyte);
630                 break; 
631         }
632         case PROTO_VIOLATION:
633         {
634                 ahc_handle_proto_violation(ahc);
635                 break;
636         }
637         case IGN_WIDE_RES:
638                 ahc_handle_ign_wide_residue(ahc, &devinfo);
639                 break;
640         case PDATA_REINIT:
641                 ahc_reinitialize_dataptrs(ahc);
642                 break;
643         case BAD_PHASE:
644         {
645                 u_int lastphase;
646
647                 lastphase = ahc_inb(ahc, LASTPHASE);
648                 kprintf("%s:%c:%d: unknown scsi bus phase %x, "
649                        "lastphase = 0x%x.  Attempting to continue\n",
650                        ahc_name(ahc), devinfo.channel, devinfo.target,
651                        lastphase, ahc_inb(ahc, SCSISIGI));
652                 break;
653         }
654         case MISSED_BUSFREE:
655         {
656                 u_int lastphase;
657
658                 lastphase = ahc_inb(ahc, LASTPHASE);
659                 kprintf("%s:%c:%d: Missed busfree. "
660                        "Lastphase = 0x%x, Curphase = 0x%x\n",
661                        ahc_name(ahc), devinfo.channel, devinfo.target,
662                        lastphase, ahc_inb(ahc, SCSISIGI));
663                 ahc_restart(ahc);
664                 return;
665         }
666         case HOST_MSG_LOOP:
667         {
668                 /*
669                  * The sequencer has encountered a message phase
670                  * that requires host assistance for completion.
671                  * While handling the message phase(s), we will be
672                  * notified by the sequencer after each byte is
673                  * transfered so we can track bus phase changes.
674                  *
675                  * If this is the first time we've seen a HOST_MSG_LOOP
676                  * interrupt, initialize the state of the host message
677                  * loop.
678                  */
679                 if (ahc->msg_type == MSG_TYPE_NONE) {
680                         struct scb *scb;
681                         u_int scb_index;
682                         u_int bus_phase;
683
684                         bus_phase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
685                         if (bus_phase != P_MESGIN
686                          && bus_phase != P_MESGOUT) {
687                                 kprintf("ahc_intr: HOST_MSG_LOOP bad "
688                                        "phase 0x%x\n",
689                                       bus_phase);
690                                 /*
691                                  * Probably transitioned to bus free before
692                                  * we got here.  Just punt the message.
693                                  */
694                                 ahc_clear_intstat(ahc);
695                                 ahc_restart(ahc);
696                                 return;
697                         }
698
699                         scb_index = ahc_inb(ahc, SCB_TAG);
700                         scb = ahc_lookup_scb(ahc, scb_index);
701                         if (devinfo.role == ROLE_INITIATOR) {
702                                 if (scb == NULL)
703                                         panic("HOST_MSG_LOOP with "
704                                               "invalid SCB %x\n", scb_index);
705
706                                 if (bus_phase == P_MESGOUT)
707                                         ahc_setup_initiator_msgout(ahc,
708                                                                    &devinfo,
709                                                                    scb);
710                                 else {
711                                         ahc->msg_type =
712                                             MSG_TYPE_INITIATOR_MSGIN;
713                                         ahc->msgin_index = 0;
714                                 }
715                         }
716 #ifdef AHC_TARGET_MODE
717                         else {
718                                 if (bus_phase == P_MESGOUT) {
719                                         ahc->msg_type =
720                                             MSG_TYPE_TARGET_MSGOUT;
721                                         ahc->msgin_index = 0;
722                                 }
723                                 else 
724                                         ahc_setup_target_msgin(ahc,
725                                                                &devinfo,
726                                                                scb);
727                         }
728 #endif
729                 }
730
731                 ahc_handle_message_phase(ahc);
732                 break;
733         }
734         case PERR_DETECTED:
735         {
736                 /*
737                  * If we've cleared the parity error interrupt
738                  * but the sequencer still believes that SCSIPERR
739                  * is true, it must be that the parity error is
740                  * for the currently presented byte on the bus,
741                  * and we are not in a phase (data-in) where we will
742                  * eventually ack this byte.  Ack the byte and
743                  * throw it away in the hope that the target will
744                  * take us to message out to deliver the appropriate
745                  * error message.
746                  */
747                 if ((intstat & SCSIINT) == 0
748                  && (ahc_inb(ahc, SSTAT1) & SCSIPERR) != 0) {
749
750                         if ((ahc->features & AHC_DT) == 0) {
751                                 u_int curphase;
752
753                                 /*
754                                  * The hardware will only let you ack bytes
755                                  * if the expected phase in SCSISIGO matches
756                                  * the current phase.  Make sure this is
757                                  * currently the case.
758                                  */
759                                 curphase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
760                                 ahc_outb(ahc, LASTPHASE, curphase);
761                                 ahc_outb(ahc, SCSISIGO, curphase);
762                         }
763                         if ((ahc_inb(ahc, SCSISIGI) & (CDI|MSGI)) == 0) {
764                                 int wait;
765
766                                 /*
767                                  * In a data phase.  Faster to bitbucket
768                                  * the data than to individually ack each
769                                  * byte.  This is also the only strategy
770                                  * that will work with AUTOACK enabled.
771                                  */
772                                 ahc_outb(ahc, SXFRCTL1,
773                                          ahc_inb(ahc, SXFRCTL1) | BITBUCKET);
774                                 wait = 5000;
775                                 while (--wait != 0) {
776                                         if ((ahc_inb(ahc, SCSISIGI)
777                                           & (CDI|MSGI)) != 0)
778                                                 break;
779                                         aic_delay(100);
780                                 }
781                                 ahc_outb(ahc, SXFRCTL1,
782                                          ahc_inb(ahc, SXFRCTL1) & ~BITBUCKET);
783                                 if (wait == 0) {
784                                         struct  scb *scb;
785                                         u_int   scb_index;
786
787                                         ahc_print_devinfo(ahc, &devinfo);
788                                         kprintf("Unable to clear parity error.  "
789                                                "Resetting bus.\n");
790                                         scb_index = ahc_inb(ahc, SCB_TAG);
791                                         scb = ahc_lookup_scb(ahc, scb_index);
792                                         if (scb != NULL)
793                                                 aic_set_transaction_status(scb,
794                                                     CAM_UNCOR_PARITY);
795                                         ahc_reset_channel(ahc, devinfo.channel, 
796                                                           /*init reset*/TRUE);
797                                 }
798                         } else {
799                                 ahc_inb(ahc, SCSIDATL);
800                         }
801                 }
802                 break;
803         }
804         case DATA_OVERRUN:
805         {
806                 /*
807                  * When the sequencer detects an overrun, it
808                  * places the controller in "BITBUCKET" mode
809                  * and allows the target to complete its transfer.
810                  * Unfortunately, none of the counters get updated
811                  * when the controller is in this mode, so we have
812                  * no way of knowing how large the overrun was.
813                  */
814                 u_int scbindex = ahc_inb(ahc, SCB_TAG);
815                 u_int lastphase = ahc_inb(ahc, LASTPHASE);
816                 u_int i;
817
818                 scb = ahc_lookup_scb(ahc, scbindex);
819                 for (i = 0; i < num_phases; i++) {
820                         if (lastphase == ahc_phase_table[i].phase)
821                                 break;
822                 }
823                 ahc_print_path(ahc, scb);
824                 kprintf("data overrun detected %s."
825                        "  Tag == 0x%x.\n",
826                        ahc_phase_table[i].phasemsg,
827                        scb->hscb->tag);
828                 ahc_print_path(ahc, scb);
829                 kprintf("%s seen Data Phase.  Length = %ld.  NumSGs = %d.\n",
830                        ahc_inb(ahc, SEQ_FLAGS) & DPHASE ? "Have" : "Haven't",
831                        aic_get_transfer_length(scb), scb->sg_count);
832                 if (scb->sg_count > 0) {
833                         for (i = 0; i < scb->sg_count; i++) {
834
835                                 kprintf("sg[%d] - Addr 0x%x%x : Length %d\n",
836                                        i,
837                                        (aic_le32toh(scb->sg_list[i].len) >> 24
838                                         & SG_HIGH_ADDR_BITS),
839                                        aic_le32toh(scb->sg_list[i].addr),
840                                        aic_le32toh(scb->sg_list[i].len)
841                                        & AHC_SG_LEN_MASK);
842                         }
843                 }
844                 /*
845                  * Set this and it will take effect when the
846                  * target does a command complete.
847                  */
848                 ahc_freeze_devq(ahc, scb);
849                 if ((scb->flags & SCB_SENSE) == 0) {
850                         aic_set_transaction_status(scb, CAM_DATA_RUN_ERR);
851                 } else {
852                         scb->flags &= ~SCB_SENSE;
853                         aic_set_transaction_status(scb, CAM_AUTOSENSE_FAIL);
854                 }
855                 aic_freeze_scb(scb);
856
857                 if ((ahc->features & AHC_ULTRA2) != 0) {
858                         /*
859                          * Clear the channel in case we return
860                          * to data phase later.
861                          */
862                         ahc_outb(ahc, SXFRCTL0,
863                                  ahc_inb(ahc, SXFRCTL0) | CLRSTCNT|CLRCHN);
864                         ahc_outb(ahc, SXFRCTL0,
865                                  ahc_inb(ahc, SXFRCTL0) | CLRSTCNT|CLRCHN);
866                 }
867                 if ((ahc->flags & AHC_39BIT_ADDRESSING) != 0) {
868                         u_int dscommand1;
869
870                         /* Ensure HHADDR is 0 for future DMA operations. */
871                         dscommand1 = ahc_inb(ahc, DSCOMMAND1);
872                         ahc_outb(ahc, DSCOMMAND1, dscommand1 | HADDLDSEL0);
873                         ahc_outb(ahc, HADDR, 0);
874                         ahc_outb(ahc, DSCOMMAND1, dscommand1);
875                 }
876                 break;
877         }
878         case MKMSG_FAILED:
879         {
880                 u_int scbindex;
881
882                 kprintf("%s:%c:%d:%d: Attempt to issue message failed\n",
883                        ahc_name(ahc), devinfo.channel, devinfo.target,
884                        devinfo.lun);
885                 scbindex = ahc_inb(ahc, SCB_TAG);
886                 scb = ahc_lookup_scb(ahc, scbindex);
887                 if (scb != NULL
888                  && (scb->flags & SCB_RECOVERY_SCB) != 0)
889                         /*
890                          * Ensure that we didn't put a second instance of this
891                          * SCB into the QINFIFO.
892                          */
893                         ahc_search_qinfifo(ahc, SCB_GET_TARGET(ahc, scb),
894                                            SCB_GET_CHANNEL(ahc, scb),
895                                            SCB_GET_LUN(scb), scb->hscb->tag,
896                                            ROLE_INITIATOR, /*status*/0,
897                                            SEARCH_REMOVE);
898                 break;
899         }
900         case NO_FREE_SCB:
901         {
902                 kprintf("%s: No free or disconnected SCBs\n", ahc_name(ahc));
903                 ahc_dump_card_state(ahc);
904                 panic("for safety");
905                 break;
906         }
907         case SCB_MISMATCH:
908         {
909                 u_int scbptr;
910
911                 scbptr = ahc_inb(ahc, SCBPTR);
912                 kprintf("Bogus TAG after DMA.  SCBPTR %d, tag %d, our tag %d\n",
913                        scbptr, ahc_inb(ahc, ARG_1),
914                        ahc->scb_data->hscbs[scbptr].tag);
915                 ahc_dump_card_state(ahc);
916                 panic("for saftey");
917                 break;
918         }
919         case OUT_OF_RANGE:
920         {
921                 kprintf("%s: BTT calculation out of range\n", ahc_name(ahc));
922                 kprintf("SAVED_SCSIID == 0x%x, SAVED_LUN == 0x%x, "
923                        "ARG_1 == 0x%x ACCUM = 0x%x\n",
924                        ahc_inb(ahc, SAVED_SCSIID), ahc_inb(ahc, SAVED_LUN),
925                        ahc_inb(ahc, ARG_1), ahc_inb(ahc, ACCUM));
926                 kprintf("SEQ_FLAGS == 0x%x, SCBPTR == 0x%x, BTT == 0x%x, "
927                        "SINDEX == 0x%x\n, A == 0x%x\n",
928                        ahc_inb(ahc, SEQ_FLAGS), ahc_inb(ahc, SCBPTR),
929                        ahc_index_busy_tcl(ahc,
930                             BUILD_TCL(ahc_inb(ahc, SAVED_SCSIID),
931                                       ahc_inb(ahc, SAVED_LUN))),
932                        ahc_inb(ahc, SINDEX),
933                        ahc_inb(ahc, ACCUM));
934                 kprintf("SCSIID == 0x%x, SCB_SCSIID == 0x%x, SCB_LUN == 0x%x, "
935                        "SCB_TAG == 0x%x, SCB_CONTROL == 0x%x\n",
936                        ahc_inb(ahc, SCSIID), ahc_inb(ahc, SCB_SCSIID),
937                        ahc_inb(ahc, SCB_LUN), ahc_inb(ahc, SCB_TAG),
938                        ahc_inb(ahc, SCB_CONTROL));
939                 kprintf("SCSIBUSL == 0x%x, SCSISIGI == 0x%x\n",
940                        ahc_inb(ahc, SCSIBUSL), ahc_inb(ahc, SCSISIGI));
941                 ahc_dump_card_state(ahc);
942                 panic("for safety");
943                 break;
944         }
945         default:
946                 kprintf("ahc_intr: seqint, "
947                        "intstat == 0x%x, scsisigi = 0x%x\n",
948                        intstat, ahc_inb(ahc, SCSISIGI));
949                 break;
950         }
951 unpause:
952         /*
953          *  The sequencer is paused immediately on
954          *  a SEQINT, so we should restart it when
955          *  we're done.
956          */
957         ahc_unpause(ahc);
958 }
959
960 void
961 ahc_handle_scsiint(struct ahc_softc *ahc, u_int intstat)
962 {
963         u_int   scb_index;
964         u_int   status0;
965         u_int   status;
966         struct  scb *scb;
967         char    cur_channel;
968         char    intr_channel;
969
970         if ((ahc->features & AHC_TWIN) != 0
971          && ((ahc_inb(ahc, SBLKCTL) & SELBUSB) != 0))
972                 cur_channel = 'B';
973         else
974                 cur_channel = 'A';
975         intr_channel = cur_channel;
976
977         if ((ahc->features & AHC_ULTRA2) != 0)
978                 status0 = ahc_inb(ahc, SSTAT0) & IOERR;
979         else
980                 status0 = 0;
981         status = ahc_inb(ahc, SSTAT1) & (SELTO|SCSIRSTI|BUSFREE|SCSIPERR);
982         if (status == 0 && status0 == 0) {
983                 if ((ahc->features & AHC_TWIN) != 0) {
984                         /* Try the other channel */
985                         ahc_outb(ahc, SBLKCTL, ahc_inb(ahc, SBLKCTL) ^ SELBUSB);
986                         status = ahc_inb(ahc, SSTAT1)
987                                & (SELTO|SCSIRSTI|BUSFREE|SCSIPERR);
988                         intr_channel = (cur_channel == 'A') ? 'B' : 'A';
989                 }
990                 if (status == 0) {
991                         kprintf("%s: Spurious SCSI interrupt\n", ahc_name(ahc));
992                         ahc_outb(ahc, CLRINT, CLRSCSIINT);
993                         ahc_unpause(ahc);
994                         return;
995                 }
996         }
997
998         /* Make sure the sequencer is in a safe location. */
999         ahc_clear_critical_section(ahc);
1000
1001         scb_index = ahc_inb(ahc, SCB_TAG);
1002         scb = ahc_lookup_scb(ahc, scb_index);
1003         if (scb != NULL
1004          && (ahc_inb(ahc, SEQ_FLAGS) & NOT_IDENTIFIED) != 0)
1005                 scb = NULL;
1006
1007         if ((ahc->features & AHC_ULTRA2) != 0
1008          && (status0 & IOERR) != 0) {
1009                 int now_lvd;
1010
1011                 now_lvd = ahc_inb(ahc, SBLKCTL) & ENAB40;
1012                 kprintf("%s: Transceiver State Has Changed to %s mode\n",
1013                        ahc_name(ahc), now_lvd ? "LVD" : "SE");
1014                 ahc_outb(ahc, CLRSINT0, CLRIOERR);
1015                 /*
1016                  * When transitioning to SE mode, the reset line
1017                  * glitches, triggering an arbitration bug in some
1018                  * Ultra2 controllers.  This bug is cleared when we
1019                  * assert the reset line.  Since a reset glitch has
1020                  * already occurred with this transition and a
1021                  * transceiver state change is handled just like
1022                  * a bus reset anyway, asserting the reset line
1023                  * ourselves is safe.
1024                  */
1025                 ahc_reset_channel(ahc, intr_channel,
1026                                  /*Initiate Reset*/now_lvd == 0);
1027         } else if ((status & SCSIRSTI) != 0) {
1028                 kprintf("%s: Someone reset channel %c\n",
1029                         ahc_name(ahc), intr_channel);
1030                 if (intr_channel != cur_channel)
1031                         ahc_outb(ahc, SBLKCTL, ahc_inb(ahc, SBLKCTL) ^ SELBUSB);
1032                 ahc_reset_channel(ahc, intr_channel, /*Initiate Reset*/FALSE);
1033         } else if ((status & SCSIPERR) != 0) {
1034                 /*
1035                  * Determine the bus phase and queue an appropriate message.
1036                  * SCSIPERR is latched true as soon as a parity error
1037                  * occurs.  If the sequencer acked the transfer that
1038                  * caused the parity error and the currently presented
1039                  * transfer on the bus has correct parity, SCSIPERR will
1040                  * be cleared by CLRSCSIPERR.  Use this to determine if
1041                  * we should look at the last phase the sequencer recorded,
1042                  * or the current phase presented on the bus.
1043                  */
1044                 struct  ahc_devinfo devinfo;
1045                 u_int   mesg_out;
1046                 u_int   curphase;
1047                 u_int   errorphase;
1048                 u_int   lastphase;
1049                 u_int   scsirate;
1050                 u_int   i;
1051                 u_int   sstat2;
1052                 int     silent;
1053
1054                 lastphase = ahc_inb(ahc, LASTPHASE);
1055                 curphase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
1056                 sstat2 = ahc_inb(ahc, SSTAT2);
1057                 ahc_outb(ahc, CLRSINT1, CLRSCSIPERR);
1058                 /*
1059                  * For all phases save DATA, the sequencer won't
1060                  * automatically ack a byte that has a parity error
1061                  * in it.  So the only way that the current phase
1062                  * could be 'data-in' is if the parity error is for
1063                  * an already acked byte in the data phase.  During
1064                  * synchronous data-in transfers, we may actually
1065                  * ack bytes before latching the current phase in
1066                  * LASTPHASE, leading to the discrepancy between
1067                  * curphase and lastphase.
1068                  */
1069                 if ((ahc_inb(ahc, SSTAT1) & SCSIPERR) != 0
1070                  || curphase == P_DATAIN || curphase == P_DATAIN_DT)
1071                         errorphase = curphase;
1072                 else
1073                         errorphase = lastphase;
1074
1075                 for (i = 0; i < num_phases; i++) {
1076                         if (errorphase == ahc_phase_table[i].phase)
1077                                 break;
1078                 }
1079                 mesg_out = ahc_phase_table[i].mesg_out;
1080                 silent = FALSE;
1081                 if (scb != NULL) {
1082                         if (SCB_IS_SILENT(scb))
1083                                 silent = TRUE;
1084                         else
1085                                 ahc_print_path(ahc, scb);
1086                         scb->flags |= SCB_TRANSMISSION_ERROR;
1087                 } else
1088                         kprintf("%s:%c:%d: ", ahc_name(ahc), intr_channel,
1089                                SCSIID_TARGET(ahc, ahc_inb(ahc, SAVED_SCSIID)));
1090                 scsirate = ahc_inb(ahc, SCSIRATE);
1091                 if (silent == FALSE) {
1092                         kprintf("parity error detected %s. "
1093                                "SEQADDR(0x%x) SCSIRATE(0x%x)\n",
1094                                ahc_phase_table[i].phasemsg,
1095                                ahc_inw(ahc, SEQADDR0),
1096                                scsirate);
1097                         if ((ahc->features & AHC_DT) != 0) {
1098                                 if ((sstat2 & CRCVALERR) != 0)
1099                                         kprintf("\tCRC Value Mismatch\n");
1100                                 if ((sstat2 & CRCENDERR) != 0)
1101                                         kprintf("\tNo terminal CRC packet "
1102                                                "received\n");
1103                                 if ((sstat2 & CRCREQERR) != 0)
1104                                         kprintf("\tIllegal CRC packet "
1105                                                "request\n");
1106                                 if ((sstat2 & DUAL_EDGE_ERR) != 0)
1107                                         kprintf("\tUnexpected %sDT Data Phase\n",
1108                                                (scsirate & SINGLE_EDGE)
1109                                              ? "" : "non-");
1110                         }
1111                 }
1112
1113                 if ((ahc->features & AHC_DT) != 0
1114                  && (sstat2 & DUAL_EDGE_ERR) != 0) {
1115                         /*
1116                          * This error applies regardless of
1117                          * data direction, so ignore the value
1118                          * in the phase table.
1119                          */
1120                         mesg_out = MSG_INITIATOR_DET_ERR;
1121                 }
1122
1123                 /*
1124                  * We've set the hardware to assert ATN if we   
1125                  * get a parity error on "in" phases, so all we  
1126                  * need to do is stuff the message buffer with
1127                  * the appropriate message.  "In" phases have set
1128                  * mesg_out to something other than MSG_NOP.
1129                  */
1130                 if (mesg_out != MSG_NOOP) {
1131                         if (ahc->msg_type != MSG_TYPE_NONE)
1132                                 ahc->send_msg_perror = TRUE;
1133                         else
1134                                 ahc_outb(ahc, MSG_OUT, mesg_out);
1135                 }
1136                 /*
1137                  * Force a renegotiation with this target just in
1138                  * case we are out of sync for some external reason
1139                  * unknown (or unreported) by the target.
1140                  */
1141                 ahc_fetch_devinfo(ahc, &devinfo);
1142                 ahc_force_renegotiation(ahc, &devinfo);
1143
1144                 ahc_outb(ahc, CLRINT, CLRSCSIINT);
1145                 ahc_unpause(ahc);
1146         } else if ((status & SELTO) != 0) {
1147                 u_int   scbptr;
1148
1149                 /* Stop the selection */
1150                 ahc_outb(ahc, SCSISEQ, 0);
1151
1152                 /* No more pending messages */
1153                 ahc_clear_msg_state(ahc);
1154
1155                 /* Clear interrupt state */
1156                 ahc_outb(ahc, SIMODE1, ahc_inb(ahc, SIMODE1) & ~ENBUSFREE);
1157                 ahc_outb(ahc, CLRSINT1, CLRSELTIMEO|CLRBUSFREE|CLRSCSIPERR);
1158
1159                 /*
1160                  * Although the driver does not care about the
1161                  * 'Selection in Progress' status bit, the busy
1162                  * LED does.  SELINGO is only cleared by a successful
1163                  * selection, so we must manually clear it to insure
1164                  * the LED turns off just in case no future successful
1165                  * selections occur (e.g. no devices on the bus).
1166                  */
1167                 ahc_outb(ahc, CLRSINT0, CLRSELINGO);
1168
1169                 scbptr = ahc_inb(ahc, WAITING_SCBH);
1170                 ahc_outb(ahc, SCBPTR, scbptr);
1171                 scb_index = ahc_inb(ahc, SCB_TAG);
1172
1173                 scb = ahc_lookup_scb(ahc, scb_index);
1174                 if (scb == NULL) {
1175                         kprintf("%s: ahc_intr - referenced scb not "
1176                                "valid during SELTO scb(%d, %d)\n",
1177                                ahc_name(ahc), scbptr, scb_index);
1178                         ahc_dump_card_state(ahc);
1179                 } else {
1180                         struct ahc_devinfo devinfo;
1181 #ifdef AHC_DEBUG
1182                         if ((ahc_debug & AHC_SHOW_SELTO) != 0) {
1183                                 ahc_print_path(ahc, scb);
1184                                 kprintf("Saw Selection Timeout for SCB 0x%x\n",
1185                                        scb_index);
1186                         }
1187 #endif
1188                         ahc_scb_devinfo(ahc, &devinfo, scb);
1189                         aic_set_transaction_status(scb, CAM_SEL_TIMEOUT);
1190                         ahc_freeze_devq(ahc, scb);
1191
1192                         /*
1193                          * Cancel any pending transactions on the device
1194                          * now that it seems to be missing.  This will
1195                          * also revert us to async/narrow transfers until
1196                          * we can renegotiate with the device.
1197                          */
1198                         ahc_handle_devreset(ahc, &devinfo,
1199                                             CAM_SEL_TIMEOUT,
1200                                             "Selection Timeout",
1201                                             /*verbose_level*/1);
1202                 }
1203                 ahc_outb(ahc, CLRINT, CLRSCSIINT);
1204                 ahc_restart(ahc);
1205         } else if ((status & BUSFREE) != 0
1206                 && (ahc_inb(ahc, SIMODE1) & ENBUSFREE) != 0) {
1207                 struct  ahc_devinfo devinfo;
1208                 u_int   lastphase;
1209                 u_int   saved_scsiid;
1210                 u_int   saved_lun;
1211                 u_int   target;
1212                 u_int   initiator_role_id;
1213                 char    channel;
1214                 int     printerror;
1215
1216                 /*
1217                  * Clear our selection hardware as soon as possible.
1218                  * We may have an entry in the waiting Q for this target,
1219                  * that is affected by this busfree and we don't want to
1220                  * go about selecting the target while we handle the event.
1221                  */
1222                 ahc_outb(ahc, SCSISEQ,
1223                          ahc_inb(ahc, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP));
1224
1225                 /*
1226                  * Disable busfree interrupts and clear the busfree
1227                  * interrupt status.  We do this here so that several
1228                  * bus transactions occur prior to clearing the SCSIINT
1229                  * latch.  It can take a bit for the clearing to take effect.
1230                  */
1231                 ahc_outb(ahc, SIMODE1, ahc_inb(ahc, SIMODE1) & ~ENBUSFREE);
1232                 ahc_outb(ahc, CLRSINT1, CLRBUSFREE|CLRSCSIPERR);
1233
1234                 /*
1235                  * Look at what phase we were last in.
1236                  * If its message out, chances are pretty good
1237                  * that the busfree was in response to one of
1238                  * our abort requests.
1239                  */
1240                 lastphase = ahc_inb(ahc, LASTPHASE);
1241                 saved_scsiid = ahc_inb(ahc, SAVED_SCSIID);
1242                 saved_lun = ahc_inb(ahc, SAVED_LUN);
1243                 target = SCSIID_TARGET(ahc, saved_scsiid);
1244                 initiator_role_id = SCSIID_OUR_ID(saved_scsiid);
1245                 channel = SCSIID_CHANNEL(ahc, saved_scsiid);
1246                 ahc_compile_devinfo(&devinfo, initiator_role_id,
1247                                     target, saved_lun, channel, ROLE_INITIATOR);
1248                 printerror = 1;
1249
1250                 if (lastphase == P_MESGOUT) {
1251                         u_int tag;
1252
1253                         tag = SCB_LIST_NULL;
1254                         if (ahc_sent_msg(ahc, AHCMSG_1B, MSG_ABORT_TAG, TRUE)
1255                          || ahc_sent_msg(ahc, AHCMSG_1B, MSG_ABORT, TRUE)) {
1256                                 if (ahc->msgout_buf[ahc->msgout_index - 1]
1257                                  == MSG_ABORT_TAG)
1258                                         tag = scb->hscb->tag;
1259                                 ahc_print_path(ahc, scb);
1260                                 kprintf("SCB %d - Abort%s Completed.\n",
1261                                        scb->hscb->tag, tag == SCB_LIST_NULL ?
1262                                        "" : " Tag");
1263                                 ahc_abort_scbs(ahc, target, channel,
1264                                                saved_lun, tag,
1265                                                ROLE_INITIATOR,
1266                                                CAM_REQ_ABORTED);
1267                                 printerror = 0;
1268                         } else if (ahc_sent_msg(ahc, AHCMSG_1B,
1269                                                 MSG_BUS_DEV_RESET, TRUE)) {
1270 #if defined(__DragonFly__) || defined(__FreeBSD__)
1271                                 /*
1272                                  * Don't mark the user's request for this BDR
1273                                  * as completing with CAM_BDR_SENT.  CAM3
1274                                  * specifies CAM_REQ_CMP.
1275                                  */
1276                                 if (scb != NULL
1277                                  && scb->io_ctx->ccb_h.func_code== XPT_RESET_DEV
1278                                  && ahc_match_scb(ahc, scb, target, channel,
1279                                                   CAM_LUN_WILDCARD,
1280                                                   SCB_LIST_NULL,
1281                                                   ROLE_INITIATOR)) {
1282                                         aic_set_transaction_status(scb, CAM_REQ_CMP);
1283                                 }
1284 #endif
1285                                 ahc_compile_devinfo(&devinfo,
1286                                                     initiator_role_id,
1287                                                     target,
1288                                                     CAM_LUN_WILDCARD,
1289                                                     channel,
1290                                                     ROLE_INITIATOR);
1291                                 ahc_handle_devreset(ahc, &devinfo,
1292                                                     CAM_BDR_SENT,
1293                                                     "Bus Device Reset",
1294                                                     /*verbose_level*/0);
1295                                 printerror = 0;
1296                         } else if (ahc_sent_msg(ahc, AHCMSG_EXT,
1297                                                 MSG_EXT_PPR, FALSE)) {
1298                                 struct ahc_initiator_tinfo *tinfo;
1299                                 struct ahc_tmode_tstate *tstate;
1300
1301                                 /*
1302                                  * PPR Rejected.  Try non-ppr negotiation
1303                                  * and retry command.
1304                                  */
1305                                 tinfo = ahc_fetch_transinfo(ahc,
1306                                                             devinfo.channel,
1307                                                             devinfo.our_scsiid,
1308                                                             devinfo.target,
1309                                                             &tstate);
1310                                 tinfo->curr.transport_version = 2;
1311                                 tinfo->goal.transport_version = 2;
1312                                 tinfo->goal.ppr_options = 0;
1313                                 ahc_qinfifo_requeue_tail(ahc, scb);
1314                                 printerror = 0;
1315                         } else if (ahc_sent_msg(ahc, AHCMSG_EXT,
1316                                                 MSG_EXT_WDTR, FALSE)) {
1317                                 /*
1318                                  * Negotiation Rejected.  Go-narrow and
1319                                  * retry command.
1320                                  */
1321                                 ahc_set_width(ahc, &devinfo,
1322                                               MSG_EXT_WDTR_BUS_8_BIT,
1323                                               AHC_TRANS_CUR|AHC_TRANS_GOAL,
1324                                               /*paused*/TRUE);
1325                                 ahc_qinfifo_requeue_tail(ahc, scb);
1326                                 printerror = 0;
1327                         } else if (ahc_sent_msg(ahc, AHCMSG_EXT,
1328                                                 MSG_EXT_SDTR, FALSE)) {
1329                                 /*
1330                                  * Negotiation Rejected.  Go-async and
1331                                  * retry command.
1332                                  */
1333                                 ahc_set_syncrate(ahc, &devinfo,
1334                                                 /*syncrate*/NULL,
1335                                                 /*period*/0, /*offset*/0,
1336                                                 /*ppr_options*/0,
1337                                                 AHC_TRANS_CUR|AHC_TRANS_GOAL,
1338                                                 /*paused*/TRUE);
1339                                 ahc_qinfifo_requeue_tail(ahc, scb);
1340                                 printerror = 0;
1341                         }
1342                 }
1343                 if (printerror != 0) {
1344                         u_int i;
1345
1346                         if (scb != NULL) {
1347                                 u_int tag;
1348
1349                                 if ((scb->hscb->control & TAG_ENB) != 0)
1350                                         tag = scb->hscb->tag;
1351                                 else
1352                                         tag = SCB_LIST_NULL;
1353                                 ahc_print_path(ahc, scb);
1354                                 ahc_abort_scbs(ahc, target, channel,
1355                                                SCB_GET_LUN(scb), tag,
1356                                                ROLE_INITIATOR,
1357                                                CAM_UNEXP_BUSFREE);
1358                         } else {
1359                                 /*
1360                                  * We had not fully identified this connection,
1361                                  * so we cannot abort anything.
1362                                  */
1363                                 kprintf("%s: ", ahc_name(ahc));
1364                         }
1365                         for (i = 0; i < num_phases; i++) {
1366                                 if (lastphase == ahc_phase_table[i].phase)
1367                                         break;
1368                         }
1369                         if (lastphase != P_BUSFREE) {
1370                                 /*
1371                                  * Renegotiate with this device at the
1372                                  * next oportunity just in case this busfree
1373                                  * is due to a negotiation mismatch with the
1374                                  * device.
1375                                  */
1376                                 ahc_force_renegotiation(ahc, &devinfo);
1377                         }
1378                         kprintf("Unexpected busfree %s\n"
1379                                "SEQADDR == 0x%x\n",
1380                                ahc_phase_table[i].phasemsg,
1381                                ahc_inb(ahc, SEQADDR0)
1382                                 | (ahc_inb(ahc, SEQADDR1) << 8));
1383                 }
1384                 ahc_outb(ahc, CLRINT, CLRSCSIINT);
1385                 ahc_restart(ahc);
1386         } else {
1387                 kprintf("%s: Missing case in ahc_handle_scsiint. status = %x\n",
1388                        ahc_name(ahc), status);
1389                 ahc_outb(ahc, CLRINT, CLRSCSIINT);
1390         }
1391 }
1392
1393 /*
1394  * Force renegotiation to occur the next time we initiate
1395  * a command to the current device.
1396  */
1397 static void
1398 ahc_force_renegotiation(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
1399 {
1400         struct  ahc_initiator_tinfo *targ_info;
1401         struct  ahc_tmode_tstate *tstate;
1402
1403         targ_info = ahc_fetch_transinfo(ahc,
1404                                         devinfo->channel,
1405                                         devinfo->our_scsiid,
1406                                         devinfo->target,
1407                                         &tstate);
1408         ahc_update_neg_request(ahc, devinfo, tstate,
1409                                targ_info, AHC_NEG_IF_NON_ASYNC);
1410 }
1411
1412 #define AHC_MAX_STEPS 2000
1413 void
1414 ahc_clear_critical_section(struct ahc_softc *ahc)
1415 {
1416         int     stepping;
1417         int     steps;
1418         u_int   simode0;
1419         u_int   simode1;
1420
1421         if (ahc->num_critical_sections == 0)
1422                 return;
1423
1424         stepping = FALSE;
1425         steps = 0;
1426         simode0 = 0;
1427         simode1 = 0;
1428         for (;;) {
1429                 struct  cs *cs;
1430                 u_int   seqaddr;
1431                 u_int   i;
1432
1433                 seqaddr = ahc_inb(ahc, SEQADDR0)
1434                         | (ahc_inb(ahc, SEQADDR1) << 8);
1435
1436                 /*
1437                  * Seqaddr represents the next instruction to execute, 
1438                  * so we are really executing the instruction just
1439                  * before it.
1440                  */
1441                 cs = ahc->critical_sections;
1442                 for (i = 0; i < ahc->num_critical_sections; i++, cs++) {
1443                         
1444                         if (cs->begin < seqaddr && cs->end >= seqaddr)
1445                                 break;
1446                 }
1447
1448                 if (i == ahc->num_critical_sections)
1449                         break;
1450
1451                 if (steps > AHC_MAX_STEPS) {
1452                         kprintf("%s: Infinite loop in critical section\n",
1453                                ahc_name(ahc));
1454                         ahc_dump_card_state(ahc);
1455                         panic("critical section loop");
1456                 }
1457
1458                 steps++;
1459                 if (stepping == FALSE) {
1460
1461                         /*
1462                          * Disable all interrupt sources so that the
1463                          * sequencer will not be stuck by a pausing
1464                          * interrupt condition while we attempt to
1465                          * leave a critical section.
1466                          */
1467                         simode0 = ahc_inb(ahc, SIMODE0);
1468                         ahc_outb(ahc, SIMODE0, 0);
1469                         simode1 = ahc_inb(ahc, SIMODE1);
1470                         if ((ahc->features & AHC_DT) != 0)
1471                                 /*
1472                                  * On DT class controllers, we
1473                                  * use the enhanced busfree logic.
1474                                  * Unfortunately we cannot re-enable
1475                                  * busfree detection within the
1476                                  * current connection, so we must
1477                                  * leave it on while single stepping.
1478                                  */
1479                                 ahc_outb(ahc, SIMODE1, simode1 & ENBUSFREE);
1480                         else
1481                                 ahc_outb(ahc, SIMODE1, 0);
1482                         ahc_outb(ahc, CLRINT, CLRSCSIINT);
1483                         ahc_outb(ahc, SEQCTL, ahc->seqctl | STEP);
1484                         stepping = TRUE;
1485                 }
1486                 if ((ahc->features & AHC_DT) != 0) {
1487                         ahc_outb(ahc, CLRSINT1, CLRBUSFREE);
1488                         ahc_outb(ahc, CLRINT, CLRSCSIINT);
1489                 }
1490                 ahc_outb(ahc, HCNTRL, ahc->unpause);
1491                 while (!ahc_is_paused(ahc))
1492                         aic_delay(200);
1493         }
1494         if (stepping) {
1495                 ahc_outb(ahc, SIMODE0, simode0);
1496                 ahc_outb(ahc, SIMODE1, simode1);
1497                 ahc_outb(ahc, SEQCTL, ahc->seqctl);
1498         }
1499 }
1500
1501 /*
1502  * Clear any pending interrupt status.
1503  */
1504 void
1505 ahc_clear_intstat(struct ahc_softc *ahc)
1506 {
1507         /* Clear any interrupt conditions this may have caused */
1508         ahc_outb(ahc, CLRSINT1, CLRSELTIMEO|CLRATNO|CLRSCSIRSTI
1509                                 |CLRBUSFREE|CLRSCSIPERR|CLRPHASECHG|
1510                                 CLRREQINIT);
1511         ahc_flush_device_writes(ahc);
1512         ahc_outb(ahc, CLRSINT0, CLRSELDO|CLRSELDI|CLRSELINGO);
1513         ahc_flush_device_writes(ahc);
1514         ahc_outb(ahc, CLRINT, CLRSCSIINT);
1515         ahc_flush_device_writes(ahc);
1516 }
1517
1518 /**************************** Debugging Routines ******************************/
1519 #ifdef AHC_DEBUG
1520 uint32_t ahc_debug = AHC_DEBUG_OPTS;
1521 #endif
1522
1523 void
1524 ahc_print_scb(struct scb *scb)
1525 {
1526         int i;
1527
1528         struct hardware_scb *hscb = scb->hscb;
1529
1530         kprintf("scb:%p control:0x%x scsiid:0x%x lun:%d cdb_len:%d\n",
1531                (void *)scb,
1532                hscb->control,
1533                hscb->scsiid,
1534                hscb->lun,
1535                hscb->cdb_len);
1536         kprintf("Shared Data: ");
1537         for (i = 0; i < sizeof(hscb->shared_data.cdb); i++)
1538                 kprintf("%#02x", hscb->shared_data.cdb[i]);
1539         kprintf("        dataptr:%#x datacnt:%#x sgptr:%#x tag:%#x\n",
1540                 aic_le32toh(hscb->dataptr),
1541                 aic_le32toh(hscb->datacnt),
1542                 aic_le32toh(hscb->sgptr),
1543                 hscb->tag);
1544         if (scb->sg_count > 0) {
1545                 for (i = 0; i < scb->sg_count; i++) {
1546                         kprintf("sg[%d] - Addr 0x%x%x : Length %d\n",
1547                                i,
1548                                (aic_le32toh(scb->sg_list[i].len) >> 24
1549                                 & SG_HIGH_ADDR_BITS),
1550                                aic_le32toh(scb->sg_list[i].addr),
1551                                aic_le32toh(scb->sg_list[i].len));
1552                 }
1553         }
1554 }
1555
1556 /************************* Transfer Negotiation *******************************/
1557 /*
1558  * Allocate per target mode instance (ID we respond to as a target)
1559  * transfer negotiation data structures.
1560  */
1561 static struct ahc_tmode_tstate *
1562 ahc_alloc_tstate(struct ahc_softc *ahc, u_int scsi_id, char channel)
1563 {
1564         struct ahc_tmode_tstate *master_tstate;
1565         struct ahc_tmode_tstate *tstate;
1566         int i;
1567
1568         master_tstate = ahc->enabled_targets[ahc->our_id];
1569         if (channel == 'B') {
1570                 scsi_id += 8;
1571                 master_tstate = ahc->enabled_targets[ahc->our_id_b + 8];
1572         }
1573         if (ahc->enabled_targets[scsi_id] != NULL
1574          && ahc->enabled_targets[scsi_id] != master_tstate)
1575                 panic("%s: ahc_alloc_tstate - Target already allocated",
1576                       ahc_name(ahc));
1577         tstate = kmalloc(sizeof(*tstate), M_DEVBUF, M_INTWAIT);
1578
1579         /*
1580          * If we have allocated a master tstate, copy user settings from
1581          * the master tstate (taken from SRAM or the EEPROM) for this
1582          * channel, but reset our current and goal settings to async/narrow
1583          * until an initiator talks to us.
1584          */
1585         if (master_tstate != NULL) {
1586                 memcpy(tstate, master_tstate, sizeof(*tstate));
1587                 memset(tstate->enabled_luns, 0, sizeof(tstate->enabled_luns));
1588                 tstate->ultraenb = 0;
1589                 for (i = 0; i < AHC_NUM_TARGETS; i++) {
1590                         memset(&tstate->transinfo[i].curr, 0,
1591                               sizeof(tstate->transinfo[i].curr));
1592                         memset(&tstate->transinfo[i].goal, 0,
1593                               sizeof(tstate->transinfo[i].goal));
1594                 }
1595         } else
1596                 memset(tstate, 0, sizeof(*tstate));
1597         ahc->enabled_targets[scsi_id] = tstate;
1598         return (tstate);
1599 }
1600
1601 #ifdef AHC_TARGET_MODE
1602 /*
1603  * Free per target mode instance (ID we respond to as a target)
1604  * transfer negotiation data structures.
1605  */
1606 static void
1607 ahc_free_tstate(struct ahc_softc *ahc, u_int scsi_id, char channel, int force)
1608 {
1609         struct ahc_tmode_tstate *tstate;
1610
1611         /*
1612          * Don't clean up our "master" tstate.
1613          * It has our default user settings.
1614          */
1615         if (((channel == 'B' && scsi_id == ahc->our_id_b)
1616           || (channel == 'A' && scsi_id == ahc->our_id))
1617          && force == FALSE)
1618                 return;
1619
1620         if (channel == 'B')
1621                 scsi_id += 8;
1622         tstate = ahc->enabled_targets[scsi_id];
1623         if (tstate != NULL)
1624                 kfree(tstate, M_DEVBUF);
1625         ahc->enabled_targets[scsi_id] = NULL;
1626 }
1627 #endif
1628
1629 /*
1630  * Called when we have an active connection to a target on the bus,
1631  * this function finds the nearest syncrate to the input period limited
1632  * by the capabilities of the bus connectivity of and sync settings for
1633  * the target.
1634  */
1635 struct ahc_syncrate *
1636 ahc_devlimited_syncrate(struct ahc_softc *ahc,
1637                         struct ahc_initiator_tinfo *tinfo,
1638                         u_int *period, u_int *ppr_options, role_t role)
1639 {
1640         struct  ahc_transinfo *transinfo;
1641         u_int   maxsync;
1642
1643         if ((ahc->features & AHC_ULTRA2) != 0) {
1644                 if ((ahc_inb(ahc, SBLKCTL) & ENAB40) != 0
1645                  && (ahc_inb(ahc, SSTAT2) & EXP_ACTIVE) == 0) {
1646                         maxsync = AHC_SYNCRATE_DT;
1647                 } else {
1648                         maxsync = AHC_SYNCRATE_ULTRA;
1649                         /* Can't do DT on an SE bus */
1650                         *ppr_options &= ~MSG_EXT_PPR_DT_REQ;
1651                 }
1652         } else if ((ahc->features & AHC_ULTRA) != 0) {
1653                 maxsync = AHC_SYNCRATE_ULTRA;
1654         } else {
1655                 maxsync = AHC_SYNCRATE_FAST;
1656         }
1657         /*
1658          * Never allow a value higher than our current goal
1659          * period otherwise we may allow a target initiated
1660          * negotiation to go above the limit as set by the
1661          * user.  In the case of an initiator initiated
1662          * sync negotiation, we limit based on the user
1663          * setting.  This allows the system to still accept
1664          * incoming negotiations even if target initiated
1665          * negotiation is not performed.
1666          */
1667         if (role == ROLE_TARGET)
1668                 transinfo = &tinfo->user;
1669         else 
1670                 transinfo = &tinfo->goal;
1671         *ppr_options &= transinfo->ppr_options;
1672         if (transinfo->width == MSG_EXT_WDTR_BUS_8_BIT) {
1673                 maxsync = MAX(maxsync, AHC_SYNCRATE_ULTRA2);
1674                 *ppr_options &= ~MSG_EXT_PPR_DT_REQ;
1675         }
1676         if (transinfo->period == 0) {
1677                 *period = 0;
1678                 *ppr_options = 0;
1679                 return (NULL);
1680         }
1681         *period = MAX(*period, transinfo->period);
1682         return (ahc_find_syncrate(ahc, period, ppr_options, maxsync));
1683 }
1684
1685 /*
1686  * Look up the valid period to SCSIRATE conversion in our table.
1687  * Return the period and offset that should be sent to the target
1688  * if this was the beginning of an SDTR.
1689  */
1690 struct ahc_syncrate *
1691 ahc_find_syncrate(struct ahc_softc *ahc, u_int *period,
1692                   u_int *ppr_options, u_int maxsync)
1693 {
1694         struct ahc_syncrate *syncrate;
1695
1696         if ((ahc->features & AHC_DT) == 0)
1697                 *ppr_options &= ~MSG_EXT_PPR_DT_REQ;
1698
1699         /* Skip all DT only entries if DT is not available */
1700         if ((*ppr_options & MSG_EXT_PPR_DT_REQ) == 0
1701          && maxsync < AHC_SYNCRATE_ULTRA2)
1702                 maxsync = AHC_SYNCRATE_ULTRA2;
1703         
1704         for (syncrate = &ahc_syncrates[maxsync];
1705              syncrate->rate != NULL;
1706              syncrate++) {
1707
1708                 /*
1709                  * The Ultra2 table doesn't go as low
1710                  * as for the Fast/Ultra cards.
1711                  */
1712                 if ((ahc->features & AHC_ULTRA2) != 0
1713                  && (syncrate->sxfr_u2 == 0))
1714                         break;
1715
1716                 if (*period <= syncrate->period) {
1717                         /*
1718                          * When responding to a target that requests
1719                          * sync, the requested rate may fall between
1720                          * two rates that we can output, but still be
1721                          * a rate that we can receive.  Because of this,
1722                          * we want to respond to the target with
1723                          * the same rate that it sent to us even
1724                          * if the period we use to send data to it
1725                          * is lower.  Only lower the response period
1726                          * if we must.
1727                          */
1728                         if (syncrate == &ahc_syncrates[maxsync])
1729                                 *period = syncrate->period;
1730
1731                         /*
1732                          * At some speeds, we only support
1733                          * ST transfers.
1734                          */
1735                         if ((syncrate->sxfr_u2 & ST_SXFR) != 0)
1736                                 *ppr_options &= ~MSG_EXT_PPR_DT_REQ;
1737                         break;
1738                 }
1739         }
1740
1741         if ((*period == 0)
1742          || (syncrate->rate == NULL)
1743          || ((ahc->features & AHC_ULTRA2) != 0
1744           && (syncrate->sxfr_u2 == 0))) {
1745                 /* Use asynchronous transfers. */
1746                 *period = 0;
1747                 syncrate = NULL;
1748                 *ppr_options &= ~MSG_EXT_PPR_DT_REQ;
1749         }
1750         return (syncrate);
1751 }
1752
1753 /*
1754  * Convert from an entry in our syncrate table to the SCSI equivalent
1755  * sync "period" factor.
1756  */
1757 u_int
1758 ahc_find_period(struct ahc_softc *ahc, u_int scsirate, u_int maxsync)
1759 {
1760         struct ahc_syncrate *syncrate;
1761
1762         if ((ahc->features & AHC_ULTRA2) != 0)
1763                 scsirate &= SXFR_ULTRA2;
1764         else
1765                 scsirate &= SXFR;
1766
1767         syncrate = &ahc_syncrates[maxsync];
1768         while (syncrate->rate != NULL) {
1769
1770                 if ((ahc->features & AHC_ULTRA2) != 0) {
1771                         if (syncrate->sxfr_u2 == 0)
1772                                 break;
1773                         else if (scsirate == (syncrate->sxfr_u2 & SXFR_ULTRA2))
1774                                 return (syncrate->period);
1775                 } else if (scsirate == (syncrate->sxfr & SXFR)) {
1776                                 return (syncrate->period);
1777                 }
1778                 syncrate++;
1779         }
1780         return (0); /* async */
1781 }
1782
1783 /*
1784  * Truncate the given synchronous offset to a value the
1785  * current adapter type and syncrate are capable of.
1786  */
1787 void
1788 ahc_validate_offset(struct ahc_softc *ahc,
1789                     struct ahc_initiator_tinfo *tinfo,
1790                     struct ahc_syncrate *syncrate,
1791                     u_int *offset, int wide, role_t role)
1792 {
1793         u_int maxoffset;
1794
1795         /* Limit offset to what we can do */
1796         if (syncrate == NULL) {
1797                 maxoffset = 0;
1798         } else if ((ahc->features & AHC_ULTRA2) != 0) {
1799                 maxoffset = MAX_OFFSET_ULTRA2;
1800         } else {
1801                 if (wide)
1802                         maxoffset = MAX_OFFSET_16BIT;
1803                 else
1804                         maxoffset = MAX_OFFSET_8BIT;
1805         }
1806         *offset = MIN(*offset, maxoffset);
1807         if (tinfo != NULL) {
1808                 if (role == ROLE_TARGET)
1809                         *offset = MIN(*offset, tinfo->user.offset);
1810                 else
1811                         *offset = MIN(*offset, tinfo->goal.offset);
1812         }
1813 }
1814
1815 /*
1816  * Truncate the given transfer width parameter to a value the
1817  * current adapter type is capable of.
1818  */
1819 void
1820 ahc_validate_width(struct ahc_softc *ahc, struct ahc_initiator_tinfo *tinfo,
1821                    u_int *bus_width, role_t role)
1822 {
1823         switch (*bus_width) {
1824         default:
1825                 if (ahc->features & AHC_WIDE) {
1826                         /* Respond Wide */
1827                         *bus_width = MSG_EXT_WDTR_BUS_16_BIT;
1828                         break;
1829                 }
1830                 /* FALLTHROUGH */
1831         case MSG_EXT_WDTR_BUS_8_BIT:
1832                 *bus_width = MSG_EXT_WDTR_BUS_8_BIT;
1833                 break;
1834         }
1835         if (tinfo != NULL) {
1836                 if (role == ROLE_TARGET)
1837                         *bus_width = MIN(tinfo->user.width, *bus_width);
1838                 else
1839                         *bus_width = MIN(tinfo->goal.width, *bus_width);
1840         }
1841 }
1842
1843 /*
1844  * Update the bitmask of targets for which the controller should
1845  * negotiate with at the next convenient oportunity.  This currently
1846  * means the next time we send the initial identify messages for
1847  * a new transaction.
1848  */
1849 int
1850 ahc_update_neg_request(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
1851                        struct ahc_tmode_tstate *tstate,
1852                        struct ahc_initiator_tinfo *tinfo, ahc_neg_type neg_type)
1853 {
1854         u_int auto_negotiate_orig;
1855
1856         auto_negotiate_orig = tstate->auto_negotiate;
1857         if (neg_type == AHC_NEG_ALWAYS) {
1858                 /*
1859                  * Force our "current" settings to be
1860                  * unknown so that unless a bus reset
1861                  * occurs the need to renegotiate is
1862                  * recorded persistently.
1863                  */
1864                 if ((ahc->features & AHC_WIDE) != 0)
1865                         tinfo->curr.width = AHC_WIDTH_UNKNOWN;
1866                 tinfo->curr.period = AHC_PERIOD_UNKNOWN;
1867                 tinfo->curr.offset = AHC_OFFSET_UNKNOWN;
1868         }
1869         if (tinfo->curr.period != tinfo->goal.period
1870          || tinfo->curr.width != tinfo->goal.width
1871          || tinfo->curr.offset != tinfo->goal.offset
1872          || tinfo->curr.ppr_options != tinfo->goal.ppr_options
1873          || (neg_type == AHC_NEG_IF_NON_ASYNC
1874           && (tinfo->goal.offset != 0
1875            || tinfo->goal.width != MSG_EXT_WDTR_BUS_8_BIT
1876            || tinfo->goal.ppr_options != 0)))
1877                 tstate->auto_negotiate |= devinfo->target_mask;
1878         else
1879                 tstate->auto_negotiate &= ~devinfo->target_mask;
1880
1881         return (auto_negotiate_orig != tstate->auto_negotiate);
1882 }
1883
1884 /*
1885  * Update the user/goal/curr tables of synchronous negotiation
1886  * parameters as well as, in the case of a current or active update,
1887  * any data structures on the host controller.  In the case of an
1888  * active update, the specified target is currently talking to us on
1889  * the bus, so the transfer parameter update must take effect
1890  * immediately.
1891  */
1892 void
1893 ahc_set_syncrate(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
1894                  struct ahc_syncrate *syncrate, u_int period,
1895                  u_int offset, u_int ppr_options, u_int type, int paused)
1896 {
1897         struct  ahc_initiator_tinfo *tinfo;
1898         struct  ahc_tmode_tstate *tstate;
1899         u_int   old_period;
1900         u_int   old_offset;
1901         u_int   old_ppr;
1902         int     active;
1903         int     update_needed;
1904
1905         active = (type & AHC_TRANS_ACTIVE) == AHC_TRANS_ACTIVE;
1906         update_needed = 0;
1907
1908         if (syncrate == NULL) {
1909                 period = 0;
1910                 offset = 0;
1911         }
1912
1913         tinfo = ahc_fetch_transinfo(ahc, devinfo->channel, devinfo->our_scsiid,
1914                                     devinfo->target, &tstate);
1915
1916         if ((type & AHC_TRANS_USER) != 0) {
1917                 tinfo->user.period = period;
1918                 tinfo->user.offset = offset;
1919                 tinfo->user.ppr_options = ppr_options;
1920         }
1921
1922         if ((type & AHC_TRANS_GOAL) != 0) {
1923                 tinfo->goal.period = period;
1924                 tinfo->goal.offset = offset;
1925                 tinfo->goal.ppr_options = ppr_options;
1926         }
1927
1928         old_period = tinfo->curr.period;
1929         old_offset = tinfo->curr.offset;
1930         old_ppr    = tinfo->curr.ppr_options;
1931
1932         if ((type & AHC_TRANS_CUR) != 0
1933          && (old_period != period
1934           || old_offset != offset
1935           || old_ppr != ppr_options)) {
1936                 u_int   scsirate;
1937
1938                 update_needed++;
1939                 scsirate = tinfo->scsirate;
1940                 if ((ahc->features & AHC_ULTRA2) != 0) {
1941
1942                         scsirate &= ~(SXFR_ULTRA2|SINGLE_EDGE|ENABLE_CRC);
1943                         if (syncrate != NULL) {
1944                                 scsirate |= syncrate->sxfr_u2;
1945                                 if ((ppr_options & MSG_EXT_PPR_DT_REQ) != 0)
1946                                         scsirate |= ENABLE_CRC;
1947                                 else
1948                                         scsirate |= SINGLE_EDGE;
1949                         }
1950                 } else {
1951
1952                         scsirate &= ~(SXFR|SOFS);
1953                         /*
1954                          * Ensure Ultra mode is set properly for
1955                          * this target.
1956                          */
1957                         tstate->ultraenb &= ~devinfo->target_mask;
1958                         if (syncrate != NULL) {
1959                                 if (syncrate->sxfr & ULTRA_SXFR) {
1960                                         tstate->ultraenb |=
1961                                                 devinfo->target_mask;
1962                                 }
1963                                 scsirate |= syncrate->sxfr & SXFR;
1964                                 scsirate |= offset & SOFS;
1965                         }
1966                         if (active) {
1967                                 u_int sxfrctl0;
1968
1969                                 sxfrctl0 = ahc_inb(ahc, SXFRCTL0);
1970                                 sxfrctl0 &= ~FAST20;
1971                                 if (tstate->ultraenb & devinfo->target_mask)
1972                                         sxfrctl0 |= FAST20;
1973                                 ahc_outb(ahc, SXFRCTL0, sxfrctl0);
1974                         }
1975                 }
1976                 if (active) {
1977                         ahc_outb(ahc, SCSIRATE, scsirate);
1978                         if ((ahc->features & AHC_ULTRA2) != 0)
1979                                 ahc_outb(ahc, SCSIOFFSET, offset);
1980                 }
1981
1982                 tinfo->scsirate = scsirate;
1983                 tinfo->curr.period = period;
1984                 tinfo->curr.offset = offset;
1985                 tinfo->curr.ppr_options = ppr_options;
1986
1987                 ahc_send_async(ahc, devinfo->channel, devinfo->target,
1988                                CAM_LUN_WILDCARD, AC_TRANSFER_NEG, NULL);
1989                 if (bootverbose) {
1990                         if (offset != 0) {
1991                                 kprintf("%s: target %d synchronous at %sMHz%s, "
1992                                        "offset = 0x%x\n", ahc_name(ahc),
1993                                        devinfo->target, syncrate->rate,
1994                                        (ppr_options & MSG_EXT_PPR_DT_REQ)
1995                                        ? " DT" : "", offset);
1996                         } else {
1997                                 kprintf("%s: target %d using "
1998                                        "asynchronous transfers\n",
1999                                        ahc_name(ahc), devinfo->target);
2000                         }
2001                 }
2002         }
2003
2004         update_needed += ahc_update_neg_request(ahc, devinfo, tstate,
2005                                                 tinfo, AHC_NEG_TO_GOAL);
2006
2007         if (update_needed)
2008                 ahc_update_pending_scbs(ahc);
2009 }
2010
2011 /*
2012  * Update the user/goal/curr tables of wide negotiation
2013  * parameters as well as, in the case of a current or active update,
2014  * any data structures on the host controller.  In the case of an
2015  * active update, the specified target is currently talking to us on
2016  * the bus, so the transfer parameter update must take effect
2017  * immediately.
2018  */
2019 void
2020 ahc_set_width(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
2021               u_int width, u_int type, int paused)
2022 {
2023         struct  ahc_initiator_tinfo *tinfo;
2024         struct  ahc_tmode_tstate *tstate;
2025         u_int   oldwidth;
2026         int     active;
2027         int     update_needed;
2028
2029         active = (type & AHC_TRANS_ACTIVE) == AHC_TRANS_ACTIVE;
2030         update_needed = 0;
2031         tinfo = ahc_fetch_transinfo(ahc, devinfo->channel, devinfo->our_scsiid,
2032                                     devinfo->target, &tstate);
2033
2034         if ((type & AHC_TRANS_USER) != 0)
2035                 tinfo->user.width = width;
2036
2037         if ((type & AHC_TRANS_GOAL) != 0)
2038                 tinfo->goal.width = width;
2039
2040         oldwidth = tinfo->curr.width;
2041         if ((type & AHC_TRANS_CUR) != 0 && oldwidth != width) {
2042                 u_int   scsirate;
2043
2044                 update_needed++;
2045                 scsirate =  tinfo->scsirate;
2046                 scsirate &= ~WIDEXFER;
2047                 if (width == MSG_EXT_WDTR_BUS_16_BIT)
2048                         scsirate |= WIDEXFER;
2049
2050                 tinfo->scsirate = scsirate;
2051
2052                 if (active)
2053                         ahc_outb(ahc, SCSIRATE, scsirate);
2054
2055                 tinfo->curr.width = width;
2056
2057                 ahc_send_async(ahc, devinfo->channel, devinfo->target,
2058                                CAM_LUN_WILDCARD, AC_TRANSFER_NEG, NULL);
2059                 if (bootverbose) {
2060                         kprintf("%s: target %d using %dbit transfers\n",
2061                                ahc_name(ahc), devinfo->target,
2062                                8 * (0x01 << width));
2063                 }
2064         }
2065
2066         update_needed += ahc_update_neg_request(ahc, devinfo, tstate,
2067                                                 tinfo, AHC_NEG_TO_GOAL);
2068         if (update_needed)
2069                 ahc_update_pending_scbs(ahc);
2070 }
2071
2072 /*
2073  * Update the current state of tagged queuing for a given target.
2074  */
2075 void
2076 ahc_set_tags(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
2077              ahc_queue_alg alg)
2078 {
2079         ahc_platform_set_tags(ahc, devinfo, alg);
2080         ahc_send_async(ahc, devinfo->channel, devinfo->target,
2081                        devinfo->lun, AC_TRANSFER_NEG, &alg);
2082 }
2083
2084 /*
2085  * When the transfer settings for a connection change, update any
2086  * in-transit SCBs to contain the new data so the hardware will
2087  * be set correctly during future (re)selections.
2088  */
2089 static void
2090 ahc_update_pending_scbs(struct ahc_softc *ahc)
2091 {
2092         struct  scb *pending_scb;
2093         int     pending_scb_count;
2094         int     i;
2095         int     paused;
2096         u_int   saved_scbptr;
2097
2098         /*
2099          * Traverse the pending SCB list and ensure that all of the
2100          * SCBs there have the proper settings.
2101          */
2102         pending_scb_count = 0;
2103         LIST_FOREACH(pending_scb, &ahc->pending_scbs, pending_links) {
2104                 struct ahc_devinfo devinfo;
2105                 struct hardware_scb *pending_hscb;
2106                 struct ahc_initiator_tinfo *tinfo;
2107                 struct ahc_tmode_tstate *tstate;
2108
2109                 ahc_scb_devinfo(ahc, &devinfo, pending_scb);
2110                 tinfo = ahc_fetch_transinfo(ahc, devinfo.channel,
2111                                             devinfo.our_scsiid,
2112                                             devinfo.target, &tstate);
2113                 pending_hscb = pending_scb->hscb;
2114                 pending_hscb->control &= ~ULTRAENB;
2115                 if ((tstate->ultraenb & devinfo.target_mask) != 0)
2116                         pending_hscb->control |= ULTRAENB;
2117                 pending_hscb->scsirate = tinfo->scsirate;
2118                 pending_hscb->scsioffset = tinfo->curr.offset;
2119                 if ((tstate->auto_negotiate & devinfo.target_mask) == 0
2120                  && (pending_scb->flags & SCB_AUTO_NEGOTIATE) != 0) {
2121                         pending_scb->flags &= ~SCB_AUTO_NEGOTIATE;
2122                         pending_hscb->control &= ~MK_MESSAGE;
2123                 }
2124                 ahc_sync_scb(ahc, pending_scb,
2125                              BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
2126                 pending_scb_count++;
2127         }
2128
2129         if (pending_scb_count == 0)
2130                 return;
2131
2132         if (ahc_is_paused(ahc)) {
2133                 paused = 1;
2134         } else {
2135                 paused = 0;
2136                 ahc_pause(ahc);
2137         }
2138
2139         saved_scbptr = ahc_inb(ahc, SCBPTR);
2140         /* Ensure that the hscbs down on the card match the new information */
2141         for (i = 0; i < ahc->scb_data->maxhscbs; i++) {
2142                 struct  hardware_scb *pending_hscb;
2143                 u_int   control;
2144                 u_int   scb_tag;
2145
2146                 ahc_outb(ahc, SCBPTR, i);
2147                 scb_tag = ahc_inb(ahc, SCB_TAG);
2148                 pending_scb = ahc_lookup_scb(ahc, scb_tag);
2149                 if (pending_scb == NULL)
2150                         continue;
2151
2152                 pending_hscb = pending_scb->hscb;
2153                 control = ahc_inb(ahc, SCB_CONTROL);
2154                 control &= ~(ULTRAENB|MK_MESSAGE);
2155                 control |= pending_hscb->control & (ULTRAENB|MK_MESSAGE);
2156                 ahc_outb(ahc, SCB_CONTROL, control);
2157                 ahc_outb(ahc, SCB_SCSIRATE, pending_hscb->scsirate);
2158                 ahc_outb(ahc, SCB_SCSIOFFSET, pending_hscb->scsioffset);
2159         }
2160         ahc_outb(ahc, SCBPTR, saved_scbptr);
2161
2162         if (paused == 0)
2163                 ahc_unpause(ahc);
2164 }
2165
2166 /**************************** Pathing Information *****************************/
2167 static void
2168 ahc_fetch_devinfo(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
2169 {
2170         u_int   saved_scsiid;
2171         role_t  role;
2172         int     our_id;
2173
2174         if (ahc_inb(ahc, SSTAT0) & TARGET)
2175                 role = ROLE_TARGET;
2176         else
2177                 role = ROLE_INITIATOR;
2178
2179         if (role == ROLE_TARGET
2180          && (ahc->features & AHC_MULTI_TID) != 0
2181          && (ahc_inb(ahc, SEQ_FLAGS)
2182            & (CMDPHASE_PENDING|TARG_CMD_PENDING|NO_DISCONNECT)) != 0) {
2183                 /* We were selected, so pull our id from TARGIDIN */
2184                 our_id = ahc_inb(ahc, TARGIDIN) & OID;
2185         } else if ((ahc->features & AHC_ULTRA2) != 0)
2186                 our_id = ahc_inb(ahc, SCSIID_ULTRA2) & OID;
2187         else
2188                 our_id = ahc_inb(ahc, SCSIID) & OID;
2189
2190         saved_scsiid = ahc_inb(ahc, SAVED_SCSIID);
2191         ahc_compile_devinfo(devinfo,
2192                             our_id,
2193                             SCSIID_TARGET(ahc, saved_scsiid),
2194                             ahc_inb(ahc, SAVED_LUN),
2195                             SCSIID_CHANNEL(ahc, saved_scsiid),
2196                             role);
2197 }
2198
2199 struct ahc_phase_table_entry*
2200 ahc_lookup_phase_entry(int phase)
2201 {
2202         struct ahc_phase_table_entry *entry;
2203         struct ahc_phase_table_entry *last_entry;
2204
2205         /*
2206          * num_phases doesn't include the default entry which
2207          * will be returned if the phase doesn't match.
2208          */
2209         last_entry = &ahc_phase_table[num_phases];
2210         for (entry = ahc_phase_table; entry < last_entry; entry++) {
2211                 if (phase == entry->phase)
2212                         break;
2213         }
2214         return (entry);
2215 }
2216
2217 void
2218 ahc_compile_devinfo(struct ahc_devinfo *devinfo, u_int our_id, u_int target,
2219                     u_int lun, char channel, role_t role)
2220 {
2221         devinfo->our_scsiid = our_id;
2222         devinfo->target = target;
2223         devinfo->lun = lun;
2224         devinfo->target_offset = target;
2225         devinfo->channel = channel;
2226         devinfo->role = role;
2227         if (channel == 'B')
2228                 devinfo->target_offset += 8;
2229         devinfo->target_mask = (0x01 << devinfo->target_offset);
2230 }
2231
2232 void
2233 ahc_print_devinfo(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
2234 {
2235         kprintf("%s:%c:%d:%d: ", ahc_name(ahc), devinfo->channel,
2236                devinfo->target, devinfo->lun);
2237 }
2238
2239 static void
2240 ahc_scb_devinfo(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
2241                 struct scb *scb)
2242 {
2243         role_t  role;
2244         int     our_id;
2245
2246         our_id = SCSIID_OUR_ID(scb->hscb->scsiid);
2247         role = ROLE_INITIATOR;
2248         if ((scb->flags & SCB_TARGET_SCB) != 0)
2249                 role = ROLE_TARGET;
2250         ahc_compile_devinfo(devinfo, our_id, SCB_GET_TARGET(ahc, scb),
2251                             SCB_GET_LUN(scb), SCB_GET_CHANNEL(ahc, scb), role);
2252 }
2253
2254
2255 /************************ Message Phase Processing ****************************/
2256 static void
2257 ahc_assert_atn(struct ahc_softc *ahc)
2258 {
2259         u_int scsisigo;
2260
2261         scsisigo = ATNO;
2262         if ((ahc->features & AHC_DT) == 0)
2263                 scsisigo |= ahc_inb(ahc, SCSISIGI);
2264         ahc_outb(ahc, SCSISIGO, scsisigo);
2265 }
2266
2267 /*
2268  * When an initiator transaction with the MK_MESSAGE flag either reconnects
2269  * or enters the initial message out phase, we are interrupted.  Fill our
2270  * outgoing message buffer with the appropriate message and beging handing
2271  * the message phase(s) manually.
2272  */
2273 static void
2274 ahc_setup_initiator_msgout(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
2275                            struct scb *scb)
2276 {
2277         /*
2278          * To facilitate adding multiple messages together,
2279          * each routine should increment the index and len
2280          * variables instead of setting them explicitly.
2281          */
2282         ahc->msgout_index = 0;
2283         ahc->msgout_len = 0;
2284
2285         if ((scb->flags & SCB_DEVICE_RESET) == 0
2286          && ahc_inb(ahc, MSG_OUT) == MSG_IDENTIFYFLAG) {
2287                 u_int identify_msg;
2288
2289                 identify_msg = MSG_IDENTIFYFLAG | SCB_GET_LUN(scb);
2290                 if ((scb->hscb->control & DISCENB) != 0)
2291                         identify_msg |= MSG_IDENTIFY_DISCFLAG;
2292                 ahc->msgout_buf[ahc->msgout_index++] = identify_msg;
2293                 ahc->msgout_len++;
2294
2295                 if ((scb->hscb->control & TAG_ENB) != 0) {
2296                         ahc->msgout_buf[ahc->msgout_index++] =
2297                             scb->hscb->control & (TAG_ENB|SCB_TAG_TYPE);
2298                         ahc->msgout_buf[ahc->msgout_index++] = scb->hscb->tag;
2299                         ahc->msgout_len += 2;
2300                 }
2301         }
2302
2303         if (scb->flags & SCB_DEVICE_RESET) {
2304                 ahc->msgout_buf[ahc->msgout_index++] = MSG_BUS_DEV_RESET;
2305                 ahc->msgout_len++;
2306                 ahc_print_path(ahc, scb);
2307                 kprintf("Bus Device Reset Message Sent\n");
2308                 /*
2309                  * Clear our selection hardware in advance of
2310                  * the busfree.  We may have an entry in the waiting
2311                  * Q for this target, and we don't want to go about
2312                  * selecting while we handle the busfree and blow it
2313                  * away.
2314                  */
2315                 ahc_outb(ahc, SCSISEQ, (ahc_inb(ahc, SCSISEQ) & ~ENSELO));
2316         } else if ((scb->flags & SCB_ABORT) != 0) {
2317                 if ((scb->hscb->control & TAG_ENB) != 0)
2318                         ahc->msgout_buf[ahc->msgout_index++] = MSG_ABORT_TAG;
2319                 else
2320                         ahc->msgout_buf[ahc->msgout_index++] = MSG_ABORT;
2321                 ahc->msgout_len++;
2322                 ahc_print_path(ahc, scb);
2323                 kprintf("Abort%s Message Sent\n",
2324                        (scb->hscb->control & TAG_ENB) != 0 ? " Tag" : "");
2325                 /*
2326                  * Clear our selection hardware in advance of
2327                  * the busfree.  We may have an entry in the waiting
2328                  * Q for this target, and we don't want to go about
2329                  * selecting while we handle the busfree and blow it
2330                  * away.
2331                  */
2332                 ahc_outb(ahc, SCSISEQ, (ahc_inb(ahc, SCSISEQ) & ~ENSELO));
2333         } else if ((scb->flags & (SCB_AUTO_NEGOTIATE|SCB_NEGOTIATE)) != 0) {
2334                 ahc_build_transfer_msg(ahc, devinfo);
2335         } else {
2336                 kprintf("ahc_intr: AWAITING_MSG for an SCB that "
2337                        "does not have a waiting message\n");
2338                 kprintf("SCSIID = %x, target_mask = %x\n", scb->hscb->scsiid,
2339                        devinfo->target_mask);
2340                 panic("SCB = %d, SCB Control = %x, MSG_OUT = %x "
2341                       "SCB flags = %x", scb->hscb->tag, scb->hscb->control,
2342                       ahc_inb(ahc, MSG_OUT), scb->flags);
2343         }
2344
2345         /*
2346          * Clear the MK_MESSAGE flag from the SCB so we aren't
2347          * asked to send this message again.
2348          */
2349         ahc_outb(ahc, SCB_CONTROL, ahc_inb(ahc, SCB_CONTROL) & ~MK_MESSAGE);
2350         scb->hscb->control &= ~MK_MESSAGE;
2351         ahc->msgout_index = 0;
2352         ahc->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
2353 }
2354
2355 /*
2356  * Build an appropriate transfer negotiation message for the
2357  * currently active target.
2358  */
2359 static void
2360 ahc_build_transfer_msg(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
2361 {
2362         /*
2363          * We need to initiate transfer negotiations.
2364          * If our current and goal settings are identical,
2365          * we want to renegotiate due to a check condition.
2366          */
2367         struct  ahc_initiator_tinfo *tinfo;
2368         struct  ahc_tmode_tstate *tstate;
2369         struct  ahc_syncrate *rate;
2370         int     dowide;
2371         int     dosync;
2372         int     doppr;
2373         u_int   period;
2374         u_int   ppr_options;
2375         u_int   offset;
2376
2377         tinfo = ahc_fetch_transinfo(ahc, devinfo->channel, devinfo->our_scsiid,
2378                                     devinfo->target, &tstate);
2379         /*
2380          * Filter our period based on the current connection.
2381          * If we can't perform DT transfers on this segment (not in LVD
2382          * mode for instance), then our decision to issue a PPR message
2383          * may change.
2384          */
2385         period = tinfo->goal.period;
2386         offset = tinfo->goal.offset;
2387         ppr_options = tinfo->goal.ppr_options;
2388         /* Target initiated PPR is not allowed in the SCSI spec */
2389         if (devinfo->role == ROLE_TARGET)
2390                 ppr_options = 0;
2391         rate = ahc_devlimited_syncrate(ahc, tinfo, &period,
2392                                        &ppr_options, devinfo->role);
2393         dowide = tinfo->curr.width != tinfo->goal.width;
2394         dosync = tinfo->curr.offset != offset || tinfo->curr.period != period;
2395         /*
2396          * Only use PPR if we have options that need it, even if the device
2397          * claims to support it.  There might be an expander in the way
2398          * that doesn't.
2399          */
2400         doppr = ppr_options != 0;
2401
2402         if (!dowide && !dosync && !doppr) {
2403                 dowide = tinfo->goal.width != MSG_EXT_WDTR_BUS_8_BIT;
2404                 dosync = tinfo->goal.offset != 0;
2405         }
2406
2407         if (!dowide && !dosync && !doppr) {
2408                 /*
2409                  * Force async with a WDTR message if we have a wide bus,
2410                  * or just issue an SDTR with a 0 offset.
2411                  */
2412                 if ((ahc->features & AHC_WIDE) != 0)
2413                         dowide = 1;
2414                 else
2415                         dosync = 1;
2416
2417                 if (bootverbose) {
2418                         ahc_print_devinfo(ahc, devinfo);
2419                         kprintf("Ensuring async\n");
2420                 }
2421         }
2422
2423         /* Target initiated PPR is not allowed in the SCSI spec */
2424         if (devinfo->role == ROLE_TARGET)
2425                 doppr = 0;
2426
2427         /*
2428          * Both the PPR message and SDTR message require the
2429          * goal syncrate to be limited to what the target device
2430          * is capable of handling (based on whether an LVD->SE
2431          * expander is on the bus), so combine these two cases.
2432          * Regardless, guarantee that if we are using WDTR and SDTR
2433          * messages that WDTR comes first.
2434          */
2435         if (doppr || (dosync && !dowide)) {
2436
2437                 offset = tinfo->goal.offset;
2438                 ahc_validate_offset(ahc, tinfo, rate, &offset,
2439                                     doppr ? tinfo->goal.width
2440                                           : tinfo->curr.width,
2441                                     devinfo->role);
2442                 if (doppr) {
2443                         ahc_construct_ppr(ahc, devinfo, period, offset,
2444                                           tinfo->goal.width, ppr_options);
2445                 } else {
2446                         ahc_construct_sdtr(ahc, devinfo, period, offset);
2447                 }
2448         } else {
2449                 ahc_construct_wdtr(ahc, devinfo, tinfo->goal.width);
2450         }
2451 }
2452
2453 /*
2454  * Build a synchronous negotiation message in our message
2455  * buffer based on the input parameters.
2456  */
2457 static void
2458 ahc_construct_sdtr(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
2459                    u_int period, u_int offset)
2460 {
2461         if (offset == 0)
2462                 period = AHC_ASYNC_XFER_PERIOD;
2463         ahc->msgout_buf[ahc->msgout_index++] = MSG_EXTENDED;
2464         ahc->msgout_buf[ahc->msgout_index++] = MSG_EXT_SDTR_LEN;
2465         ahc->msgout_buf[ahc->msgout_index++] = MSG_EXT_SDTR;
2466         ahc->msgout_buf[ahc->msgout_index++] = period;
2467         ahc->msgout_buf[ahc->msgout_index++] = offset;
2468         ahc->msgout_len += 5;
2469         if (bootverbose) {
2470                 kprintf("(%s:%c:%d:%d): Sending SDTR period %x, offset %x\n",
2471                        ahc_name(ahc), devinfo->channel, devinfo->target,
2472                        devinfo->lun, period, offset);
2473         }
2474 }
2475
2476 /*
2477  * Build a wide negotiation message in our message
2478  * buffer based on the input parameters.
2479  */
2480 static void
2481 ahc_construct_wdtr(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
2482                    u_int bus_width)
2483 {
2484         ahc->msgout_buf[ahc->msgout_index++] = MSG_EXTENDED;
2485         ahc->msgout_buf[ahc->msgout_index++] = MSG_EXT_WDTR_LEN;
2486         ahc->msgout_buf[ahc->msgout_index++] = MSG_EXT_WDTR;
2487         ahc->msgout_buf[ahc->msgout_index++] = bus_width;
2488         ahc->msgout_len += 4;
2489         if (bootverbose) {
2490                 kprintf("(%s:%c:%d:%d): Sending WDTR %x\n",
2491                        ahc_name(ahc), devinfo->channel, devinfo->target,
2492                        devinfo->lun, bus_width);
2493         }
2494 }
2495
2496 /*
2497  * Build a parallel protocol request message in our message
2498  * buffer based on the input parameters.
2499  */
2500 static void
2501 ahc_construct_ppr(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
2502                   u_int period, u_int offset, u_int bus_width,
2503                   u_int ppr_options)
2504 {
2505         if (offset == 0)
2506                 period = AHC_ASYNC_XFER_PERIOD;
2507         ahc->msgout_buf[ahc->msgout_index++] = MSG_EXTENDED;
2508         ahc->msgout_buf[ahc->msgout_index++] = MSG_EXT_PPR_LEN;
2509         ahc->msgout_buf[ahc->msgout_index++] = MSG_EXT_PPR;
2510         ahc->msgout_buf[ahc->msgout_index++] = period;
2511         ahc->msgout_buf[ahc->msgout_index++] = 0;
2512         ahc->msgout_buf[ahc->msgout_index++] = offset;
2513         ahc->msgout_buf[ahc->msgout_index++] = bus_width;
2514         ahc->msgout_buf[ahc->msgout_index++] = ppr_options;
2515         ahc->msgout_len += 8;
2516         if (bootverbose) {
2517                 kprintf("(%s:%c:%d:%d): Sending PPR bus_width %x, period %x, "
2518                        "offset %x, ppr_options %x\n", ahc_name(ahc),
2519                        devinfo->channel, devinfo->target, devinfo->lun,
2520                        bus_width, period, offset, ppr_options);
2521         }
2522 }
2523
2524 /*
2525  * Clear any active message state.
2526  */
2527 static void
2528 ahc_clear_msg_state(struct ahc_softc *ahc)
2529 {
2530         ahc->msgout_len = 0;
2531         ahc->msgin_index = 0;
2532         ahc->msg_type = MSG_TYPE_NONE;
2533         if ((ahc_inb(ahc, SCSISIGI) & ATNI) != 0) {
2534                 /*
2535                  * The target didn't care to respond to our
2536                  * message request, so clear ATN.
2537                  */
2538                 ahc_outb(ahc, CLRSINT1, CLRATNO);
2539         }
2540         ahc_outb(ahc, MSG_OUT, MSG_NOOP);
2541         ahc_outb(ahc, SEQ_FLAGS2,
2542                  ahc_inb(ahc, SEQ_FLAGS2) & ~TARGET_MSG_PENDING);
2543 }
2544
2545 static void
2546 ahc_handle_proto_violation(struct ahc_softc *ahc)
2547 {
2548         struct  ahc_devinfo devinfo;
2549         struct  scb *scb;
2550         u_int   scbid;
2551         u_int   seq_flags;
2552         u_int   curphase;
2553         u_int   lastphase;
2554         int     found;
2555
2556         ahc_fetch_devinfo(ahc, &devinfo);
2557         scbid = ahc_inb(ahc, SCB_TAG);
2558         scb = ahc_lookup_scb(ahc, scbid);
2559         seq_flags = ahc_inb(ahc, SEQ_FLAGS);
2560         curphase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
2561         lastphase = ahc_inb(ahc, LASTPHASE);
2562         if ((seq_flags & NOT_IDENTIFIED) != 0) {
2563
2564                 /*
2565                  * The reconnecting target either did not send an
2566                  * identify message, or did, but we didn't find an SCB
2567                  * to match.
2568                  */
2569                 ahc_print_devinfo(ahc, &devinfo);
2570                 kprintf("Target did not send an IDENTIFY message. "
2571                        "LASTPHASE = 0x%x.\n", lastphase);
2572                 scb = NULL;
2573         } else if (scb == NULL) {
2574                 /*
2575                  * We don't seem to have an SCB active for this
2576                  * transaction.  Print an error and reset the bus.
2577                  */
2578                 ahc_print_devinfo(ahc, &devinfo);
2579                 kprintf("No SCB found during protocol violation\n");
2580                 goto proto_violation_reset;
2581         } else {
2582                 aic_set_transaction_status(scb, CAM_SEQUENCE_FAIL);
2583                 if ((seq_flags & NO_CDB_SENT) != 0) {
2584                         ahc_print_path(ahc, scb);
2585                         kprintf("No or incomplete CDB sent to device.\n");
2586                 } else if ((ahc_inb(ahc, SCB_CONTROL) & STATUS_RCVD) == 0) {
2587                         /*
2588                          * The target never bothered to provide status to
2589                          * us prior to completing the command.  Since we don't
2590                          * know the disposition of this command, we must attempt
2591                          * to abort it.  Assert ATN and prepare to send an abort
2592                          * message.
2593                          */
2594                         ahc_print_path(ahc, scb);
2595                         kprintf("Completed command without status.\n");
2596                 } else {
2597                         ahc_print_path(ahc, scb);
2598                         kprintf("Unknown protocol violation.\n");
2599                         ahc_dump_card_state(ahc);
2600                 }
2601         }
2602         if ((lastphase & ~P_DATAIN_DT) == 0
2603          || lastphase == P_COMMAND) {
2604 proto_violation_reset:
2605                 /*
2606                  * Target either went directly to data/command
2607                  * phase or didn't respond to our ATN.
2608                  * The only safe thing to do is to blow
2609                  * it away with a bus reset.
2610                  */
2611                 found = ahc_reset_channel(ahc, 'A', TRUE);
2612                 kprintf("%s: Issued Channel %c Bus Reset. "
2613                        "%d SCBs aborted\n", ahc_name(ahc), 'A', found);
2614         } else {
2615                 /*
2616                  * Leave the selection hardware off in case
2617                  * this abort attempt will affect yet to
2618                  * be sent commands.
2619                  */
2620                 ahc_outb(ahc, SCSISEQ,
2621                          ahc_inb(ahc, SCSISEQ) & ~ENSELO);
2622                 ahc_assert_atn(ahc);
2623                 ahc_outb(ahc, MSG_OUT, HOST_MSG);
2624                 if (scb == NULL) {
2625                         ahc_print_devinfo(ahc, &devinfo);
2626                         ahc->msgout_buf[0] = MSG_ABORT_TASK;
2627                         ahc->msgout_len = 1;
2628                         ahc->msgout_index = 0;
2629                         ahc->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
2630                 } else {
2631                         ahc_print_path(ahc, scb);
2632                         scb->flags |= SCB_ABORT;
2633                 }
2634                 kprintf("Protocol violation %s.  Attempting to abort.\n",
2635                        ahc_lookup_phase_entry(curphase)->phasemsg);
2636         }
2637 }
2638
2639 /*
2640  * Manual message loop handler.
2641  */
2642 static void
2643 ahc_handle_message_phase(struct ahc_softc *ahc)
2644
2645         struct  ahc_devinfo devinfo;
2646         u_int   bus_phase;
2647         int     end_session;
2648
2649         ahc_fetch_devinfo(ahc, &devinfo);
2650         end_session = FALSE;
2651         bus_phase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
2652
2653 reswitch:
2654         switch (ahc->msg_type) {
2655         case MSG_TYPE_INITIATOR_MSGOUT:
2656         {
2657                 int lastbyte;
2658                 int phasemis;
2659                 int msgdone;
2660
2661                 if (ahc->msgout_len == 0)
2662                         panic("HOST_MSG_LOOP interrupt with no active message");
2663
2664 #ifdef AHC_DEBUG
2665                 if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
2666                         ahc_print_devinfo(ahc, &devinfo);
2667                         kprintf("INITIATOR_MSG_OUT");
2668                 }
2669 #endif
2670                 phasemis = bus_phase != P_MESGOUT;
2671                 if (phasemis) {
2672 #ifdef AHC_DEBUG
2673                         if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
2674                                 kprintf(" PHASEMIS %s\n",
2675                                        ahc_lookup_phase_entry(bus_phase)
2676                                                              ->phasemsg);
2677                         }
2678 #endif
2679                         if (bus_phase == P_MESGIN) {
2680                                 /*
2681                                  * Change gears and see if
2682                                  * this messages is of interest to
2683                                  * us or should be passed back to
2684                                  * the sequencer.
2685                                  */
2686                                 ahc_outb(ahc, CLRSINT1, CLRATNO);
2687                                 ahc->send_msg_perror = FALSE;
2688                                 ahc->msg_type = MSG_TYPE_INITIATOR_MSGIN;
2689                                 ahc->msgin_index = 0;
2690                                 goto reswitch;
2691                         }
2692                         end_session = TRUE;
2693                         break;
2694                 }
2695
2696                 if (ahc->send_msg_perror) {
2697                         ahc_outb(ahc, CLRSINT1, CLRATNO);
2698                         ahc_outb(ahc, CLRSINT1, CLRREQINIT);
2699 #ifdef AHC_DEBUG
2700                         if ((ahc_debug & AHC_SHOW_MESSAGES) != 0)
2701                                 kprintf(" byte 0x%x\n", ahc->send_msg_perror);
2702 #endif
2703                         ahc_outb(ahc, SCSIDATL, MSG_PARITY_ERROR);
2704                         break;
2705                 }
2706
2707                 msgdone = ahc->msgout_index == ahc->msgout_len;
2708                 if (msgdone) {
2709                         /*
2710                          * The target has requested a retry.
2711                          * Re-assert ATN, reset our message index to
2712                          * 0, and try again.
2713                          */
2714                         ahc->msgout_index = 0;
2715                         ahc_assert_atn(ahc);
2716                 }
2717
2718                 lastbyte = ahc->msgout_index == (ahc->msgout_len - 1);
2719                 if (lastbyte) {
2720                         /* Last byte is signified by dropping ATN */
2721                         ahc_outb(ahc, CLRSINT1, CLRATNO);
2722                 }
2723
2724                 /*
2725                  * Clear our interrupt status and present
2726                  * the next byte on the bus.
2727                  */
2728                 ahc_outb(ahc, CLRSINT1, CLRREQINIT);
2729 #ifdef AHC_DEBUG
2730                 if ((ahc_debug & AHC_SHOW_MESSAGES) != 0)
2731                         kprintf(" byte 0x%x\n",
2732                                ahc->msgout_buf[ahc->msgout_index]);
2733 #endif
2734                 ahc_outb(ahc, SCSIDATL, ahc->msgout_buf[ahc->msgout_index++]);
2735                 break;
2736         }
2737         case MSG_TYPE_INITIATOR_MSGIN:
2738         {
2739                 int phasemis;
2740                 int message_done;
2741
2742 #ifdef AHC_DEBUG
2743                 if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
2744                         ahc_print_devinfo(ahc, &devinfo);
2745                         kprintf("INITIATOR_MSG_IN");
2746                 }
2747 #endif
2748                 phasemis = bus_phase != P_MESGIN;
2749                 if (phasemis) {
2750 #ifdef AHC_DEBUG
2751                         if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
2752                                 kprintf(" PHASEMIS %s\n",
2753                                        ahc_lookup_phase_entry(bus_phase)
2754                                                              ->phasemsg);
2755                         }
2756 #endif
2757                         ahc->msgin_index = 0;
2758                         if (bus_phase == P_MESGOUT
2759                          && (ahc->send_msg_perror == TRUE
2760                           || (ahc->msgout_len != 0
2761                            && ahc->msgout_index == 0))) {
2762                                 ahc->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
2763                                 goto reswitch;
2764                         }
2765                         end_session = TRUE;
2766                         break;
2767                 }
2768
2769                 /* Pull the byte in without acking it */
2770                 ahc->msgin_buf[ahc->msgin_index] = ahc_inb(ahc, SCSIBUSL);
2771 #ifdef AHC_DEBUG
2772                 if ((ahc_debug & AHC_SHOW_MESSAGES) != 0)
2773                         kprintf(" byte 0x%x\n",
2774                                ahc->msgin_buf[ahc->msgin_index]);
2775 #endif
2776
2777                 message_done = ahc_parse_msg(ahc, &devinfo);
2778
2779                 if (message_done) {
2780                         /*
2781                          * Clear our incoming message buffer in case there
2782                          * is another message following this one.
2783                          */
2784                         ahc->msgin_index = 0;
2785
2786                         /*
2787                          * If this message illicited a response,
2788                          * assert ATN so the target takes us to the
2789                          * message out phase.
2790                          */
2791                         if (ahc->msgout_len != 0) {
2792 #ifdef AHC_DEBUG
2793                                 if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
2794                                         ahc_print_devinfo(ahc, &devinfo);
2795                                         kprintf("Asserting ATN for response\n");
2796                                 }
2797 #endif
2798                                 ahc_assert_atn(ahc);
2799                         }
2800                 } else 
2801                         ahc->msgin_index++;
2802
2803                 if (message_done == MSGLOOP_TERMINATED) {
2804                         end_session = TRUE;
2805                 } else {
2806                         /* Ack the byte */
2807                         ahc_outb(ahc, CLRSINT1, CLRREQINIT);
2808                         ahc_inb(ahc, SCSIDATL);
2809                 }
2810                 break;
2811         }
2812         case MSG_TYPE_TARGET_MSGIN:
2813         {
2814                 int msgdone;
2815                 int msgout_request;
2816
2817                 if (ahc->msgout_len == 0)
2818                         panic("Target MSGIN with no active message");
2819
2820                 /*
2821                  * If we interrupted a mesgout session, the initiator
2822                  * will not know this until our first REQ.  So, we
2823                  * only honor mesgout requests after we've sent our
2824                  * first byte.
2825                  */
2826                 if ((ahc_inb(ahc, SCSISIGI) & ATNI) != 0
2827                  && ahc->msgout_index > 0)
2828                         msgout_request = TRUE;
2829                 else
2830                         msgout_request = FALSE;
2831
2832                 if (msgout_request) {
2833
2834                         /*
2835                          * Change gears and see if
2836                          * this messages is of interest to
2837                          * us or should be passed back to
2838                          * the sequencer.
2839                          */
2840                         ahc->msg_type = MSG_TYPE_TARGET_MSGOUT;
2841                         ahc_outb(ahc, SCSISIGO, P_MESGOUT | BSYO);
2842                         ahc->msgin_index = 0;
2843                         /* Dummy read to REQ for first byte */
2844                         ahc_inb(ahc, SCSIDATL);
2845                         ahc_outb(ahc, SXFRCTL0,
2846                                  ahc_inb(ahc, SXFRCTL0) | SPIOEN);
2847                         break;
2848                 }
2849
2850                 msgdone = ahc->msgout_index == ahc->msgout_len;
2851                 if (msgdone) {
2852                         ahc_outb(ahc, SXFRCTL0,
2853                                  ahc_inb(ahc, SXFRCTL0) & ~SPIOEN);
2854                         end_session = TRUE;
2855                         break;
2856                 }
2857
2858                 /*
2859                  * Present the next byte on the bus.
2860                  */
2861                 ahc_outb(ahc, SXFRCTL0, ahc_inb(ahc, SXFRCTL0) | SPIOEN);
2862                 ahc_outb(ahc, SCSIDATL, ahc->msgout_buf[ahc->msgout_index++]);
2863                 break;
2864         }
2865         case MSG_TYPE_TARGET_MSGOUT:
2866         {
2867                 int lastbyte;
2868                 int msgdone;
2869
2870                 /*
2871                  * The initiator signals that this is
2872                  * the last byte by dropping ATN.
2873                  */
2874                 lastbyte = (ahc_inb(ahc, SCSISIGI) & ATNI) == 0;
2875
2876                 /*
2877                  * Read the latched byte, but turn off SPIOEN first
2878                  * so that we don't inadvertently cause a REQ for the
2879                  * next byte.
2880                  */
2881                 ahc_outb(ahc, SXFRCTL0, ahc_inb(ahc, SXFRCTL0) & ~SPIOEN);
2882                 ahc->msgin_buf[ahc->msgin_index] = ahc_inb(ahc, SCSIDATL);
2883                 msgdone = ahc_parse_msg(ahc, &devinfo);
2884                 if (msgdone == MSGLOOP_TERMINATED) {
2885                         /*
2886                          * The message is *really* done in that it caused
2887                          * us to go to bus free.  The sequencer has already
2888                          * been reset at this point, so pull the ejection
2889                          * handle.
2890                          */
2891                         return;
2892                 }
2893                 
2894                 ahc->msgin_index++;
2895
2896                 /*
2897                  * XXX Read spec about initiator dropping ATN too soon
2898                  *     and use msgdone to detect it.
2899                  */
2900                 if (msgdone == MSGLOOP_MSGCOMPLETE) {
2901                         ahc->msgin_index = 0;
2902
2903                         /*
2904                          * If this message illicited a response, transition
2905                          * to the Message in phase and send it.
2906                          */
2907                         if (ahc->msgout_len != 0) {
2908                                 ahc_outb(ahc, SCSISIGO, P_MESGIN | BSYO);
2909                                 ahc_outb(ahc, SXFRCTL0,
2910                                          ahc_inb(ahc, SXFRCTL0) | SPIOEN);
2911                                 ahc->msg_type = MSG_TYPE_TARGET_MSGIN;
2912                                 ahc->msgin_index = 0;
2913                                 break;
2914                         }
2915                 }
2916
2917                 if (lastbyte)
2918                         end_session = TRUE;
2919                 else {
2920                         /* Ask for the next byte. */
2921                         ahc_outb(ahc, SXFRCTL0,
2922                                  ahc_inb(ahc, SXFRCTL0) | SPIOEN);
2923                 }
2924
2925                 break;
2926         }
2927         default:
2928                 panic("Unknown REQINIT message type");
2929         }
2930
2931         if (end_session) {
2932                 ahc_clear_msg_state(ahc);
2933                 ahc_outb(ahc, RETURN_1, EXIT_MSG_LOOP);
2934         } else
2935                 ahc_outb(ahc, RETURN_1, CONT_MSG_LOOP);
2936 }
2937
2938 /*
2939  * See if we sent a particular extended message to the target.
2940  * If "full" is true, return true only if the target saw the full
2941  * message.  If "full" is false, return true if the target saw at
2942  * least the first byte of the message.
2943  */
2944 static int
2945 ahc_sent_msg(struct ahc_softc *ahc, ahc_msgtype type, u_int msgval, int full)
2946 {
2947         int found;
2948         u_int index;
2949
2950         found = FALSE;
2951         index = 0;
2952
2953         while (index < ahc->msgout_len) {
2954                 if (ahc->msgout_buf[index] == MSG_EXTENDED) {
2955                         u_int end_index;
2956
2957                         end_index = index + 1 + ahc->msgout_buf[index + 1];
2958                         if (ahc->msgout_buf[index+2] == msgval
2959                          && type == AHCMSG_EXT) {
2960
2961                                 if (full) {
2962                                         if (ahc->msgout_index > end_index)
2963                                                 found = TRUE;
2964                                 } else if (ahc->msgout_index > index)
2965                                         found = TRUE;
2966                         }
2967                         index = end_index;
2968                 } else if (ahc->msgout_buf[index] >= MSG_SIMPLE_TASK
2969                         && ahc->msgout_buf[index] <= MSG_IGN_WIDE_RESIDUE) {
2970
2971                         /* Skip tag type and tag id or residue param*/
2972                         index += 2;
2973                 } else {
2974                         /* Single byte message */
2975                         if (type == AHCMSG_1B
2976                          && ahc->msgout_buf[index] == msgval
2977                          && ahc->msgout_index > index)
2978                                 found = TRUE;
2979                         index++;
2980                 }
2981
2982                 if (found)
2983                         break;
2984         }
2985         return (found);
2986 }
2987
2988 /*
2989  * Wait for a complete incoming message, parse it, and respond accordingly.
2990  */
2991 static int
2992 ahc_parse_msg(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
2993 {
2994         struct  ahc_initiator_tinfo *tinfo;
2995         struct  ahc_tmode_tstate *tstate;
2996         int     reject;
2997         int     done;
2998         int     response;
2999         u_int   targ_scsirate;
3000
3001         done = MSGLOOP_IN_PROG;
3002         response = FALSE;
3003         reject = FALSE;
3004         tinfo = ahc_fetch_transinfo(ahc, devinfo->channel, devinfo->our_scsiid,
3005                                     devinfo->target, &tstate);
3006         targ_scsirate = tinfo->scsirate;
3007
3008         /*
3009          * Parse as much of the message as is available,
3010          * rejecting it if we don't support it.  When
3011          * the entire message is available and has been
3012          * handled, return MSGLOOP_MSGCOMPLETE, indicating
3013          * that we have parsed an entire message.
3014          *
3015          * In the case of extended messages, we accept the length
3016          * byte outright and perform more checking once we know the
3017          * extended message type.
3018          */
3019         switch (ahc->msgin_buf[0]) {
3020         case MSG_DISCONNECT:
3021         case MSG_SAVEDATAPOINTER:
3022         case MSG_CMDCOMPLETE:
3023         case MSG_RESTOREPOINTERS:
3024         case MSG_IGN_WIDE_RESIDUE:
3025                 /*
3026                  * End our message loop as these are messages
3027                  * the sequencer handles on its own.
3028                  */
3029                 done = MSGLOOP_TERMINATED;
3030                 break;
3031         case MSG_MESSAGE_REJECT:
3032                 response = ahc_handle_msg_reject(ahc, devinfo);
3033                 /* FALLTHROUGH */
3034         case MSG_NOOP:
3035                 done = MSGLOOP_MSGCOMPLETE;
3036                 break;
3037         case MSG_EXTENDED:
3038         {
3039                 /* Wait for enough of the message to begin validation */
3040                 if (ahc->msgin_index < 2)
3041                         break;
3042                 switch (ahc->msgin_buf[2]) {
3043                 case MSG_EXT_SDTR:
3044                 {
3045                         struct   ahc_syncrate *syncrate;
3046                         u_int    period;
3047                         u_int    ppr_options;
3048                         u_int    offset;
3049                         u_int    saved_offset;
3050                         
3051                         if (ahc->msgin_buf[1] != MSG_EXT_SDTR_LEN) {
3052                                 reject = TRUE;
3053                                 break;
3054                         }
3055
3056                         /*
3057                          * Wait until we have both args before validating
3058                          * and acting on this message.
3059                          *
3060                          * Add one to MSG_EXT_SDTR_LEN to account for
3061                          * the extended message preamble.
3062                          */
3063                         if (ahc->msgin_index < (MSG_EXT_SDTR_LEN + 1))
3064                                 break;
3065
3066                         period = ahc->msgin_buf[3];
3067                         ppr_options = 0;
3068                         saved_offset = offset = ahc->msgin_buf[4];
3069                         syncrate = ahc_devlimited_syncrate(ahc, tinfo, &period,
3070                                                            &ppr_options,
3071                                                            devinfo->role);
3072                         ahc_validate_offset(ahc, tinfo, syncrate, &offset,
3073                                             targ_scsirate & WIDEXFER,
3074                                             devinfo->role);
3075                         if (bootverbose) {
3076                                 kprintf("(%s:%c:%d:%d): Received "
3077                                        "SDTR period %x, offset %x\n\t"
3078                                        "Filtered to period %x, offset %x\n",
3079                                        ahc_name(ahc), devinfo->channel,
3080                                        devinfo->target, devinfo->lun,
3081                                        ahc->msgin_buf[3], saved_offset,
3082                                        period, offset);
3083                         }
3084                         ahc_set_syncrate(ahc, devinfo, 
3085                                          syncrate, period,
3086                                          offset, ppr_options,
3087                                          AHC_TRANS_ACTIVE|AHC_TRANS_GOAL,
3088                                          /*paused*/TRUE);
3089
3090                         /*
3091                          * See if we initiated Sync Negotiation
3092                          * and didn't have to fall down to async
3093                          * transfers.
3094                          */
3095                         if (ahc_sent_msg(ahc, AHCMSG_EXT, MSG_EXT_SDTR, TRUE)) {
3096                                 /* We started it */
3097                                 if (saved_offset != offset) {
3098                                         /* Went too low - force async */
3099                                         reject = TRUE;
3100                                 }
3101                         } else {
3102                                 /*
3103                                  * Send our own SDTR in reply
3104                                  */
3105                                 if (bootverbose
3106                                  && devinfo->role == ROLE_INITIATOR) {
3107                                         kprintf("(%s:%c:%d:%d): Target "
3108                                                "Initiated SDTR\n",
3109                                                ahc_name(ahc), devinfo->channel,
3110                                                devinfo->target, devinfo->lun);
3111                                 }
3112                                 ahc->msgout_index = 0;
3113                                 ahc->msgout_len = 0;
3114                                 ahc_construct_sdtr(ahc, devinfo,
3115                                                    period, offset);
3116                                 ahc->msgout_index = 0;
3117                                 response = TRUE;
3118                         }
3119                         done = MSGLOOP_MSGCOMPLETE;
3120                         break;
3121                 }
3122                 case MSG_EXT_WDTR:
3123                 {
3124                         u_int bus_width;
3125                         u_int saved_width;
3126                         u_int sending_reply;
3127
3128                         sending_reply = FALSE;
3129                         if (ahc->msgin_buf[1] != MSG_EXT_WDTR_LEN) {
3130                                 reject = TRUE;
3131                                 break;
3132                         }
3133
3134                         /*
3135                          * Wait until we have our arg before validating
3136                          * and acting on this message.
3137                          *
3138                          * Add one to MSG_EXT_WDTR_LEN to account for
3139                          * the extended message preamble.
3140                          */
3141                         if (ahc->msgin_index < (MSG_EXT_WDTR_LEN + 1))
3142                                 break;
3143
3144                         bus_width = ahc->msgin_buf[3];
3145                         saved_width = bus_width;
3146                         ahc_validate_width(ahc, tinfo, &bus_width,
3147                                            devinfo->role);
3148                         if (bootverbose) {
3149                                 kprintf("(%s:%c:%d:%d): Received WDTR "
3150                                        "%x filtered to %x\n",
3151                                        ahc_name(ahc), devinfo->channel,
3152                                        devinfo->target, devinfo->lun,
3153                                        saved_width, bus_width);
3154                         }
3155
3156                         if (ahc_sent_msg(ahc, AHCMSG_EXT, MSG_EXT_WDTR, TRUE)) {
3157                                 /*
3158                                  * Don't send a WDTR back to the
3159                                  * target, since we asked first.
3160                                  * If the width went higher than our
3161                                  * request, reject it.
3162                                  */
3163                                 if (saved_width > bus_width) {
3164                                         reject = TRUE;
3165                                         kprintf("(%s:%c:%d:%d): requested %dBit "
3166                                                "transfers.  Rejecting...\n",
3167                                                ahc_name(ahc), devinfo->channel,
3168                                                devinfo->target, devinfo->lun,
3169                                                8 * (0x01 << bus_width));
3170                                         bus_width = 0;
3171                                 }
3172                         } else {
3173                                 /*
3174                                  * Send our own WDTR in reply
3175                                  */
3176                                 if (bootverbose
3177                                  && devinfo->role == ROLE_INITIATOR) {
3178                                         kprintf("(%s:%c:%d:%d): Target "
3179                                                "Initiated WDTR\n",
3180                                                ahc_name(ahc), devinfo->channel,
3181                                                devinfo->target, devinfo->lun);
3182                                 }
3183                                 ahc->msgout_index = 0;
3184                                 ahc->msgout_len = 0;
3185                                 ahc_construct_wdtr(ahc, devinfo, bus_width);
3186                                 ahc->msgout_index = 0;
3187                                 response = TRUE;
3188                                 sending_reply = TRUE;
3189                         }
3190                         /*
3191                          * After a wide message, we are async, but
3192                          * some devices don't seem to honor this portion
3193                          * of the spec.  Force a renegotiation of the
3194                          * sync component of our transfer agreement even
3195                          * if our goal is async.  By updating our width
3196                          * after forcing the negotiation, we avoid
3197                          * renegotiating for width.
3198                          */
3199                         ahc_update_neg_request(ahc, devinfo, tstate,
3200                                                tinfo, AHC_NEG_ALWAYS);
3201                         ahc_set_width(ahc, devinfo, bus_width,
3202                                       AHC_TRANS_ACTIVE|AHC_TRANS_GOAL,
3203                                       /*paused*/TRUE);
3204                         if (sending_reply == FALSE && reject == FALSE) {
3205
3206                                 /*
3207                                  * We will always have an SDTR to send.
3208                                  */
3209                                 ahc->msgout_index = 0;
3210                                 ahc->msgout_len = 0;
3211                                 ahc_build_transfer_msg(ahc, devinfo);
3212                                 ahc->msgout_index = 0;
3213                                 response = TRUE;
3214                         }
3215                         done = MSGLOOP_MSGCOMPLETE;
3216                         break;
3217                 }
3218                 case MSG_EXT_PPR:
3219                 {
3220                         struct  ahc_syncrate *syncrate;
3221                         u_int   period;
3222                         u_int   offset;
3223                         u_int   bus_width;
3224                         u_int   ppr_options;
3225                         u_int   saved_width;
3226                         u_int   saved_offset;
3227                         u_int   saved_ppr_options;
3228
3229                         if (ahc->msgin_buf[1] != MSG_EXT_PPR_LEN) {
3230                                 reject = TRUE;
3231                                 break;
3232                         }
3233
3234                         /*
3235                          * Wait until we have all args before validating
3236                          * and acting on this message.
3237                          *
3238                          * Add one to MSG_EXT_PPR_LEN to account for
3239                          * the extended message preamble.
3240                          */
3241                         if (ahc->msgin_index < (MSG_EXT_PPR_LEN + 1))
3242                                 break;
3243
3244                         period = ahc->msgin_buf[3];
3245                         offset = ahc->msgin_buf[5];
3246                         bus_width = ahc->msgin_buf[6];
3247                         saved_width = bus_width;
3248                         ppr_options = ahc->msgin_buf[7];
3249                         /*
3250                          * According to the spec, a DT only
3251                          * period factor with no DT option
3252                          * set implies async.
3253                          */
3254                         if ((ppr_options & MSG_EXT_PPR_DT_REQ) == 0
3255                          && period == 9)
3256                                 offset = 0;
3257                         saved_ppr_options = ppr_options;
3258                         saved_offset = offset;
3259
3260                         /*
3261                          * Mask out any options we don't support
3262                          * on any controller.  Transfer options are
3263                          * only available if we are negotiating wide.
3264                          */
3265                         ppr_options &= MSG_EXT_PPR_DT_REQ;
3266                         if (bus_width == 0)
3267                                 ppr_options = 0;
3268
3269                         ahc_validate_width(ahc, tinfo, &bus_width,
3270                                            devinfo->role);
3271                         syncrate = ahc_devlimited_syncrate(ahc, tinfo, &period,
3272                                                            &ppr_options,
3273                                                            devinfo->role);
3274                         ahc_validate_offset(ahc, tinfo, syncrate,
3275                                             &offset, bus_width,
3276                                             devinfo->role);
3277
3278                         if (ahc_sent_msg(ahc, AHCMSG_EXT, MSG_EXT_PPR, TRUE)) {
3279                                 /*
3280                                  * If we are unable to do any of the
3281                                  * requested options (we went too low),
3282                                  * then we'll have to reject the message.
3283                                  */
3284                                 if (saved_width > bus_width
3285                                  || saved_offset != offset
3286                                  || saved_ppr_options != ppr_options) {
3287                                         reject = TRUE;
3288                                         period = 0;
3289                                         offset = 0;
3290                                         bus_width = 0;
3291                                         ppr_options = 0;
3292                                         syncrate = NULL;
3293                                 }
3294                         } else {
3295                                 if (devinfo->role != ROLE_TARGET)
3296                                         kprintf("(%s:%c:%d:%d): Target "
3297                                                "Initiated PPR\n",
3298                                                ahc_name(ahc), devinfo->channel,
3299                                                devinfo->target, devinfo->lun);
3300                                 else
3301                                         kprintf("(%s:%c:%d:%d): Initiator "
3302                                                "Initiated PPR\n",
3303                                                ahc_name(ahc), devinfo->channel,
3304                                                devinfo->target, devinfo->lun);
3305                                 ahc->msgout_index = 0;
3306                                 ahc->msgout_len = 0;
3307                                 ahc_construct_ppr(ahc, devinfo, period, offset,
3308                                                   bus_width, ppr_options);
3309                                 ahc->msgout_index = 0;
3310                                 response = TRUE;
3311                         }
3312                         if (bootverbose) {
3313                                 kprintf("(%s:%c:%d:%d): Received PPR width %x, "
3314                                        "period %x, offset %x,options %x\n"
3315                                        "\tFiltered to width %x, period %x, "
3316                                        "offset %x, options %x\n",
3317                                        ahc_name(ahc), devinfo->channel,
3318                                        devinfo->target, devinfo->lun,
3319                                        saved_width, ahc->msgin_buf[3],
3320                                        saved_offset, saved_ppr_options,
3321                                        bus_width, period, offset, ppr_options);
3322                         }
3323                         ahc_set_width(ahc, devinfo, bus_width,
3324                                       AHC_TRANS_ACTIVE|AHC_TRANS_GOAL,
3325                                       /*paused*/TRUE);
3326                         ahc_set_syncrate(ahc, devinfo,
3327                                          syncrate, period,
3328                                          offset, ppr_options,
3329                                          AHC_TRANS_ACTIVE|AHC_TRANS_GOAL,
3330                                          /*paused*/TRUE);
3331                         done = MSGLOOP_MSGCOMPLETE;
3332                         break;
3333                 }
3334                 default:
3335                         /* Unknown extended message.  Reject it. */
3336                         reject = TRUE;
3337                         break;
3338                 }
3339                 break;
3340         }
3341 #ifdef AHC_TARGET_MODE
3342         case MSG_BUS_DEV_RESET:
3343                 ahc_handle_devreset(ahc, devinfo,
3344                                     CAM_BDR_SENT,
3345                                     "Bus Device Reset Received",
3346                                     /*verbose_level*/0);
3347                 ahc_restart(ahc);
3348                 done = MSGLOOP_TERMINATED;
3349                 break;
3350         case MSG_ABORT_TAG:
3351         case MSG_ABORT:
3352         case MSG_CLEAR_QUEUE:
3353         {
3354                 int tag;
3355
3356                 /* Target mode messages */
3357                 if (devinfo->role != ROLE_TARGET) {
3358                         reject = TRUE;
3359                         break;
3360                 }
3361                 tag = SCB_LIST_NULL;
3362                 if (ahc->msgin_buf[0] == MSG_ABORT_TAG)
3363                         tag = ahc_inb(ahc, INITIATOR_TAG);
3364                 ahc_abort_scbs(ahc, devinfo->target, devinfo->channel,
3365                                devinfo->lun, tag, ROLE_TARGET,
3366                                CAM_REQ_ABORTED);
3367
3368                 tstate = ahc->enabled_targets[devinfo->our_scsiid];
3369                 if (tstate != NULL) {
3370                         struct ahc_tmode_lstate* lstate;
3371
3372                         lstate = tstate->enabled_luns[devinfo->lun];
3373                         if (lstate != NULL) {
3374                                 ahc_queue_lstate_event(ahc, lstate,
3375                                                        devinfo->our_scsiid,
3376                                                        ahc->msgin_buf[0],
3377                                                        /*arg*/tag);
3378                                 ahc_send_lstate_events(ahc, lstate);
3379                         }
3380                 }
3381                 ahc_restart(ahc);
3382                 done = MSGLOOP_TERMINATED;
3383                 break;
3384         }
3385 #endif
3386         case MSG_TERM_IO_PROC:
3387         default:
3388                 reject = TRUE;
3389                 break;
3390         }
3391
3392         if (reject) {