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