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