]> www.pilppa.org Git - linux-2.6-omap-h63xx.git/blob - drivers/scsi/aic7xxx/aic79xx_core.c
[SCSI] aic7xxx, aic79xx: deinline functions
[linux-2.6-omap-h63xx.git] / drivers / scsi / aic7xxx / aic79xx_core.c
1 /*
2  * Core routines and tables shareable across OS platforms.
3  *
4  * Copyright (c) 1994-2002 Justin T. Gibbs.
5  * Copyright (c) 2000-2003 Adaptec Inc.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions, and the following disclaimer,
13  *    without modification.
14  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
15  *    substantially similar to the "NO WARRANTY" disclaimer below
16  *    ("Disclaimer") and any redistribution must be conditioned upon
17  *    including a substantially similar Disclaimer requirement for further
18  *    binary redistribution.
19  * 3. Neither the names of the above-listed copyright holders nor the names
20  *    of any contributors may be used to endorse or promote products derived
21  *    from this software without specific prior written permission.
22  *
23  * Alternatively, this software may be distributed under the terms of the
24  * GNU General Public License ("GPL") version 2 as published by the Free
25  * Software Foundation.
26  *
27  * NO WARRANTY
28  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
31  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
36  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
37  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
38  * POSSIBILITY OF SUCH DAMAGES.
39  *
40  * $Id: //depot/aic7xxx/aic7xxx/aic79xx.c#250 $
41  */
42
43 #ifdef __linux__
44 #include "aic79xx_osm.h"
45 #include "aic79xx_inline.h"
46 #include "aicasm/aicasm_insformat.h"
47 #else
48 #include <dev/aic7xxx/aic79xx_osm.h>
49 #include <dev/aic7xxx/aic79xx_inline.h>
50 #include <dev/aic7xxx/aicasm/aicasm_insformat.h>
51 #endif
52
53
54 /***************************** Lookup Tables **********************************/
55 static char *ahd_chip_names[] =
56 {
57         "NONE",
58         "aic7901",
59         "aic7902",
60         "aic7901A"
61 };
62 static const u_int num_chip_names = ARRAY_SIZE(ahd_chip_names);
63
64 /*
65  * Hardware error codes.
66  */
67 struct ahd_hard_error_entry {
68         uint8_t errno;
69         char *errmesg;
70 };
71
72 static struct ahd_hard_error_entry ahd_hard_errors[] = {
73         { DSCTMOUT,     "Discard Timer has timed out" },
74         { ILLOPCODE,    "Illegal Opcode in sequencer program" },
75         { SQPARERR,     "Sequencer Parity Error" },
76         { DPARERR,      "Data-path Parity Error" },
77         { MPARERR,      "Scratch or SCB Memory Parity Error" },
78         { CIOPARERR,    "CIOBUS Parity Error" },
79 };
80 static const u_int num_errors = ARRAY_SIZE(ahd_hard_errors);
81
82 static struct ahd_phase_table_entry ahd_phase_table[] =
83 {
84         { P_DATAOUT,    MSG_NOOP,               "in Data-out phase"     },
85         { P_DATAIN,     MSG_INITIATOR_DET_ERR,  "in Data-in phase"      },
86         { P_DATAOUT_DT, MSG_NOOP,               "in DT Data-out phase"  },
87         { P_DATAIN_DT,  MSG_INITIATOR_DET_ERR,  "in DT Data-in phase"   },
88         { P_COMMAND,    MSG_NOOP,               "in Command phase"      },
89         { P_MESGOUT,    MSG_NOOP,               "in Message-out phase"  },
90         { P_STATUS,     MSG_INITIATOR_DET_ERR,  "in Status phase"       },
91         { P_MESGIN,     MSG_PARITY_ERROR,       "in Message-in phase"   },
92         { P_BUSFREE,    MSG_NOOP,               "while idle"            },
93         { 0,            MSG_NOOP,               "in unknown phase"      }
94 };
95
96 /*
97  * In most cases we only wish to itterate over real phases, so
98  * exclude the last element from the count.
99  */
100 static const u_int num_phases = ARRAY_SIZE(ahd_phase_table) - 1;
101
102 /* Our Sequencer Program */
103 #include "aic79xx_seq.h"
104
105 /**************************** Function Declarations ***************************/
106 static void             ahd_handle_transmission_error(struct ahd_softc *ahd);
107 static void             ahd_handle_lqiphase_error(struct ahd_softc *ahd,
108                                                   u_int lqistat1);
109 static int              ahd_handle_pkt_busfree(struct ahd_softc *ahd,
110                                                u_int busfreetime);
111 static int              ahd_handle_nonpkt_busfree(struct ahd_softc *ahd);
112 static void             ahd_handle_proto_violation(struct ahd_softc *ahd);
113 static void             ahd_force_renegotiation(struct ahd_softc *ahd,
114                                                 struct ahd_devinfo *devinfo);
115
116 static struct ahd_tmode_tstate*
117                         ahd_alloc_tstate(struct ahd_softc *ahd,
118                                          u_int scsi_id, char channel);
119 #ifdef AHD_TARGET_MODE
120 static void             ahd_free_tstate(struct ahd_softc *ahd,
121                                         u_int scsi_id, char channel, int force);
122 #endif
123 static void             ahd_devlimited_syncrate(struct ahd_softc *ahd,
124                                                 struct ahd_initiator_tinfo *,
125                                                 u_int *period,
126                                                 u_int *ppr_options,
127                                                 role_t role);
128 static void             ahd_update_neg_table(struct ahd_softc *ahd,
129                                              struct ahd_devinfo *devinfo,
130                                              struct ahd_transinfo *tinfo);
131 static void             ahd_update_pending_scbs(struct ahd_softc *ahd);
132 static void             ahd_fetch_devinfo(struct ahd_softc *ahd,
133                                           struct ahd_devinfo *devinfo);
134 static void             ahd_scb_devinfo(struct ahd_softc *ahd,
135                                         struct ahd_devinfo *devinfo,
136                                         struct scb *scb);
137 static void             ahd_setup_initiator_msgout(struct ahd_softc *ahd,
138                                                    struct ahd_devinfo *devinfo,
139                                                    struct scb *scb);
140 static void             ahd_build_transfer_msg(struct ahd_softc *ahd,
141                                                struct ahd_devinfo *devinfo);
142 static void             ahd_construct_sdtr(struct ahd_softc *ahd,
143                                            struct ahd_devinfo *devinfo,
144                                            u_int period, u_int offset);
145 static void             ahd_construct_wdtr(struct ahd_softc *ahd,
146                                            struct ahd_devinfo *devinfo,
147                                            u_int bus_width);
148 static void             ahd_construct_ppr(struct ahd_softc *ahd,
149                                           struct ahd_devinfo *devinfo,
150                                           u_int period, u_int offset,
151                                           u_int bus_width, u_int ppr_options);
152 static void             ahd_clear_msg_state(struct ahd_softc *ahd);
153 static void             ahd_handle_message_phase(struct ahd_softc *ahd);
154 typedef enum {
155         AHDMSG_1B,
156         AHDMSG_2B,
157         AHDMSG_EXT
158 } ahd_msgtype;
159 static int              ahd_sent_msg(struct ahd_softc *ahd, ahd_msgtype type,
160                                      u_int msgval, int full);
161 static int              ahd_parse_msg(struct ahd_softc *ahd,
162                                       struct ahd_devinfo *devinfo);
163 static int              ahd_handle_msg_reject(struct ahd_softc *ahd,
164                                               struct ahd_devinfo *devinfo);
165 static void             ahd_handle_ign_wide_residue(struct ahd_softc *ahd,
166                                                 struct ahd_devinfo *devinfo);
167 static void             ahd_reinitialize_dataptrs(struct ahd_softc *ahd);
168 static void             ahd_handle_devreset(struct ahd_softc *ahd,
169                                             struct ahd_devinfo *devinfo,
170                                             u_int lun, cam_status status,
171                                             char *message, int verbose_level);
172 #ifdef AHD_TARGET_MODE
173 static void             ahd_setup_target_msgin(struct ahd_softc *ahd,
174                                                struct ahd_devinfo *devinfo,
175                                                struct scb *scb);
176 #endif
177
178 static u_int            ahd_sglist_size(struct ahd_softc *ahd);
179 static u_int            ahd_sglist_allocsize(struct ahd_softc *ahd);
180 static bus_dmamap_callback_t
181                         ahd_dmamap_cb; 
182 static void             ahd_initialize_hscbs(struct ahd_softc *ahd);
183 static int              ahd_init_scbdata(struct ahd_softc *ahd);
184 static void             ahd_fini_scbdata(struct ahd_softc *ahd);
185 static void             ahd_setup_iocell_workaround(struct ahd_softc *ahd);
186 static void             ahd_iocell_first_selection(struct ahd_softc *ahd);
187 static void             ahd_add_col_list(struct ahd_softc *ahd,
188                                          struct scb *scb, u_int col_idx);
189 static void             ahd_rem_col_list(struct ahd_softc *ahd,
190                                          struct scb *scb);
191 static void             ahd_chip_init(struct ahd_softc *ahd);
192 static void             ahd_qinfifo_requeue(struct ahd_softc *ahd,
193                                             struct scb *prev_scb,
194                                             struct scb *scb);
195 static int              ahd_qinfifo_count(struct ahd_softc *ahd);
196 static int              ahd_search_scb_list(struct ahd_softc *ahd, int target,
197                                             char channel, int lun, u_int tag,
198                                             role_t role, uint32_t status,
199                                             ahd_search_action action,
200                                             u_int *list_head, u_int *list_tail,
201                                             u_int tid);
202 static void             ahd_stitch_tid_list(struct ahd_softc *ahd,
203                                             u_int tid_prev, u_int tid_cur,
204                                             u_int tid_next);
205 static void             ahd_add_scb_to_free_list(struct ahd_softc *ahd,
206                                                  u_int scbid);
207 static u_int            ahd_rem_wscb(struct ahd_softc *ahd, u_int scbid,
208                                      u_int prev, u_int next, u_int tid);
209 static void             ahd_reset_current_bus(struct ahd_softc *ahd);
210 static ahd_callback_t   ahd_stat_timer;
211 #ifdef AHD_DUMP_SEQ
212 static void             ahd_dumpseq(struct ahd_softc *ahd);
213 #endif
214 static void             ahd_loadseq(struct ahd_softc *ahd);
215 static int              ahd_check_patch(struct ahd_softc *ahd,
216                                         struct patch **start_patch,
217                                         u_int start_instr, u_int *skip_addr);
218 static u_int            ahd_resolve_seqaddr(struct ahd_softc *ahd,
219                                             u_int address);
220 static void             ahd_download_instr(struct ahd_softc *ahd,
221                                            u_int instrptr, uint8_t *dconsts);
222 static int              ahd_probe_stack_size(struct ahd_softc *ahd);
223 static int              ahd_scb_active_in_fifo(struct ahd_softc *ahd,
224                                                struct scb *scb);
225 static void             ahd_run_data_fifo(struct ahd_softc *ahd,
226                                           struct scb *scb);
227
228 #ifdef AHD_TARGET_MODE
229 static void             ahd_queue_lstate_event(struct ahd_softc *ahd,
230                                                struct ahd_tmode_lstate *lstate,
231                                                u_int initiator_id,
232                                                u_int event_type,
233                                                u_int event_arg);
234 static void             ahd_update_scsiid(struct ahd_softc *ahd,
235                                           u_int targid_mask);
236 static int              ahd_handle_target_cmd(struct ahd_softc *ahd,
237                                               struct target_cmd *cmd);
238 #endif
239
240 static int              ahd_abort_scbs(struct ahd_softc *ahd, int target,
241                                        char channel, int lun, u_int tag,
242                                        role_t role, uint32_t status);
243 static void             ahd_alloc_scbs(struct ahd_softc *ahd);
244 static void             ahd_busy_tcl(struct ahd_softc *ahd, u_int tcl,
245                                      u_int scbid);
246 static void             ahd_calc_residual(struct ahd_softc *ahd,
247                                           struct scb *scb);
248 static void             ahd_clear_critical_section(struct ahd_softc *ahd);
249 static void             ahd_clear_intstat(struct ahd_softc *ahd);
250 static void             ahd_enable_coalescing(struct ahd_softc *ahd,
251                                               int enable);
252 static u_int            ahd_find_busy_tcl(struct ahd_softc *ahd, u_int tcl);
253 static void             ahd_freeze_devq(struct ahd_softc *ahd,
254                                         struct scb *scb);
255 static void             ahd_handle_scb_status(struct ahd_softc *ahd,
256                                               struct scb *scb);
257 static struct ahd_phase_table_entry* ahd_lookup_phase_entry(int phase);
258 static void             ahd_shutdown(void *arg);
259 static void             ahd_update_coalescing_values(struct ahd_softc *ahd,
260                                                      u_int timer,
261                                                      u_int maxcmds,
262                                                      u_int mincmds);
263 static int              ahd_verify_vpd_cksum(struct vpd_config *vpd);
264 static int              ahd_wait_seeprom(struct ahd_softc *ahd);
265 static int              ahd_match_scb(struct ahd_softc *ahd, struct scb *scb,
266                                       int target, char channel, int lun,
267                                       u_int tag, role_t role);
268
269 /************************ Sequencer Execution Control *************************/
270 void
271 ahd_set_modes(struct ahd_softc *ahd, ahd_mode src, ahd_mode dst)
272 {
273         if (ahd->src_mode == src && ahd->dst_mode == dst)
274                 return;
275 #ifdef AHD_DEBUG
276         if (ahd->src_mode == AHD_MODE_UNKNOWN
277          || ahd->dst_mode == AHD_MODE_UNKNOWN)
278                 panic("Setting mode prior to saving it.\n");
279         if ((ahd_debug & AHD_SHOW_MODEPTR) != 0)
280                 printf("%s: Setting mode 0x%x\n", ahd_name(ahd),
281                        ahd_build_mode_state(ahd, src, dst));
282 #endif
283         ahd_outb(ahd, MODE_PTR, ahd_build_mode_state(ahd, src, dst));
284         ahd->src_mode = src;
285         ahd->dst_mode = dst;
286 }
287
288 void
289 ahd_update_modes(struct ahd_softc *ahd)
290 {
291         ahd_mode_state mode_ptr;
292         ahd_mode src;
293         ahd_mode dst;
294
295         mode_ptr = ahd_inb(ahd, MODE_PTR);
296 #ifdef AHD_DEBUG
297         if ((ahd_debug & AHD_SHOW_MODEPTR) != 0)
298                 printf("Reading mode 0x%x\n", mode_ptr);
299 #endif
300         ahd_extract_mode_state(ahd, mode_ptr, &src, &dst);
301         ahd_known_modes(ahd, src, dst);
302 }
303
304 void
305 ahd_assert_modes(struct ahd_softc *ahd, ahd_mode srcmode,
306                  ahd_mode dstmode, const char *file, int line)
307 {
308 #ifdef AHD_DEBUG
309         if ((srcmode & AHD_MK_MSK(ahd->src_mode)) == 0
310          || (dstmode & AHD_MK_MSK(ahd->dst_mode)) == 0) {
311                 panic("%s:%s:%d: Mode assertion failed.\n",
312                        ahd_name(ahd), file, line);
313         }
314 #endif
315 }
316
317 #define AHD_ASSERT_MODES(ahd, source, dest) \
318         ahd_assert_modes(ahd, source, dest, __FILE__, __LINE__);
319
320 ahd_mode_state
321 ahd_save_modes(struct ahd_softc *ahd)
322 {
323         if (ahd->src_mode == AHD_MODE_UNKNOWN
324          || ahd->dst_mode == AHD_MODE_UNKNOWN)
325                 ahd_update_modes(ahd);
326
327         return (ahd_build_mode_state(ahd, ahd->src_mode, ahd->dst_mode));
328 }
329
330 void
331 ahd_restore_modes(struct ahd_softc *ahd, ahd_mode_state state)
332 {
333         ahd_mode src;
334         ahd_mode dst;
335
336         ahd_extract_mode_state(ahd, state, &src, &dst);
337         ahd_set_modes(ahd, src, dst);
338 }
339
340 /*
341  * Determine whether the sequencer has halted code execution.
342  * Returns non-zero status if the sequencer is stopped.
343  */
344 int
345 ahd_is_paused(struct ahd_softc *ahd)
346 {
347         return ((ahd_inb(ahd, HCNTRL) & PAUSE) != 0);
348 }
349
350 /*
351  * Request that the sequencer stop and wait, indefinitely, for it
352  * to stop.  The sequencer will only acknowledge that it is paused
353  * once it has reached an instruction boundary and PAUSEDIS is
354  * cleared in the SEQCTL register.  The sequencer may use PAUSEDIS
355  * for critical sections.
356  */
357 void
358 ahd_pause(struct ahd_softc *ahd)
359 {
360         ahd_outb(ahd, HCNTRL, ahd->pause);
361
362         /*
363          * Since the sequencer can disable pausing in a critical section, we
364          * must loop until it actually stops.
365          */
366         while (ahd_is_paused(ahd) == 0)
367                 ;
368 }
369
370 /*
371  * Allow the sequencer to continue program execution.
372  * We check here to ensure that no additional interrupt
373  * sources that would cause the sequencer to halt have been
374  * asserted.  If, for example, a SCSI bus reset is detected
375  * while we are fielding a different, pausing, interrupt type,
376  * we don't want to release the sequencer before going back
377  * into our interrupt handler and dealing with this new
378  * condition.
379  */
380 void
381 ahd_unpause(struct ahd_softc *ahd)
382 {
383         /*
384          * Automatically restore our modes to those saved
385          * prior to the first change of the mode.
386          */
387         if (ahd->saved_src_mode != AHD_MODE_UNKNOWN
388          && ahd->saved_dst_mode != AHD_MODE_UNKNOWN) {
389                 if ((ahd->flags & AHD_UPDATE_PEND_CMDS) != 0)
390                         ahd_reset_cmds_pending(ahd);
391                 ahd_set_modes(ahd, ahd->saved_src_mode, ahd->saved_dst_mode);
392         }
393
394         if ((ahd_inb(ahd, INTSTAT) & ~CMDCMPLT) == 0)
395                 ahd_outb(ahd, HCNTRL, ahd->unpause);
396
397         ahd_known_modes(ahd, AHD_MODE_UNKNOWN, AHD_MODE_UNKNOWN);
398 }
399
400 /*********************** Scatter Gather List Handling *************************/
401 void *
402 ahd_sg_setup(struct ahd_softc *ahd, struct scb *scb,
403              void *sgptr, dma_addr_t addr, bus_size_t len, int last)
404 {
405         scb->sg_count++;
406         if (sizeof(dma_addr_t) > 4
407          && (ahd->flags & AHD_64BIT_ADDRESSING) != 0) {
408                 struct ahd_dma64_seg *sg;
409
410                 sg = (struct ahd_dma64_seg *)sgptr;
411                 sg->addr = ahd_htole64(addr);
412                 sg->len = ahd_htole32(len | (last ? AHD_DMA_LAST_SEG : 0));
413                 return (sg + 1);
414         } else {
415                 struct ahd_dma_seg *sg;
416
417                 sg = (struct ahd_dma_seg *)sgptr;
418                 sg->addr = ahd_htole32(addr & 0xFFFFFFFF);
419                 sg->len = ahd_htole32(len | ((addr >> 8) & 0x7F000000)
420                                     | (last ? AHD_DMA_LAST_SEG : 0));
421                 return (sg + 1);
422         }
423 }
424
425 void
426 ahd_setup_scb_common(struct ahd_softc *ahd, struct scb *scb)
427 {
428         /* XXX Handle target mode SCBs. */
429         scb->crc_retry_count = 0;
430         if ((scb->flags & SCB_PACKETIZED) != 0) {
431                 /* XXX what about ACA??  It is type 4, but TAG_TYPE == 0x3. */
432                 scb->hscb->task_attribute = scb->hscb->control & SCB_TAG_TYPE;
433         } else {
434                 if (ahd_get_transfer_length(scb) & 0x01)
435                         scb->hscb->task_attribute = SCB_XFERLEN_ODD;
436                 else
437                         scb->hscb->task_attribute = 0;
438         }
439
440         if (scb->hscb->cdb_len <= MAX_CDB_LEN_WITH_SENSE_ADDR
441          || (scb->hscb->cdb_len & SCB_CDB_LEN_PTR) != 0)
442                 scb->hscb->shared_data.idata.cdb_plus_saddr.sense_addr =
443                     ahd_htole32(scb->sense_busaddr);
444 }
445
446 void
447 ahd_setup_data_scb(struct ahd_softc *ahd, struct scb *scb)
448 {
449         /*
450          * Copy the first SG into the "current" data ponter area.
451          */
452         if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0) {
453                 struct ahd_dma64_seg *sg;
454
455                 sg = (struct ahd_dma64_seg *)scb->sg_list;
456                 scb->hscb->dataptr = sg->addr;
457                 scb->hscb->datacnt = sg->len;
458         } else {
459                 struct ahd_dma_seg *sg;
460                 uint32_t *dataptr_words;
461
462                 sg = (struct ahd_dma_seg *)scb->sg_list;
463                 dataptr_words = (uint32_t*)&scb->hscb->dataptr;
464                 dataptr_words[0] = sg->addr;
465                 dataptr_words[1] = 0;
466                 if ((ahd->flags & AHD_39BIT_ADDRESSING) != 0) {
467                         uint64_t high_addr;
468
469                         high_addr = ahd_le32toh(sg->len) & 0x7F000000;
470                         scb->hscb->dataptr |= ahd_htole64(high_addr << 8);
471                 }
472                 scb->hscb->datacnt = sg->len;
473         }
474         /*
475          * Note where to find the SG entries in bus space.
476          * We also set the full residual flag which the
477          * sequencer will clear as soon as a data transfer
478          * occurs.
479          */
480         scb->hscb->sgptr = ahd_htole32(scb->sg_list_busaddr|SG_FULL_RESID);
481 }
482
483 void
484 ahd_setup_noxfer_scb(struct ahd_softc *ahd, struct scb *scb)
485 {
486         scb->hscb->sgptr = ahd_htole32(SG_LIST_NULL);
487         scb->hscb->dataptr = 0;
488         scb->hscb->datacnt = 0;
489 }
490
491 /************************** Memory mapping routines ***************************/
492 void *
493 ahd_sg_bus_to_virt(struct ahd_softc *ahd, struct scb *scb, uint32_t sg_busaddr)
494 {
495         dma_addr_t sg_offset;
496
497         /* sg_list_phys points to entry 1, not 0 */
498         sg_offset = sg_busaddr - (scb->sg_list_busaddr - ahd_sg_size(ahd));
499         return ((uint8_t *)scb->sg_list + sg_offset);
500 }
501
502 uint32_t
503 ahd_sg_virt_to_bus(struct ahd_softc *ahd, struct scb *scb, void *sg)
504 {
505         dma_addr_t sg_offset;
506
507         /* sg_list_phys points to entry 1, not 0 */
508         sg_offset = ((uint8_t *)sg - (uint8_t *)scb->sg_list)
509                   - ahd_sg_size(ahd);
510
511         return (scb->sg_list_busaddr + sg_offset);
512 }
513
514 void
515 ahd_sync_scb(struct ahd_softc *ahd, struct scb *scb, int op)
516 {
517         ahd_dmamap_sync(ahd, ahd->scb_data.hscb_dmat,
518                         scb->hscb_map->dmamap,
519                         /*offset*/(uint8_t*)scb->hscb - scb->hscb_map->vaddr,
520                         /*len*/sizeof(*scb->hscb), op);
521 }
522
523 void
524 ahd_sync_sglist(struct ahd_softc *ahd, struct scb *scb, int op)
525 {
526         if (scb->sg_count == 0)
527                 return;
528
529         ahd_dmamap_sync(ahd, ahd->scb_data.sg_dmat,
530                         scb->sg_map->dmamap,
531                         /*offset*/scb->sg_list_busaddr - ahd_sg_size(ahd),
532                         /*len*/ahd_sg_size(ahd) * scb->sg_count, op);
533 }
534
535 void
536 ahd_sync_sense(struct ahd_softc *ahd, struct scb *scb, int op)
537 {
538         ahd_dmamap_sync(ahd, ahd->scb_data.sense_dmat,
539                         scb->sense_map->dmamap,
540                         /*offset*/scb->sense_busaddr,
541                         /*len*/AHD_SENSE_BUFSIZE, op);
542 }
543
544 uint32_t
545 ahd_targetcmd_offset(struct ahd_softc *ahd, u_int index)
546 {
547         return (((uint8_t *)&ahd->targetcmds[index])
548                - (uint8_t *)ahd->qoutfifo);
549 }
550
551 /*********************** Miscelaneous Support Functions ***********************/
552 /*
553  * Return pointers to the transfer negotiation information
554  * for the specified our_id/remote_id pair.
555  */
556 struct ahd_initiator_tinfo *
557 ahd_fetch_transinfo(struct ahd_softc *ahd, char channel, u_int our_id,
558                     u_int remote_id, struct ahd_tmode_tstate **tstate)
559 {
560         /*
561          * Transfer data structures are stored from the perspective
562          * of the target role.  Since the parameters for a connection
563          * in the initiator role to a given target are the same as
564          * when the roles are reversed, we pretend we are the target.
565          */
566         if (channel == 'B')
567                 our_id += 8;
568         *tstate = ahd->enabled_targets[our_id];
569         return (&(*tstate)->transinfo[remote_id]);
570 }
571
572 uint16_t
573 ahd_inw(struct ahd_softc *ahd, u_int port)
574 {
575         /*
576          * Read high byte first as some registers increment
577          * or have other side effects when the low byte is
578          * read.
579          */
580         uint16_t r = ahd_inb(ahd, port+1) << 8;
581         return r | ahd_inb(ahd, port);
582 }
583
584 void
585 ahd_outw(struct ahd_softc *ahd, u_int port, u_int value)
586 {
587         /*
588          * Write low byte first to accomodate registers
589          * such as PRGMCNT where the order maters.
590          */
591         ahd_outb(ahd, port, value & 0xFF);
592         ahd_outb(ahd, port+1, (value >> 8) & 0xFF);
593 }
594
595 uint32_t
596 ahd_inl(struct ahd_softc *ahd, u_int port)
597 {
598         return ((ahd_inb(ahd, port))
599               | (ahd_inb(ahd, port+1) << 8)
600               | (ahd_inb(ahd, port+2) << 16)
601               | (ahd_inb(ahd, port+3) << 24));
602 }
603
604 void
605 ahd_outl(struct ahd_softc *ahd, u_int port, uint32_t value)
606 {
607         ahd_outb(ahd, port, (value) & 0xFF);
608         ahd_outb(ahd, port+1, ((value) >> 8) & 0xFF);
609         ahd_outb(ahd, port+2, ((value) >> 16) & 0xFF);
610         ahd_outb(ahd, port+3, ((value) >> 24) & 0xFF);
611 }
612
613 uint64_t
614 ahd_inq(struct ahd_softc *ahd, u_int port)
615 {
616         return ((ahd_inb(ahd, port))
617               | (ahd_inb(ahd, port+1) << 8)
618               | (ahd_inb(ahd, port+2) << 16)
619               | (ahd_inb(ahd, port+3) << 24)
620               | (((uint64_t)ahd_inb(ahd, port+4)) << 32)
621               | (((uint64_t)ahd_inb(ahd, port+5)) << 40)
622               | (((uint64_t)ahd_inb(ahd, port+6)) << 48)
623               | (((uint64_t)ahd_inb(ahd, port+7)) << 56));
624 }
625
626 void
627 ahd_outq(struct ahd_softc *ahd, u_int port, uint64_t value)
628 {
629         ahd_outb(ahd, port, value & 0xFF);
630         ahd_outb(ahd, port+1, (value >> 8) & 0xFF);
631         ahd_outb(ahd, port+2, (value >> 16) & 0xFF);
632         ahd_outb(ahd, port+3, (value >> 24) & 0xFF);
633         ahd_outb(ahd, port+4, (value >> 32) & 0xFF);
634         ahd_outb(ahd, port+5, (value >> 40) & 0xFF);
635         ahd_outb(ahd, port+6, (value >> 48) & 0xFF);
636         ahd_outb(ahd, port+7, (value >> 56) & 0xFF);
637 }
638
639 u_int
640 ahd_get_scbptr(struct ahd_softc *ahd)
641 {
642         AHD_ASSERT_MODES(ahd, ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK),
643                          ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK));
644         return (ahd_inb(ahd, SCBPTR) | (ahd_inb(ahd, SCBPTR + 1) << 8));
645 }
646
647 void
648 ahd_set_scbptr(struct ahd_softc *ahd, u_int scbptr)
649 {
650         AHD_ASSERT_MODES(ahd, ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK),
651                          ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK));
652         ahd_outb(ahd, SCBPTR, scbptr & 0xFF);
653         ahd_outb(ahd, SCBPTR+1, (scbptr >> 8) & 0xFF);
654 }
655
656 u_int
657 ahd_get_hnscb_qoff(struct ahd_softc *ahd)
658 {
659         return (ahd_inw_atomic(ahd, HNSCB_QOFF));
660 }
661
662 void
663 ahd_set_hnscb_qoff(struct ahd_softc *ahd, u_int value)
664 {
665         ahd_outw_atomic(ahd, HNSCB_QOFF, value);
666 }
667
668 u_int
669 ahd_get_hescb_qoff(struct ahd_softc *ahd)
670 {
671         return (ahd_inb(ahd, HESCB_QOFF));
672 }
673
674 void
675 ahd_set_hescb_qoff(struct ahd_softc *ahd, u_int value)
676 {
677         ahd_outb(ahd, HESCB_QOFF, value);
678 }
679
680 u_int
681 ahd_get_snscb_qoff(struct ahd_softc *ahd)
682 {
683         u_int oldvalue;
684
685         AHD_ASSERT_MODES(ahd, AHD_MODE_CCHAN_MSK, AHD_MODE_CCHAN_MSK);
686         oldvalue = ahd_inw(ahd, SNSCB_QOFF);
687         ahd_outw(ahd, SNSCB_QOFF, oldvalue);
688         return (oldvalue);
689 }
690
691 void
692 ahd_set_snscb_qoff(struct ahd_softc *ahd, u_int value)
693 {
694         AHD_ASSERT_MODES(ahd, AHD_MODE_CCHAN_MSK, AHD_MODE_CCHAN_MSK);
695         ahd_outw(ahd, SNSCB_QOFF, value);
696 }
697
698 u_int
699 ahd_get_sescb_qoff(struct ahd_softc *ahd)
700 {
701         AHD_ASSERT_MODES(ahd, AHD_MODE_CCHAN_MSK, AHD_MODE_CCHAN_MSK);
702         return (ahd_inb(ahd, SESCB_QOFF));
703 }
704
705 void
706 ahd_set_sescb_qoff(struct ahd_softc *ahd, u_int value)
707 {
708         AHD_ASSERT_MODES(ahd, AHD_MODE_CCHAN_MSK, AHD_MODE_CCHAN_MSK);
709         ahd_outb(ahd, SESCB_QOFF, value);
710 }
711
712 u_int
713 ahd_get_sdscb_qoff(struct ahd_softc *ahd)
714 {
715         AHD_ASSERT_MODES(ahd, AHD_MODE_CCHAN_MSK, AHD_MODE_CCHAN_MSK);
716         return (ahd_inb(ahd, SDSCB_QOFF) | (ahd_inb(ahd, SDSCB_QOFF + 1) << 8));
717 }
718
719 void
720 ahd_set_sdscb_qoff(struct ahd_softc *ahd, u_int value)
721 {
722         AHD_ASSERT_MODES(ahd, AHD_MODE_CCHAN_MSK, AHD_MODE_CCHAN_MSK);
723         ahd_outb(ahd, SDSCB_QOFF, value & 0xFF);
724         ahd_outb(ahd, SDSCB_QOFF+1, (value >> 8) & 0xFF);
725 }
726
727 u_int
728 ahd_inb_scbram(struct ahd_softc *ahd, u_int offset)
729 {
730         u_int value;
731
732         /*
733          * Workaround PCI-X Rev A. hardware bug.
734          * After a host read of SCB memory, the chip
735          * may become confused into thinking prefetch
736          * was required.  This starts the discard timer
737          * running and can cause an unexpected discard
738          * timer interrupt.  The work around is to read
739          * a normal register prior to the exhaustion of
740          * the discard timer.  The mode pointer register
741          * has no side effects and so serves well for
742          * this purpose.
743          *
744          * Razor #528
745          */
746         value = ahd_inb(ahd, offset);
747         if ((ahd->bugs & AHD_PCIX_SCBRAM_RD_BUG) != 0)
748                 ahd_inb(ahd, MODE_PTR);
749         return (value);
750 }
751
752 u_int
753 ahd_inw_scbram(struct ahd_softc *ahd, u_int offset)
754 {
755         return (ahd_inb_scbram(ahd, offset)
756               | (ahd_inb_scbram(ahd, offset+1) << 8));
757 }
758
759 uint32_t
760 ahd_inl_scbram(struct ahd_softc *ahd, u_int offset)
761 {
762         return (ahd_inw_scbram(ahd, offset)
763               | (ahd_inw_scbram(ahd, offset+2) << 16));
764 }
765
766 uint64_t
767 ahd_inq_scbram(struct ahd_softc *ahd, u_int offset)
768 {
769         return (ahd_inl_scbram(ahd, offset)
770               | ((uint64_t)ahd_inl_scbram(ahd, offset+4)) << 32);
771 }
772
773 struct scb *
774 ahd_lookup_scb(struct ahd_softc *ahd, u_int tag)
775 {
776         struct scb* scb;
777
778         if (tag >= AHD_SCB_MAX)
779                 return (NULL);
780         scb = ahd->scb_data.scbindex[tag];
781         if (scb != NULL)
782                 ahd_sync_scb(ahd, scb,
783                              BUS_DMASYNC_POSTREAD|BUS_DMASYNC_POSTWRITE);
784         return (scb);
785 }
786
787 void
788 ahd_swap_with_next_hscb(struct ahd_softc *ahd, struct scb *scb)
789 {
790         struct   hardware_scb *q_hscb;
791         struct   map_node *q_hscb_map;
792         uint32_t saved_hscb_busaddr;
793
794         /*
795          * Our queuing method is a bit tricky.  The card
796          * knows in advance which HSCB (by address) to download,
797          * and we can't disappoint it.  To achieve this, the next
798          * HSCB to download is saved off in ahd->next_queued_hscb.
799          * When we are called to queue "an arbitrary scb",
800          * we copy the contents of the incoming HSCB to the one
801          * the sequencer knows about, swap HSCB pointers and
802          * finally assign the SCB to the tag indexed location
803          * in the scb_array.  This makes sure that we can still
804          * locate the correct SCB by SCB_TAG.
805          */
806         q_hscb = ahd->next_queued_hscb;
807         q_hscb_map = ahd->next_queued_hscb_map;
808         saved_hscb_busaddr = q_hscb->hscb_busaddr;
809         memcpy(q_hscb, scb->hscb, sizeof(*scb->hscb));
810         q_hscb->hscb_busaddr = saved_hscb_busaddr;
811         q_hscb->next_hscb_busaddr = scb->hscb->hscb_busaddr;
812
813         /* Now swap HSCB pointers. */
814         ahd->next_queued_hscb = scb->hscb;
815         ahd->next_queued_hscb_map = scb->hscb_map;
816         scb->hscb = q_hscb;
817         scb->hscb_map = q_hscb_map;
818
819         /* Now define the mapping from tag to SCB in the scbindex */
820         ahd->scb_data.scbindex[SCB_GET_TAG(scb)] = scb;
821 }
822
823 /*
824  * Tell the sequencer about a new transaction to execute.
825  */
826 void
827 ahd_queue_scb(struct ahd_softc *ahd, struct scb *scb)
828 {
829         ahd_swap_with_next_hscb(ahd, scb);
830
831         if (SCBID_IS_NULL(SCB_GET_TAG(scb)))
832                 panic("Attempt to queue invalid SCB tag %x\n",
833                       SCB_GET_TAG(scb));
834
835         /*
836          * Keep a history of SCBs we've downloaded in the qinfifo.
837          */
838         ahd->qinfifo[AHD_QIN_WRAP(ahd->qinfifonext)] = SCB_GET_TAG(scb);
839         ahd->qinfifonext++;
840
841         if (scb->sg_count != 0)
842                 ahd_setup_data_scb(ahd, scb);
843         else
844                 ahd_setup_noxfer_scb(ahd, scb);
845         ahd_setup_scb_common(ahd, scb);
846
847         /*
848          * Make sure our data is consistent from the
849          * perspective of the adapter.
850          */
851         ahd_sync_scb(ahd, scb, BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
852
853 #ifdef AHD_DEBUG
854         if ((ahd_debug & AHD_SHOW_QUEUE) != 0) {
855                 uint64_t host_dataptr;
856
857                 host_dataptr = ahd_le64toh(scb->hscb->dataptr);
858                 printf("%s: Queueing SCB %d:0x%x bus addr 0x%x - 0x%x%x/0x%x\n",
859                        ahd_name(ahd),
860                        SCB_GET_TAG(scb), scb->hscb->scsiid,
861                        ahd_le32toh(scb->hscb->hscb_busaddr),
862                        (u_int)((host_dataptr >> 32) & 0xFFFFFFFF),
863                        (u_int)(host_dataptr & 0xFFFFFFFF),
864                        ahd_le32toh(scb->hscb->datacnt));
865         }
866 #endif
867         /* Tell the adapter about the newly queued SCB */
868         ahd_set_hnscb_qoff(ahd, ahd->qinfifonext);
869 }
870
871 /************************** Interrupt Processing ******************************/
872 void
873 ahd_sync_qoutfifo(struct ahd_softc *ahd, int op)
874 {
875         ahd_dmamap_sync(ahd, ahd->shared_data_dmat, ahd->shared_data_map.dmamap,
876                         /*offset*/0,
877                         /*len*/AHD_SCB_MAX * sizeof(struct ahd_completion), op);
878 }
879
880 void
881 ahd_sync_tqinfifo(struct ahd_softc *ahd, int op)
882 {
883 #ifdef AHD_TARGET_MODE
884         if ((ahd->flags & AHD_TARGETROLE) != 0) {
885                 ahd_dmamap_sync(ahd, ahd->shared_data_dmat,
886                                 ahd->shared_data_map.dmamap,
887                                 ahd_targetcmd_offset(ahd, 0),
888                                 sizeof(struct target_cmd) * AHD_TMODE_CMDS,
889                                 op);
890         }
891 #endif
892 }
893
894 /*
895  * See if the firmware has posted any completed commands
896  * into our in-core command complete fifos.
897  */
898 #define AHD_RUN_QOUTFIFO 0x1
899 #define AHD_RUN_TQINFIFO 0x2
900 u_int
901 ahd_check_cmdcmpltqueues(struct ahd_softc *ahd)
902 {
903         u_int retval;
904
905         retval = 0;
906         ahd_dmamap_sync(ahd, ahd->shared_data_dmat, ahd->shared_data_map.dmamap,
907                         /*offset*/ahd->qoutfifonext * sizeof(*ahd->qoutfifo),
908                         /*len*/sizeof(*ahd->qoutfifo), BUS_DMASYNC_POSTREAD);
909         if (ahd->qoutfifo[ahd->qoutfifonext].valid_tag
910           == ahd->qoutfifonext_valid_tag)
911                 retval |= AHD_RUN_QOUTFIFO;
912 #ifdef AHD_TARGET_MODE
913         if ((ahd->flags & AHD_TARGETROLE) != 0
914          && (ahd->flags & AHD_TQINFIFO_BLOCKED) == 0) {
915                 ahd_dmamap_sync(ahd, ahd->shared_data_dmat,
916                                 ahd->shared_data_map.dmamap,
917                                 ahd_targetcmd_offset(ahd, ahd->tqinfifofnext),
918                                 /*len*/sizeof(struct target_cmd),
919                                 BUS_DMASYNC_POSTREAD);
920                 if (ahd->targetcmds[ahd->tqinfifonext].cmd_valid != 0)
921                         retval |= AHD_RUN_TQINFIFO;
922         }
923 #endif
924         return (retval);
925 }
926
927 /*
928  * Catch an interrupt from the adapter
929  */
930 int
931 ahd_intr(struct ahd_softc *ahd)
932 {
933         u_int   intstat;
934
935         if ((ahd->pause & INTEN) == 0) {
936                 /*
937                  * Our interrupt is not enabled on the chip
938                  * and may be disabled for re-entrancy reasons,
939                  * so just return.  This is likely just a shared
940                  * interrupt.
941                  */
942                 return (0);
943         }
944
945         /*
946          * Instead of directly reading the interrupt status register,
947          * infer the cause of the interrupt by checking our in-core
948          * completion queues.  This avoids a costly PCI bus read in
949          * most cases.
950          */
951         if ((ahd->flags & AHD_ALL_INTERRUPTS) == 0
952          && (ahd_check_cmdcmpltqueues(ahd) != 0))
953                 intstat = CMDCMPLT;
954         else
955                 intstat = ahd_inb(ahd, INTSTAT);
956
957         if ((intstat & INT_PEND) == 0)
958                 return (0);
959
960         if (intstat & CMDCMPLT) {
961                 ahd_outb(ahd, CLRINT, CLRCMDINT);
962
963                 /*
964                  * Ensure that the chip sees that we've cleared
965                  * this interrupt before we walk the output fifo.
966                  * Otherwise, we may, due to posted bus writes,
967                  * clear the interrupt after we finish the scan,
968                  * and after the sequencer has added new entries
969                  * and asserted the interrupt again.
970                  */
971                 if ((ahd->bugs & AHD_INTCOLLISION_BUG) != 0) {
972                         if (ahd_is_paused(ahd)) {
973                                 /*
974                                  * Potentially lost SEQINT.
975                                  * If SEQINTCODE is non-zero,
976                                  * simulate the SEQINT.
977                                  */
978                                 if (ahd_inb(ahd, SEQINTCODE) != NO_SEQINT)
979                                         intstat |= SEQINT;
980                         }
981                 } else {
982                         ahd_flush_device_writes(ahd);
983                 }
984                 ahd_run_qoutfifo(ahd);
985                 ahd->cmdcmplt_counts[ahd->cmdcmplt_bucket]++;
986                 ahd->cmdcmplt_total++;
987 #ifdef AHD_TARGET_MODE
988                 if ((ahd->flags & AHD_TARGETROLE) != 0)
989                         ahd_run_tqinfifo(ahd, /*paused*/FALSE);
990 #endif
991         }
992
993         /*
994          * Handle statuses that may invalidate our cached
995          * copy of INTSTAT separately.
996          */
997         if (intstat == 0xFF && (ahd->features & AHD_REMOVABLE) != 0) {
998                 /* Hot eject.  Do nothing */
999         } else if (intstat & HWERRINT) {
1000                 ahd_handle_hwerrint(ahd);
1001         } else if ((intstat & (PCIINT|SPLTINT)) != 0) {
1002                 ahd->bus_intr(ahd);
1003         } else {
1004
1005                 if ((intstat & SEQINT) != 0)
1006                         ahd_handle_seqint(ahd, intstat);
1007
1008                 if ((intstat & SCSIINT) != 0)
1009                         ahd_handle_scsiint(ahd, intstat);
1010         }
1011         return (1);
1012 }
1013
1014 /******************************** Private Inlines *****************************/
1015 static __inline void
1016 ahd_assert_atn(struct ahd_softc *ahd)
1017 {
1018         ahd_outb(ahd, SCSISIGO, ATNO);
1019 }
1020
1021 /*
1022  * Determine if the current connection has a packetized
1023  * agreement.  This does not necessarily mean that we
1024  * are currently in a packetized transfer.  We could
1025  * just as easily be sending or receiving a message.
1026  */
1027 static int
1028 ahd_currently_packetized(struct ahd_softc *ahd)
1029 {
1030         ahd_mode_state   saved_modes;
1031         int              packetized;
1032
1033         saved_modes = ahd_save_modes(ahd);
1034         if ((ahd->bugs & AHD_PKTIZED_STATUS_BUG) != 0) {
1035                 /*
1036                  * The packetized bit refers to the last
1037                  * connection, not the current one.  Check
1038                  * for non-zero LQISTATE instead.
1039                  */
1040                 ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
1041                 packetized = ahd_inb(ahd, LQISTATE) != 0;
1042         } else {
1043                 ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
1044                 packetized = ahd_inb(ahd, LQISTAT2) & PACKETIZED;
1045         }
1046         ahd_restore_modes(ahd, saved_modes);
1047         return (packetized);
1048 }
1049
1050 static __inline int
1051 ahd_set_active_fifo(struct ahd_softc *ahd)
1052 {
1053         u_int active_fifo;
1054
1055         AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
1056         active_fifo = ahd_inb(ahd, DFFSTAT) & CURRFIFO;
1057         switch (active_fifo) {
1058         case 0:
1059         case 1:
1060                 ahd_set_modes(ahd, active_fifo, active_fifo);
1061                 return (1);
1062         default:
1063                 return (0);
1064         }
1065 }
1066
1067 static __inline void
1068 ahd_unbusy_tcl(struct ahd_softc *ahd, u_int tcl)
1069 {
1070         ahd_busy_tcl(ahd, tcl, SCB_LIST_NULL);
1071 }
1072
1073 /*
1074  * Determine whether the sequencer reported a residual
1075  * for this SCB/transaction.
1076  */
1077 static __inline void
1078 ahd_update_residual(struct ahd_softc *ahd, struct scb *scb)
1079 {
1080         uint32_t sgptr;
1081
1082         sgptr = ahd_le32toh(scb->hscb->sgptr);
1083         if ((sgptr & SG_STATUS_VALID) != 0)
1084                 ahd_calc_residual(ahd, scb);
1085 }
1086
1087 static __inline void
1088 ahd_complete_scb(struct ahd_softc *ahd, struct scb *scb)
1089 {
1090         uint32_t sgptr;
1091
1092         sgptr = ahd_le32toh(scb->hscb->sgptr);
1093         if ((sgptr & SG_STATUS_VALID) != 0)
1094                 ahd_handle_scb_status(ahd, scb);
1095         else
1096                 ahd_done(ahd, scb);
1097 }
1098
1099
1100 /************************* Sequencer Execution Control ************************/
1101 /*
1102  * Restart the sequencer program from address zero
1103  */
1104 static void
1105 ahd_restart(struct ahd_softc *ahd)
1106 {
1107
1108         ahd_pause(ahd);
1109
1110         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
1111
1112         /* No more pending messages */
1113         ahd_clear_msg_state(ahd);
1114         ahd_outb(ahd, SCSISIGO, 0);             /* De-assert BSY */
1115         ahd_outb(ahd, MSG_OUT, MSG_NOOP);       /* No message to send */
1116         ahd_outb(ahd, SXFRCTL1, ahd_inb(ahd, SXFRCTL1) & ~BITBUCKET);
1117         ahd_outb(ahd, SEQINTCTL, 0);
1118         ahd_outb(ahd, LASTPHASE, P_BUSFREE);
1119         ahd_outb(ahd, SEQ_FLAGS, 0);
1120         ahd_outb(ahd, SAVED_SCSIID, 0xFF);
1121         ahd_outb(ahd, SAVED_LUN, 0xFF);
1122
1123         /*
1124          * Ensure that the sequencer's idea of TQINPOS
1125          * matches our own.  The sequencer increments TQINPOS
1126          * only after it sees a DMA complete and a reset could
1127          * occur before the increment leaving the kernel to believe
1128          * the command arrived but the sequencer to not.
1129          */
1130         ahd_outb(ahd, TQINPOS, ahd->tqinfifonext);
1131
1132         /* Always allow reselection */
1133         ahd_outb(ahd, SCSISEQ1,
1134                  ahd_inb(ahd, SCSISEQ_TEMPLATE) & (ENSELI|ENRSELI|ENAUTOATNP));
1135         ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
1136
1137         /*
1138          * Clear any pending sequencer interrupt.  It is no
1139          * longer relevant since we're resetting the Program
1140          * Counter.
1141          */
1142         ahd_outb(ahd, CLRINT, CLRSEQINT);
1143
1144         ahd_outb(ahd, SEQCTL0, FASTMODE|SEQRESET);
1145         ahd_unpause(ahd);
1146 }
1147
1148 static void
1149 ahd_clear_fifo(struct ahd_softc *ahd, u_int fifo)
1150 {
1151         ahd_mode_state   saved_modes;
1152
1153 #ifdef AHD_DEBUG
1154         if ((ahd_debug & AHD_SHOW_FIFOS) != 0)
1155                 printf("%s: Clearing FIFO %d\n", ahd_name(ahd), fifo);
1156 #endif
1157         saved_modes = ahd_save_modes(ahd);
1158         ahd_set_modes(ahd, fifo, fifo);
1159         ahd_outb(ahd, DFFSXFRCTL, RSTCHN|CLRSHCNT);
1160         if ((ahd_inb(ahd, SG_STATE) & FETCH_INPROG) != 0)
1161                 ahd_outb(ahd, CCSGCTL, CCSGRESET);
1162         ahd_outb(ahd, LONGJMP_ADDR + 1, INVALID_ADDR);
1163         ahd_outb(ahd, SG_STATE, 0);
1164         ahd_restore_modes(ahd, saved_modes);
1165 }
1166
1167 /************************* Input/Output Queues ********************************/
1168 /*
1169  * Flush and completed commands that are sitting in the command
1170  * complete queues down on the chip but have yet to be dma'ed back up.
1171  */
1172 static void
1173 ahd_flush_qoutfifo(struct ahd_softc *ahd)
1174 {
1175         struct          scb *scb;
1176         ahd_mode_state  saved_modes;
1177         u_int           saved_scbptr;
1178         u_int           ccscbctl;
1179         u_int           scbid;
1180         u_int           next_scbid;
1181
1182         saved_modes = ahd_save_modes(ahd);
1183
1184         /*
1185          * Flush the good status FIFO for completed packetized commands.
1186          */
1187         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
1188         saved_scbptr = ahd_get_scbptr(ahd);
1189         while ((ahd_inb(ahd, LQISTAT2) & LQIGSAVAIL) != 0) {
1190                 u_int fifo_mode;
1191                 u_int i;
1192                 
1193                 scbid = ahd_inw(ahd, GSFIFO);
1194                 scb = ahd_lookup_scb(ahd, scbid);
1195                 if (scb == NULL) {
1196                         printf("%s: Warning - GSFIFO SCB %d invalid\n",
1197                                ahd_name(ahd), scbid);
1198                         continue;
1199                 }
1200                 /*
1201                  * Determine if this transaction is still active in
1202                  * any FIFO.  If it is, we must flush that FIFO to
1203                  * the host before completing the  command.
1204                  */
1205                 fifo_mode = 0;
1206 rescan_fifos:
1207                 for (i = 0; i < 2; i++) {
1208                         /* Toggle to the other mode. */
1209                         fifo_mode ^= 1;
1210                         ahd_set_modes(ahd, fifo_mode, fifo_mode);
1211
1212                         if (ahd_scb_active_in_fifo(ahd, scb) == 0)
1213                                 continue;
1214
1215                         ahd_run_data_fifo(ahd, scb);
1216
1217                         /*
1218                          * Running this FIFO may cause a CFG4DATA for
1219                          * this same transaction to assert in the other
1220                          * FIFO or a new snapshot SAVEPTRS interrupt
1221                          * in this FIFO.  Even running a FIFO may not
1222                          * clear the transaction if we are still waiting
1223                          * for data to drain to the host. We must loop
1224                          * until the transaction is not active in either
1225                          * FIFO just to be sure.  Reset our loop counter
1226                          * so we will visit both FIFOs again before
1227                          * declaring this transaction finished.  We
1228                          * also delay a bit so that status has a chance
1229                          * to change before we look at this FIFO again.
1230                          */
1231                         ahd_delay(200);
1232                         goto rescan_fifos;
1233                 }
1234                 ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
1235                 ahd_set_scbptr(ahd, scbid);
1236                 if ((ahd_inb_scbram(ahd, SCB_SGPTR) & SG_LIST_NULL) == 0
1237                  && ((ahd_inb_scbram(ahd, SCB_SGPTR) & SG_FULL_RESID) != 0
1238                   || (ahd_inb_scbram(ahd, SCB_RESIDUAL_SGPTR)
1239                       & SG_LIST_NULL) != 0)) {
1240                         u_int comp_head;
1241
1242                         /*
1243                          * The transfer completed with a residual.
1244                          * Place this SCB on the complete DMA list
1245                          * so that we update our in-core copy of the
1246                          * SCB before completing the command.
1247                          */
1248                         ahd_outb(ahd, SCB_SCSI_STATUS, 0);
1249                         ahd_outb(ahd, SCB_SGPTR,
1250                                  ahd_inb_scbram(ahd, SCB_SGPTR)
1251                                  | SG_STATUS_VALID);
1252                         ahd_outw(ahd, SCB_TAG, scbid);
1253                         ahd_outw(ahd, SCB_NEXT_COMPLETE, SCB_LIST_NULL);
1254                         comp_head = ahd_inw(ahd, COMPLETE_DMA_SCB_HEAD);
1255                         if (SCBID_IS_NULL(comp_head)) {
1256                                 ahd_outw(ahd, COMPLETE_DMA_SCB_HEAD, scbid);
1257                                 ahd_outw(ahd, COMPLETE_DMA_SCB_TAIL, scbid);
1258                         } else {
1259                                 u_int tail;
1260
1261                                 tail = ahd_inw(ahd, COMPLETE_DMA_SCB_TAIL);
1262                                 ahd_set_scbptr(ahd, tail);
1263                                 ahd_outw(ahd, SCB_NEXT_COMPLETE, scbid);
1264                                 ahd_outw(ahd, COMPLETE_DMA_SCB_TAIL, scbid);
1265                                 ahd_set_scbptr(ahd, scbid);
1266                         }
1267                 } else
1268                         ahd_complete_scb(ahd, scb);
1269         }
1270         ahd_set_scbptr(ahd, saved_scbptr);
1271
1272         /*
1273          * Setup for command channel portion of flush.
1274          */
1275         ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
1276
1277         /*
1278          * Wait for any inprogress DMA to complete and clear DMA state
1279          * if this if for an SCB in the qinfifo.
1280          */
1281         while (((ccscbctl = ahd_inb(ahd, CCSCBCTL)) & (CCARREN|CCSCBEN)) != 0) {
1282
1283                 if ((ccscbctl & (CCSCBDIR|CCARREN)) == (CCSCBDIR|CCARREN)) {
1284                         if ((ccscbctl & ARRDONE) != 0)
1285                                 break;
1286                 } else if ((ccscbctl & CCSCBDONE) != 0)
1287                         break;
1288                 ahd_delay(200);
1289         }
1290         /*
1291          * We leave the sequencer to cleanup in the case of DMA's to
1292          * update the qoutfifo.  In all other cases (DMA's to the
1293          * chip or a push of an SCB from the COMPLETE_DMA_SCB list),
1294          * we disable the DMA engine so that the sequencer will not
1295          * attempt to handle the DMA completion.
1296          */
1297         if ((ccscbctl & CCSCBDIR) != 0 || (ccscbctl & ARRDONE) != 0)
1298                 ahd_outb(ahd, CCSCBCTL, ccscbctl & ~(CCARREN|CCSCBEN));
1299
1300         /*
1301          * Complete any SCBs that just finished
1302          * being DMA'ed into the qoutfifo.
1303          */
1304         ahd_run_qoutfifo(ahd);
1305
1306         saved_scbptr = ahd_get_scbptr(ahd);
1307         /*
1308          * Manually update/complete any completed SCBs that are waiting to be
1309          * DMA'ed back up to the host.
1310          */
1311         scbid = ahd_inw(ahd, COMPLETE_DMA_SCB_HEAD);
1312         while (!SCBID_IS_NULL(scbid)) {
1313                 uint8_t *hscb_ptr;
1314                 u_int    i;
1315                 
1316                 ahd_set_scbptr(ahd, scbid);
1317                 next_scbid = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
1318                 scb = ahd_lookup_scb(ahd, scbid);
1319                 if (scb == NULL) {
1320                         printf("%s: Warning - DMA-up and complete "
1321                                "SCB %d invalid\n", ahd_name(ahd), scbid);
1322                         continue;
1323                 }
1324                 hscb_ptr = (uint8_t *)scb->hscb;
1325                 for (i = 0; i < sizeof(struct hardware_scb); i++)
1326                         *hscb_ptr++ = ahd_inb_scbram(ahd, SCB_BASE + i);
1327
1328                 ahd_complete_scb(ahd, scb);
1329                 scbid = next_scbid;
1330         }
1331         ahd_outw(ahd, COMPLETE_DMA_SCB_HEAD, SCB_LIST_NULL);
1332         ahd_outw(ahd, COMPLETE_DMA_SCB_TAIL, SCB_LIST_NULL);
1333
1334         scbid = ahd_inw(ahd, COMPLETE_ON_QFREEZE_HEAD);
1335         while (!SCBID_IS_NULL(scbid)) {
1336
1337                 ahd_set_scbptr(ahd, scbid);
1338                 next_scbid = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
1339                 scb = ahd_lookup_scb(ahd, scbid);
1340                 if (scb == NULL) {
1341                         printf("%s: Warning - Complete Qfrz SCB %d invalid\n",
1342                                ahd_name(ahd), scbid);
1343                         continue;
1344                 }
1345
1346                 ahd_complete_scb(ahd, scb);
1347                 scbid = next_scbid;
1348         }
1349         ahd_outw(ahd, COMPLETE_ON_QFREEZE_HEAD, SCB_LIST_NULL);
1350
1351         scbid = ahd_inw(ahd, COMPLETE_SCB_HEAD);
1352         while (!SCBID_IS_NULL(scbid)) {
1353
1354                 ahd_set_scbptr(ahd, scbid);
1355                 next_scbid = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
1356                 scb = ahd_lookup_scb(ahd, scbid);
1357                 if (scb == NULL) {
1358                         printf("%s: Warning - Complete SCB %d invalid\n",
1359                                ahd_name(ahd), scbid);
1360                         continue;
1361                 }
1362
1363                 ahd_complete_scb(ahd, scb);
1364                 scbid = next_scbid;
1365         }
1366         ahd_outw(ahd, COMPLETE_SCB_HEAD, SCB_LIST_NULL);
1367
1368         /*
1369          * Restore state.
1370          */
1371         ahd_set_scbptr(ahd, saved_scbptr);
1372         ahd_restore_modes(ahd, saved_modes);
1373         ahd->flags |= AHD_UPDATE_PEND_CMDS;
1374 }
1375
1376 /*
1377  * Determine if an SCB for a packetized transaction
1378  * is active in a FIFO.
1379  */
1380 static int
1381 ahd_scb_active_in_fifo(struct ahd_softc *ahd, struct scb *scb)
1382 {
1383
1384         /*
1385          * The FIFO is only active for our transaction if
1386          * the SCBPTR matches the SCB's ID and the firmware
1387          * has installed a handler for the FIFO or we have
1388          * a pending SAVEPTRS or CFG4DATA interrupt.
1389          */
1390         if (ahd_get_scbptr(ahd) != SCB_GET_TAG(scb)
1391          || ((ahd_inb(ahd, LONGJMP_ADDR+1) & INVALID_ADDR) != 0
1392           && (ahd_inb(ahd, SEQINTSRC) & (CFG4DATA|SAVEPTRS)) == 0))
1393                 return (0);
1394
1395         return (1);
1396 }
1397
1398 /*
1399  * Run a data fifo to completion for a transaction we know
1400  * has completed across the SCSI bus (good status has been
1401  * received).  We are already set to the correct FIFO mode
1402  * on entry to this routine.
1403  *
1404  * This function attempts to operate exactly as the firmware
1405  * would when running this FIFO.  Care must be taken to update
1406  * this routine any time the firmware's FIFO algorithm is
1407  * changed.
1408  */
1409 static void
1410 ahd_run_data_fifo(struct ahd_softc *ahd, struct scb *scb)
1411 {
1412         u_int seqintsrc;
1413
1414         seqintsrc = ahd_inb(ahd, SEQINTSRC);
1415         if ((seqintsrc & CFG4DATA) != 0) {
1416                 uint32_t datacnt;
1417                 uint32_t sgptr;
1418
1419                 /*
1420                  * Clear full residual flag.
1421                  */
1422                 sgptr = ahd_inl_scbram(ahd, SCB_SGPTR) & ~SG_FULL_RESID;
1423                 ahd_outb(ahd, SCB_SGPTR, sgptr);
1424
1425                 /*
1426                  * Load datacnt and address.
1427                  */
1428                 datacnt = ahd_inl_scbram(ahd, SCB_DATACNT);
1429                 if ((datacnt & AHD_DMA_LAST_SEG) != 0) {
1430                         sgptr |= LAST_SEG;
1431                         ahd_outb(ahd, SG_STATE, 0);
1432                 } else
1433                         ahd_outb(ahd, SG_STATE, LOADING_NEEDED);
1434                 ahd_outq(ahd, HADDR, ahd_inq_scbram(ahd, SCB_DATAPTR));
1435                 ahd_outl(ahd, HCNT, datacnt & AHD_SG_LEN_MASK);
1436                 ahd_outb(ahd, SG_CACHE_PRE, sgptr);
1437                 ahd_outb(ahd, DFCNTRL, PRELOADEN|SCSIEN|HDMAEN);
1438
1439                 /*
1440                  * Initialize Residual Fields.
1441                  */
1442                 ahd_outb(ahd, SCB_RESIDUAL_DATACNT+3, datacnt >> 24);
1443                 ahd_outl(ahd, SCB_RESIDUAL_SGPTR, sgptr & SG_PTR_MASK);
1444
1445                 /*
1446                  * Mark the SCB as having a FIFO in use.
1447                  */
1448                 ahd_outb(ahd, SCB_FIFO_USE_COUNT,
1449                          ahd_inb_scbram(ahd, SCB_FIFO_USE_COUNT) + 1);
1450
1451                 /*
1452                  * Install a "fake" handler for this FIFO.
1453                  */
1454                 ahd_outw(ahd, LONGJMP_ADDR, 0);
1455
1456                 /*
1457                  * Notify the hardware that we have satisfied
1458                  * this sequencer interrupt.
1459                  */
1460                 ahd_outb(ahd, CLRSEQINTSRC, CLRCFG4DATA);
1461         } else if ((seqintsrc & SAVEPTRS) != 0) {
1462                 uint32_t sgptr;
1463                 uint32_t resid;
1464
1465                 if ((ahd_inb(ahd, LONGJMP_ADDR+1)&INVALID_ADDR) != 0) {
1466                         /*
1467                          * Snapshot Save Pointers.  All that
1468                          * is necessary to clear the snapshot
1469                          * is a CLRCHN.
1470                          */
1471                         goto clrchn;
1472                 }
1473
1474                 /*
1475                  * Disable S/G fetch so the DMA engine
1476                  * is available to future users.
1477                  */
1478                 if ((ahd_inb(ahd, SG_STATE) & FETCH_INPROG) != 0)
1479                         ahd_outb(ahd, CCSGCTL, 0);
1480                 ahd_outb(ahd, SG_STATE, 0);
1481
1482                 /*
1483                  * Flush the data FIFO.  Strickly only
1484                  * necessary for Rev A parts.
1485                  */
1486                 ahd_outb(ahd, DFCNTRL, ahd_inb(ahd, DFCNTRL) | FIFOFLUSH);
1487
1488                 /*
1489                  * Calculate residual.
1490                  */
1491                 sgptr = ahd_inl_scbram(ahd, SCB_RESIDUAL_SGPTR);
1492                 resid = ahd_inl(ahd, SHCNT);
1493                 resid |= ahd_inb_scbram(ahd, SCB_RESIDUAL_DATACNT+3) << 24;
1494                 ahd_outl(ahd, SCB_RESIDUAL_DATACNT, resid);
1495                 if ((ahd_inb(ahd, SG_CACHE_SHADOW) & LAST_SEG) == 0) {
1496                         /*
1497                          * Must back up to the correct S/G element.
1498                          * Typically this just means resetting our
1499                          * low byte to the offset in the SG_CACHE,
1500                          * but if we wrapped, we have to correct
1501                          * the other bytes of the sgptr too.
1502                          */
1503                         if ((ahd_inb(ahd, SG_CACHE_SHADOW) & 0x80) != 0
1504                          && (sgptr & 0x80) == 0)
1505                                 sgptr -= 0x100;
1506                         sgptr &= ~0xFF;
1507                         sgptr |= ahd_inb(ahd, SG_CACHE_SHADOW)
1508                                & SG_ADDR_MASK;
1509                         ahd_outl(ahd, SCB_RESIDUAL_SGPTR, sgptr);
1510                         ahd_outb(ahd, SCB_RESIDUAL_DATACNT + 3, 0);
1511                 } else if ((resid & AHD_SG_LEN_MASK) == 0) {
1512                         ahd_outb(ahd, SCB_RESIDUAL_SGPTR,
1513                                  sgptr | SG_LIST_NULL);
1514                 }
1515                 /*
1516                  * Save Pointers.
1517                  */
1518                 ahd_outq(ahd, SCB_DATAPTR, ahd_inq(ahd, SHADDR));
1519                 ahd_outl(ahd, SCB_DATACNT, resid);
1520                 ahd_outl(ahd, SCB_SGPTR, sgptr);
1521                 ahd_outb(ahd, CLRSEQINTSRC, CLRSAVEPTRS);
1522                 ahd_outb(ahd, SEQIMODE,
1523                          ahd_inb(ahd, SEQIMODE) | ENSAVEPTRS);
1524                 /*
1525                  * If the data is to the SCSI bus, we are
1526                  * done, otherwise wait for FIFOEMP.
1527                  */
1528                 if ((ahd_inb(ahd, DFCNTRL) & DIRECTION) != 0)
1529                         goto clrchn;
1530         } else if ((ahd_inb(ahd, SG_STATE) & LOADING_NEEDED) != 0) {
1531                 uint32_t sgptr;
1532                 uint64_t data_addr;
1533                 uint32_t data_len;
1534                 u_int    dfcntrl;
1535
1536                 /*
1537                  * Disable S/G fetch so the DMA engine
1538                  * is available to future users.  We won't
1539                  * be using the DMA engine to load segments.
1540                  */
1541                 if ((ahd_inb(ahd, SG_STATE) & FETCH_INPROG) != 0) {
1542                         ahd_outb(ahd, CCSGCTL, 0);
1543                         ahd_outb(ahd, SG_STATE, LOADING_NEEDED);
1544                 }
1545
1546                 /*
1547                  * Wait for the DMA engine to notice that the
1548                  * host transfer is enabled and that there is
1549                  * space in the S/G FIFO for new segments before
1550                  * loading more segments.
1551                  */
1552                 if ((ahd_inb(ahd, DFSTATUS) & PRELOAD_AVAIL) != 0
1553                  && (ahd_inb(ahd, DFCNTRL) & HDMAENACK) != 0) {
1554
1555                         /*
1556                          * Determine the offset of the next S/G
1557                          * element to load.
1558                          */
1559                         sgptr = ahd_inl_scbram(ahd, SCB_RESIDUAL_SGPTR);
1560                         sgptr &= SG_PTR_MASK;
1561                         if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0) {
1562                                 struct ahd_dma64_seg *sg;
1563
1564                                 sg = ahd_sg_bus_to_virt(ahd, scb, sgptr);
1565                                 data_addr = sg->addr;
1566                                 data_len = sg->len;
1567                                 sgptr += sizeof(*sg);
1568                         } else {
1569                                 struct  ahd_dma_seg *sg;
1570
1571                                 sg = ahd_sg_bus_to_virt(ahd, scb, sgptr);
1572                                 data_addr = sg->len & AHD_SG_HIGH_ADDR_MASK;
1573                                 data_addr <<= 8;
1574                                 data_addr |= sg->addr;
1575                                 data_len = sg->len;
1576                                 sgptr += sizeof(*sg);
1577                         }
1578
1579                         /*
1580                          * Update residual information.
1581                          */
1582                         ahd_outb(ahd, SCB_RESIDUAL_DATACNT+3, data_len >> 24);
1583                         ahd_outl(ahd, SCB_RESIDUAL_SGPTR, sgptr);
1584
1585                         /*
1586                          * Load the S/G.
1587                          */
1588                         if (data_len & AHD_DMA_LAST_SEG) {
1589                                 sgptr |= LAST_SEG;
1590                                 ahd_outb(ahd, SG_STATE, 0);
1591                         }
1592                         ahd_outq(ahd, HADDR, data_addr);
1593                         ahd_outl(ahd, HCNT, data_len & AHD_SG_LEN_MASK);
1594                         ahd_outb(ahd, SG_CACHE_PRE, sgptr & 0xFF);
1595
1596                         /*
1597                          * Advertise the segment to the hardware.
1598                          */
1599                         dfcntrl = ahd_inb(ahd, DFCNTRL)|PRELOADEN|HDMAEN;
1600                         if ((ahd->features & AHD_NEW_DFCNTRL_OPTS) != 0) {
1601                                 /*
1602                                  * Use SCSIENWRDIS so that SCSIEN
1603                                  * is never modified by this
1604                                  * operation.
1605                                  */
1606                                 dfcntrl |= SCSIENWRDIS;
1607                         }
1608                         ahd_outb(ahd, DFCNTRL, dfcntrl);
1609                 }
1610         } else if ((ahd_inb(ahd, SG_CACHE_SHADOW) & LAST_SEG_DONE) != 0) {
1611
1612                 /*
1613                  * Transfer completed to the end of SG list
1614                  * and has flushed to the host.
1615                  */
1616                 ahd_outb(ahd, SCB_SGPTR,
1617                          ahd_inb_scbram(ahd, SCB_SGPTR) | SG_LIST_NULL);
1618                 goto clrchn;
1619         } else if ((ahd_inb(ahd, DFSTATUS) & FIFOEMP) != 0) {
1620 clrchn:
1621                 /*
1622                  * Clear any handler for this FIFO, decrement
1623                  * the FIFO use count for the SCB, and release
1624                  * the FIFO.
1625                  */
1626                 ahd_outb(ahd, LONGJMP_ADDR + 1, INVALID_ADDR);
1627                 ahd_outb(ahd, SCB_FIFO_USE_COUNT,
1628                          ahd_inb_scbram(ahd, SCB_FIFO_USE_COUNT) - 1);
1629                 ahd_outb(ahd, DFFSXFRCTL, CLRCHN);
1630         }
1631 }
1632
1633 /*
1634  * Look for entries in the QoutFIFO that have completed.
1635  * The valid_tag completion field indicates the validity
1636  * of the entry - the valid value toggles each time through
1637  * the queue. We use the sg_status field in the completion
1638  * entry to avoid referencing the hscb if the completion
1639  * occurred with no errors and no residual.  sg_status is
1640  * a copy of the first byte (little endian) of the sgptr
1641  * hscb field.
1642  */
1643 void
1644 ahd_run_qoutfifo(struct ahd_softc *ahd)
1645 {
1646         struct ahd_completion *completion;
1647         struct scb *scb;
1648         u_int  scb_index;
1649
1650         if ((ahd->flags & AHD_RUNNING_QOUTFIFO) != 0)
1651                 panic("ahd_run_qoutfifo recursion");
1652         ahd->flags |= AHD_RUNNING_QOUTFIFO;
1653         ahd_sync_qoutfifo(ahd, BUS_DMASYNC_POSTREAD);
1654         for (;;) {
1655                 completion = &ahd->qoutfifo[ahd->qoutfifonext];
1656
1657                 if (completion->valid_tag != ahd->qoutfifonext_valid_tag)
1658                         break;
1659
1660                 scb_index = ahd_le16toh(completion->tag);
1661                 scb = ahd_lookup_scb(ahd, scb_index);
1662                 if (scb == NULL) {
1663                         printf("%s: WARNING no command for scb %d "
1664                                "(cmdcmplt)\nQOUTPOS = %d\n",
1665                                ahd_name(ahd), scb_index,
1666                                ahd->qoutfifonext);
1667                         ahd_dump_card_state(ahd);
1668                 } else if ((completion->sg_status & SG_STATUS_VALID) != 0) {
1669                         ahd_handle_scb_status(ahd, scb);
1670                 } else {
1671                         ahd_done(ahd, scb);
1672                 }
1673
1674                 ahd->qoutfifonext = (ahd->qoutfifonext+1) & (AHD_QOUT_SIZE-1);
1675                 if (ahd->qoutfifonext == 0)
1676                         ahd->qoutfifonext_valid_tag ^= QOUTFIFO_ENTRY_VALID;
1677         }
1678         ahd->flags &= ~AHD_RUNNING_QOUTFIFO;
1679 }
1680
1681 /************************* Interrupt Handling *********************************/
1682 void
1683 ahd_handle_hwerrint(struct ahd_softc *ahd)
1684 {
1685         /*
1686          * Some catastrophic hardware error has occurred.
1687          * Print it for the user and disable the controller.
1688          */
1689         int i;
1690         int error;
1691
1692         error = ahd_inb(ahd, ERROR);
1693         for (i = 0; i < num_errors; i++) {
1694                 if ((error & ahd_hard_errors[i].errno) != 0)
1695                         printf("%s: hwerrint, %s\n",
1696                                ahd_name(ahd), ahd_hard_errors[i].errmesg);
1697         }
1698
1699         ahd_dump_card_state(ahd);
1700         panic("BRKADRINT");
1701
1702         /* Tell everyone that this HBA is no longer available */
1703         ahd_abort_scbs(ahd, CAM_TARGET_WILDCARD, ALL_CHANNELS,
1704                        CAM_LUN_WILDCARD, SCB_LIST_NULL, ROLE_UNKNOWN,
1705                        CAM_NO_HBA);
1706
1707         /* Tell the system that this controller has gone away. */
1708         ahd_free(ahd);
1709 }
1710
1711 #ifdef AHD_DEBUG
1712 static void
1713 ahd_dump_sglist(struct scb *scb)
1714 {
1715         int i;
1716
1717         if (scb->sg_count > 0) {
1718                 if ((scb->ahd_softc->flags & AHD_64BIT_ADDRESSING) != 0) {
1719                         struct ahd_dma64_seg *sg_list;
1720
1721                         sg_list = (struct ahd_dma64_seg*)scb->sg_list;
1722                         for (i = 0; i < scb->sg_count; i++) {
1723                                 uint64_t addr;
1724                                 uint32_t len;
1725
1726                                 addr = ahd_le64toh(sg_list[i].addr);
1727                                 len = ahd_le32toh(sg_list[i].len);
1728                                 printf("sg[%d] - Addr 0x%x%x : Length %d%s\n",
1729                                        i,
1730                                        (uint32_t)((addr >> 32) & 0xFFFFFFFF),
1731                                        (uint32_t)(addr & 0xFFFFFFFF),
1732                                        sg_list[i].len & AHD_SG_LEN_MASK,
1733                                        (sg_list[i].len & AHD_DMA_LAST_SEG)
1734                                      ? " Last" : "");
1735                         }
1736                 } else {
1737                         struct ahd_dma_seg *sg_list;
1738
1739                         sg_list = (struct ahd_dma_seg*)scb->sg_list;
1740                         for (i = 0; i < scb->sg_count; i++) {
1741                                 uint32_t len;
1742
1743                                 len = ahd_le32toh(sg_list[i].len);
1744                                 printf("sg[%d] - Addr 0x%x%x : Length %d%s\n",
1745                                        i,
1746                                        (len & AHD_SG_HIGH_ADDR_MASK) >> 24,
1747                                        ahd_le32toh(sg_list[i].addr),
1748                                        len & AHD_SG_LEN_MASK,
1749                                        len & AHD_DMA_LAST_SEG ? " Last" : "");
1750                         }
1751                 }
1752         }
1753 }
1754 #endif  /*  AHD_DEBUG  */
1755
1756 void
1757 ahd_handle_seqint(struct ahd_softc *ahd, u_int intstat)
1758 {
1759         u_int seqintcode;
1760
1761         /*
1762          * Save the sequencer interrupt code and clear the SEQINT
1763          * bit. We will unpause the sequencer, if appropriate,
1764          * after servicing the request.
1765          */
1766         seqintcode = ahd_inb(ahd, SEQINTCODE);
1767         ahd_outb(ahd, CLRINT, CLRSEQINT);
1768         if ((ahd->bugs & AHD_INTCOLLISION_BUG) != 0) {
1769                 /*
1770                  * Unpause the sequencer and let it clear
1771                  * SEQINT by writing NO_SEQINT to it.  This
1772                  * will cause the sequencer to be paused again,
1773                  * which is the expected state of this routine.
1774                  */
1775                 ahd_unpause(ahd);
1776                 while (!ahd_is_paused(ahd))
1777                         ;
1778                 ahd_outb(ahd, CLRINT, CLRSEQINT);
1779         }
1780         ahd_update_modes(ahd);
1781 #ifdef AHD_DEBUG
1782         if ((ahd_debug & AHD_SHOW_MISC) != 0)
1783                 printf("%s: Handle Seqint Called for code %d\n",
1784                        ahd_name(ahd), seqintcode);
1785 #endif
1786         switch (seqintcode) {
1787         case ENTERING_NONPACK:
1788         {
1789                 struct  scb *scb;
1790                 u_int   scbid;
1791
1792                 AHD_ASSERT_MODES(ahd, ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK),
1793                                  ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK));
1794                 scbid = ahd_get_scbptr(ahd);
1795                 scb = ahd_lookup_scb(ahd, scbid);
1796                 if (scb == NULL) {
1797                         /*
1798                          * Somehow need to know if this
1799                          * is from a selection or reselection.
1800                          * From that, we can determine target
1801                          * ID so we at least have an I_T nexus.
1802                          */
1803                 } else {
1804                         ahd_outb(ahd, SAVED_SCSIID, scb->hscb->scsiid);
1805                         ahd_outb(ahd, SAVED_LUN, scb->hscb->lun);
1806                         ahd_outb(ahd, SEQ_FLAGS, 0x0);
1807                 }
1808                 if ((ahd_inb(ahd, LQISTAT2) & LQIPHASE_OUTPKT) != 0
1809                  && (ahd_inb(ahd, SCSISIGO) & ATNO) != 0) {
1810                         /*
1811                          * Phase change after read stream with
1812                          * CRC error with P0 asserted on last
1813                          * packet.
1814                          */
1815 #ifdef AHD_DEBUG
1816                         if ((ahd_debug & AHD_SHOW_RECOVERY) != 0)
1817                                 printf("%s: Assuming LQIPHASE_NLQ with "
1818                                        "P0 assertion\n", ahd_name(ahd));
1819 #endif
1820                 }
1821 #ifdef AHD_DEBUG
1822                 if ((ahd_debug & AHD_SHOW_RECOVERY) != 0)
1823                         printf("%s: Entering NONPACK\n", ahd_name(ahd));
1824 #endif
1825                 break;
1826         }
1827         case INVALID_SEQINT:
1828                 printf("%s: Invalid Sequencer interrupt occurred, "
1829                        "resetting channel.\n",
1830                        ahd_name(ahd));
1831 #ifdef AHD_DEBUG
1832                 if ((ahd_debug & AHD_SHOW_RECOVERY) != 0)
1833                         ahd_dump_card_state(ahd);
1834 #endif
1835                 ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
1836                 break;
1837         case STATUS_OVERRUN:
1838         {
1839                 struct  scb *scb;
1840                 u_int   scbid;
1841
1842                 scbid = ahd_get_scbptr(ahd);
1843                 scb = ahd_lookup_scb(ahd, scbid);
1844                 if (scb != NULL)
1845                         ahd_print_path(ahd, scb);
1846                 else
1847                         printf("%s: ", ahd_name(ahd));
1848                 printf("SCB %d Packetized Status Overrun", scbid);
1849                 ahd_dump_card_state(ahd);
1850                 ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
1851                 break;
1852         }
1853         case CFG4ISTAT_INTR:
1854         {
1855                 struct  scb *scb;
1856                 u_int   scbid;
1857
1858                 scbid = ahd_get_scbptr(ahd);
1859                 scb = ahd_lookup_scb(ahd, scbid);
1860                 if (scb == NULL) {
1861                         ahd_dump_card_state(ahd);
1862                         printf("CFG4ISTAT: Free SCB %d referenced", scbid);
1863                         panic("For safety");
1864                 }
1865                 ahd_outq(ahd, HADDR, scb->sense_busaddr);
1866                 ahd_outw(ahd, HCNT, AHD_SENSE_BUFSIZE);
1867                 ahd_outb(ahd, HCNT + 2, 0);
1868                 ahd_outb(ahd, SG_CACHE_PRE, SG_LAST_SEG);
1869                 ahd_outb(ahd, DFCNTRL, PRELOADEN|SCSIEN|HDMAEN);
1870                 break;
1871         }
1872         case ILLEGAL_PHASE:
1873         {
1874                 u_int bus_phase;
1875
1876                 bus_phase = ahd_inb(ahd, SCSISIGI) & PHASE_MASK;
1877                 printf("%s: ILLEGAL_PHASE 0x%x\n",
1878                        ahd_name(ahd), bus_phase);
1879
1880                 switch (bus_phase) {
1881                 case P_DATAOUT:
1882                 case P_DATAIN:
1883                 case P_DATAOUT_DT:
1884                 case P_DATAIN_DT:
1885                 case P_MESGOUT:
1886                 case P_STATUS:
1887                 case P_MESGIN:
1888                         ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
1889                         printf("%s: Issued Bus Reset.\n", ahd_name(ahd));
1890                         break;
1891                 case P_COMMAND:
1892                 {
1893                         struct  ahd_devinfo devinfo;
1894                         struct  scb *scb;
1895                         struct  ahd_initiator_tinfo *targ_info;
1896                         struct  ahd_tmode_tstate *tstate;
1897                         struct  ahd_transinfo *tinfo;
1898                         u_int   scbid;
1899
1900                         /*
1901                          * If a target takes us into the command phase
1902                          * assume that it has been externally reset and
1903                          * has thus lost our previous packetized negotiation
1904                          * agreement.  Since we have not sent an identify
1905                          * message and may not have fully qualified the
1906                          * connection, we change our command to TUR, assert
1907                          * ATN and ABORT the task when we go to message in
1908                          * phase.  The OSM will see the REQUEUE_REQUEST
1909                          * status and retry the command.
1910                          */
1911                         scbid = ahd_get_scbptr(ahd);
1912                         scb = ahd_lookup_scb(ahd, scbid);
1913                         if (scb == NULL) {
1914                                 printf("Invalid phase with no valid SCB.  "
1915                                        "Resetting bus.\n");
1916                                 ahd_reset_channel(ahd, 'A',
1917                                                   /*Initiate Reset*/TRUE);
1918                                 break;
1919                         }
1920                         ahd_compile_devinfo(&devinfo, SCB_GET_OUR_ID(scb),
1921                                             SCB_GET_TARGET(ahd, scb),
1922                                             SCB_GET_LUN(scb),
1923                                             SCB_GET_CHANNEL(ahd, scb),
1924                                             ROLE_INITIATOR);
1925                         targ_info = ahd_fetch_transinfo(ahd,
1926                                                         devinfo.channel,
1927                                                         devinfo.our_scsiid,
1928                                                         devinfo.target,
1929                                                         &tstate);
1930                         tinfo = &targ_info->curr;
1931                         ahd_set_width(ahd, &devinfo, MSG_EXT_WDTR_BUS_8_BIT,
1932                                       AHD_TRANS_ACTIVE, /*paused*/TRUE);
1933                         ahd_set_syncrate(ahd, &devinfo, /*period*/0,
1934                                          /*offset*/0, /*ppr_options*/0,
1935                                          AHD_TRANS_ACTIVE, /*paused*/TRUE);
1936                         /* Hand-craft TUR command */
1937                         ahd_outb(ahd, SCB_CDB_STORE, 0);
1938                         ahd_outb(ahd, SCB_CDB_STORE+1, 0);
1939                         ahd_outb(ahd, SCB_CDB_STORE+2, 0);
1940                         ahd_outb(ahd, SCB_CDB_STORE+3, 0);
1941                         ahd_outb(ahd, SCB_CDB_STORE+4, 0);
1942                         ahd_outb(ahd, SCB_CDB_STORE+5, 0);
1943                         ahd_outb(ahd, SCB_CDB_LEN, 6);
1944                         scb->hscb->control &= ~(TAG_ENB|SCB_TAG_TYPE);
1945                         scb->hscb->control |= MK_MESSAGE;
1946                         ahd_outb(ahd, SCB_CONTROL, scb->hscb->control);
1947                         ahd_outb(ahd, MSG_OUT, HOST_MSG);
1948                         ahd_outb(ahd, SAVED_SCSIID, scb->hscb->scsiid);
1949                         /*
1950                          * The lun is 0, regardless of the SCB's lun
1951                          * as we have not sent an identify message.
1952                          */
1953                         ahd_outb(ahd, SAVED_LUN, 0);
1954                         ahd_outb(ahd, SEQ_FLAGS, 0);
1955                         ahd_assert_atn(ahd);
1956                         scb->flags &= ~SCB_PACKETIZED;
1957                         scb->flags |= SCB_ABORT|SCB_EXTERNAL_RESET;
1958                         ahd_freeze_devq(ahd, scb);
1959                         ahd_set_transaction_status(scb, CAM_REQUEUE_REQ);
1960                         ahd_freeze_scb(scb);
1961
1962                         /* Notify XPT */
1963                         ahd_send_async(ahd, devinfo.channel, devinfo.target,
1964                                        CAM_LUN_WILDCARD, AC_SENT_BDR);
1965
1966                         /*
1967                          * Allow the sequencer to continue with
1968                          * non-pack processing.
1969                          */
1970                         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
1971                         ahd_outb(ahd, CLRLQOINT1, CLRLQOPHACHGINPKT);
1972                         if ((ahd->bugs & AHD_CLRLQO_AUTOCLR_BUG) != 0) {
1973                                 ahd_outb(ahd, CLRLQOINT1, 0);
1974                         }
1975 #ifdef AHD_DEBUG
1976                         if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) {
1977                                 ahd_print_path(ahd, scb);
1978                                 printf("Unexpected command phase from "
1979                                        "packetized target\n");
1980                         }
1981 #endif
1982                         break;
1983                 }
1984                 }
1985                 break;
1986         }
1987         case CFG4OVERRUN:
1988         {
1989                 struct  scb *scb;
1990                 u_int   scb_index;
1991                 
1992 #ifdef AHD_DEBUG
1993                 if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) {
1994                         printf("%s: CFG4OVERRUN mode = %x\n", ahd_name(ahd),
1995                                ahd_inb(ahd, MODE_PTR));
1996                 }
1997 #endif
1998                 scb_index = ahd_get_scbptr(ahd);
1999                 scb = ahd_lookup_scb(ahd, scb_index);
2000                 if (scb == NULL) {
2001                         /*
2002                          * Attempt to transfer to an SCB that is
2003                          * not outstanding.
2004                          */
2005                         ahd_assert_atn(ahd);
2006                         ahd_outb(ahd, MSG_OUT, HOST_MSG);
2007                         ahd->msgout_buf[0] = MSG_ABORT_TASK;
2008                         ahd->msgout_len = 1;
2009                         ahd->msgout_index = 0;
2010                         ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
2011                         /*
2012                          * Clear status received flag to prevent any
2013                          * attempt to complete this bogus SCB.
2014                          */
2015                         ahd_outb(ahd, SCB_CONTROL,
2016                                  ahd_inb_scbram(ahd, SCB_CONTROL)
2017                                  & ~STATUS_RCVD);
2018                 }
2019                 break;
2020         }
2021         case DUMP_CARD_STATE:
2022         {
2023                 ahd_dump_card_state(ahd);
2024                 break;
2025         }
2026         case PDATA_REINIT:
2027         {
2028 #ifdef AHD_DEBUG
2029                 if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) {
2030                         printf("%s: PDATA_REINIT - DFCNTRL = 0x%x "
2031                                "SG_CACHE_SHADOW = 0x%x\n",
2032                                ahd_name(ahd), ahd_inb(ahd, DFCNTRL),
2033                                ahd_inb(ahd, SG_CACHE_SHADOW));
2034                 }
2035 #endif
2036                 ahd_reinitialize_dataptrs(ahd);
2037                 break;
2038         }
2039         case HOST_MSG_LOOP:
2040         {
2041                 struct ahd_devinfo devinfo;
2042
2043                 /*
2044                  * The sequencer has encountered a message phase
2045                  * that requires host assistance for completion.
2046                  * While handling the message phase(s), we will be
2047                  * notified by the sequencer after each byte is
2048                  * transfered so we can track bus phase changes.
2049                  *
2050                  * If this is the first time we've seen a HOST_MSG_LOOP
2051                  * interrupt, initialize the state of the host message
2052                  * loop.
2053                  */
2054                 ahd_fetch_devinfo(ahd, &devinfo);
2055                 if (ahd->msg_type == MSG_TYPE_NONE) {
2056                         struct scb *scb;
2057                         u_int scb_index;
2058                         u_int bus_phase;
2059
2060                         bus_phase = ahd_inb(ahd, SCSISIGI) & PHASE_MASK;
2061                         if (bus_phase != P_MESGIN
2062                          && bus_phase != P_MESGOUT) {
2063                                 printf("ahd_intr: HOST_MSG_LOOP bad "
2064                                        "phase 0x%x\n", bus_phase);
2065                                 /*
2066                                  * Probably transitioned to bus free before
2067                                  * we got here.  Just punt the message.
2068                                  */
2069                                 ahd_dump_card_state(ahd);
2070                                 ahd_clear_intstat(ahd);
2071                                 ahd_restart(ahd);
2072                                 return;
2073                         }
2074
2075                         scb_index = ahd_get_scbptr(ahd);
2076                         scb = ahd_lookup_scb(ahd, scb_index);
2077                         if (devinfo.role == ROLE_INITIATOR) {
2078                                 if (bus_phase == P_MESGOUT)
2079                                         ahd_setup_initiator_msgout(ahd,
2080                                                                    &devinfo,
2081                                                                    scb);
2082                                 else {
2083                                         ahd->msg_type =
2084                                             MSG_TYPE_INITIATOR_MSGIN;
2085                                         ahd->msgin_index = 0;
2086                                 }
2087                         }
2088 #ifdef AHD_TARGET_MODE
2089                         else {
2090                                 if (bus_phase == P_MESGOUT) {
2091                                         ahd->msg_type =
2092                                             MSG_TYPE_TARGET_MSGOUT;
2093                                         ahd->msgin_index = 0;
2094                                 }
2095                                 else 
2096                                         ahd_setup_target_msgin(ahd,
2097                                                                &devinfo,
2098                                                                scb);
2099                         }
2100 #endif
2101                 }
2102
2103                 ahd_handle_message_phase(ahd);
2104                 break;
2105         }
2106         case NO_MATCH:
2107         {
2108                 /* Ensure we don't leave the selection hardware on */
2109                 AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
2110                 ahd_outb(ahd, SCSISEQ0, ahd_inb(ahd, SCSISEQ0) & ~ENSELO);
2111
2112                 printf("%s:%c:%d: no active SCB for reconnecting "
2113                        "target - issuing BUS DEVICE RESET\n",
2114                        ahd_name(ahd), 'A', ahd_inb(ahd, SELID) >> 4);
2115                 printf("SAVED_SCSIID == 0x%x, SAVED_LUN == 0x%x, "
2116                        "REG0 == 0x%x ACCUM = 0x%x\n",
2117                        ahd_inb(ahd, SAVED_SCSIID), ahd_inb(ahd, SAVED_LUN),
2118                        ahd_inw(ahd, REG0), ahd_inb(ahd, ACCUM));
2119                 printf("SEQ_FLAGS == 0x%x, SCBPTR == 0x%x, BTT == 0x%x, "
2120                        "SINDEX == 0x%x\n",
2121                        ahd_inb(ahd, SEQ_FLAGS), ahd_get_scbptr(ahd),
2122                        ahd_find_busy_tcl(ahd,
2123                                          BUILD_TCL(ahd_inb(ahd, SAVED_SCSIID),
2124                                                    ahd_inb(ahd, SAVED_LUN))),
2125                        ahd_inw(ahd, SINDEX));
2126                 printf("SELID == 0x%x, SCB_SCSIID == 0x%x, SCB_LUN == 0x%x, "
2127                        "SCB_CONTROL == 0x%x\n",
2128                        ahd_inb(ahd, SELID), ahd_inb_scbram(ahd, SCB_SCSIID),
2129                        ahd_inb_scbram(ahd, SCB_LUN),
2130                        ahd_inb_scbram(ahd, SCB_CONTROL));
2131                 printf("SCSIBUS[0] == 0x%x, SCSISIGI == 0x%x\n",
2132                        ahd_inb(ahd, SCSIBUS), ahd_inb(ahd, SCSISIGI));
2133                 printf("SXFRCTL0 == 0x%x\n", ahd_inb(ahd, SXFRCTL0));
2134                 printf("SEQCTL0 == 0x%x\n", ahd_inb(ahd, SEQCTL0));
2135                 ahd_dump_card_state(ahd);
2136                 ahd->msgout_buf[0] = MSG_BUS_DEV_RESET;
2137                 ahd->msgout_len = 1;
2138                 ahd->msgout_index = 0;
2139                 ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
2140                 ahd_outb(ahd, MSG_OUT, HOST_MSG);
2141                 ahd_assert_atn(ahd);
2142                 break;
2143         }
2144         case PROTO_VIOLATION:
2145         {
2146                 ahd_handle_proto_violation(ahd);
2147                 break;
2148         }
2149         case IGN_WIDE_RES:
2150         {
2151                 struct ahd_devinfo devinfo;
2152
2153                 ahd_fetch_devinfo(ahd, &devinfo);
2154                 ahd_handle_ign_wide_residue(ahd, &devinfo);
2155                 break;
2156         }
2157         case BAD_PHASE:
2158         {
2159                 u_int lastphase;
2160
2161                 lastphase = ahd_inb(ahd, LASTPHASE);
2162                 printf("%s:%c:%d: unknown scsi bus phase %x, "
2163                        "lastphase = 0x%x.  Attempting to continue\n",
2164                        ahd_name(ahd), 'A',
2165                        SCSIID_TARGET(ahd, ahd_inb(ahd, SAVED_SCSIID)),
2166                        lastphase, ahd_inb(ahd, SCSISIGI));
2167                 break;
2168         }
2169         case MISSED_BUSFREE:
2170         {
2171                 u_int lastphase;
2172
2173                 lastphase = ahd_inb(ahd, LASTPHASE);
2174                 printf("%s:%c:%d: Missed busfree. "
2175                        "Lastphase = 0x%x, Curphase = 0x%x\n",
2176                        ahd_name(ahd), 'A',
2177                        SCSIID_TARGET(ahd, ahd_inb(ahd, SAVED_SCSIID)),
2178                        lastphase, ahd_inb(ahd, SCSISIGI));
2179                 ahd_restart(ahd);
2180                 return;
2181         }
2182         case DATA_OVERRUN:
2183         {
2184                 /*
2185                  * When the sequencer detects an overrun, it
2186                  * places the controller in "BITBUCKET" mode
2187                  * and allows the target to complete its transfer.
2188                  * Unfortunately, none of the counters get updated
2189                  * when the controller is in this mode, so we have
2190                  * no way of knowing how large the overrun was.
2191                  */
2192                 struct  scb *scb;
2193                 u_int   scbindex;
2194 #ifdef AHD_DEBUG
2195                 u_int   lastphase;
2196 #endif
2197
2198                 scbindex = ahd_get_scbptr(ahd);
2199                 scb = ahd_lookup_scb(ahd, scbindex);
2200 #ifdef AHD_DEBUG
2201                 lastphase = ahd_inb(ahd, LASTPHASE);
2202                 if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) {
2203                         ahd_print_path(ahd, scb);
2204                         printf("data overrun detected %s.  Tag == 0x%x.\n",
2205                                ahd_lookup_phase_entry(lastphase)->phasemsg,
2206                                SCB_GET_TAG(scb));
2207                         ahd_print_path(ahd, scb);
2208                         printf("%s seen Data Phase.  Length = %ld.  "
2209                                "NumSGs = %d.\n",
2210                                ahd_inb(ahd, SEQ_FLAGS) & DPHASE
2211                                ? "Have" : "Haven't",
2212                                ahd_get_transfer_length(scb), scb->sg_count);
2213                         ahd_dump_sglist(scb);
2214                 }
2215 #endif
2216
2217                 /*
2218                  * Set this and it will take effect when the
2219                  * target does a command complete.
2220                  */
2221                 ahd_freeze_devq(ahd, scb);
2222                 ahd_set_transaction_status(scb, CAM_DATA_RUN_ERR);
2223                 ahd_freeze_scb(scb);
2224                 break;
2225         }
2226         case MKMSG_FAILED:
2227         {
2228                 struct ahd_devinfo devinfo;
2229                 struct scb *scb;
2230                 u_int scbid;
2231
2232                 ahd_fetch_devinfo(ahd, &devinfo);
2233                 printf("%s:%c:%d:%d: Attempt to issue message failed\n",
2234                        ahd_name(ahd), devinfo.channel, devinfo.target,
2235                        devinfo.lun);
2236                 scbid = ahd_get_scbptr(ahd);
2237                 scb = ahd_lookup_scb(ahd, scbid);
2238                 if (scb != NULL
2239                  && (scb->flags & SCB_RECOVERY_SCB) != 0)
2240                         /*
2241                          * Ensure that we didn't put a second instance of this
2242                          * SCB into the QINFIFO.
2243                          */
2244                         ahd_search_qinfifo(ahd, SCB_GET_TARGET(ahd, scb),
2245                                            SCB_GET_CHANNEL(ahd, scb),
2246                                            SCB_GET_LUN(scb), SCB_GET_TAG(scb),
2247                                            ROLE_INITIATOR, /*status*/0,
2248                                            SEARCH_REMOVE);
2249                 ahd_outb(ahd, SCB_CONTROL,
2250                          ahd_inb_scbram(ahd, SCB_CONTROL) & ~MK_MESSAGE);
2251                 break;
2252         }
2253         case TASKMGMT_FUNC_COMPLETE:
2254         {
2255                 u_int   scbid;
2256                 struct  scb *scb;
2257
2258                 scbid = ahd_get_scbptr(ahd);
2259                 scb = ahd_lookup_scb(ahd, scbid);
2260                 if (scb != NULL) {
2261                         u_int      lun;
2262                         u_int      tag;
2263                         cam_status error;
2264
2265                         ahd_print_path(ahd, scb);
2266                         printf("Task Management Func 0x%x Complete\n",
2267                                scb->hscb->task_management);
2268                         lun = CAM_LUN_WILDCARD;
2269                         tag = SCB_LIST_NULL;
2270
2271                         switch (scb->hscb->task_management) {
2272                         case SIU_TASKMGMT_ABORT_TASK:
2273                                 tag = SCB_GET_TAG(scb);
2274                         case SIU_TASKMGMT_ABORT_TASK_SET:
2275                         case SIU_TASKMGMT_CLEAR_TASK_SET:
2276                                 lun = scb->hscb->lun;
2277                                 error = CAM_REQ_ABORTED;
2278                                 ahd_abort_scbs(ahd, SCB_GET_TARGET(ahd, scb),
2279                                                'A', lun, tag, ROLE_INITIATOR,
2280                                                error);
2281                                 break;
2282                         case SIU_TASKMGMT_LUN_RESET:
2283                                 lun = scb->hscb->lun;
2284                         case SIU_TASKMGMT_TARGET_RESET:
2285                         {
2286                                 struct ahd_devinfo devinfo;
2287
2288                                 ahd_scb_devinfo(ahd, &devinfo, scb);
2289                                 error = CAM_BDR_SENT;
2290                                 ahd_handle_devreset(ahd, &devinfo, lun,
2291                                                     CAM_BDR_SENT,
2292                                                     lun != CAM_LUN_WILDCARD
2293                                                     ? "Lun Reset"
2294                                                     : "Target Reset",
2295                                                     /*verbose_level*/0);
2296                                 break;
2297                         }
2298                         default:
2299                                 panic("Unexpected TaskMgmt Func\n");
2300                                 break;
2301                         }
2302                 }
2303                 break;
2304         }
2305         case TASKMGMT_CMD_CMPLT_OKAY:
2306         {
2307                 u_int   scbid;
2308                 struct  scb *scb;
2309
2310                 /*
2311                  * An ABORT TASK TMF failed to be delivered before
2312                  * the targeted command completed normally.
2313                  */
2314                 scbid = ahd_get_scbptr(ahd);
2315                 scb = ahd_lookup_scb(ahd, scbid);
2316                 if (scb != NULL) {
2317                         /*
2318                          * Remove the second instance of this SCB from
2319                          * the QINFIFO if it is still there.
2320                          */
2321                         ahd_print_path(ahd, scb);
2322                         printf("SCB completes before TMF\n");
2323                         /*
2324                          * Handle losing the race.  Wait until any
2325                          * current selection completes.  We will then
2326                          * set the TMF back to zero in this SCB so that
2327                          * the sequencer doesn't bother to issue another
2328                          * sequencer interrupt for its completion.
2329                          */
2330                         while ((ahd_inb(ahd, SCSISEQ0) & ENSELO) != 0
2331                             && (ahd_inb(ahd, SSTAT0) & SELDO) == 0
2332                             && (ahd_inb(ahd, SSTAT1) & SELTO) == 0)
2333                                 ;
2334                         ahd_outb(ahd, SCB_TASK_MANAGEMENT, 0);
2335                         ahd_search_qinfifo(ahd, SCB_GET_TARGET(ahd, scb),
2336                                            SCB_GET_CHANNEL(ahd, scb),  
2337                                            SCB_GET_LUN(scb), SCB_GET_TAG(scb), 
2338                                            ROLE_INITIATOR, /*status*/0,   
2339                                            SEARCH_REMOVE);
2340                 }
2341                 break;
2342         }
2343         case TRACEPOINT0:
2344         case TRACEPOINT1:
2345         case TRACEPOINT2:
2346         case TRACEPOINT3:
2347                 printf("%s: Tracepoint %d\n", ahd_name(ahd),
2348                        seqintcode - TRACEPOINT0);
2349                 break;
2350         case NO_SEQINT:
2351                 break;
2352         case SAW_HWERR:
2353                 ahd_handle_hwerrint(ahd);
2354                 break;
2355         default:
2356                 printf("%s: Unexpected SEQINTCODE %d\n", ahd_name(ahd),
2357                        seqintcode);
2358                 break;
2359         }
2360         /*
2361          *  The sequencer is paused immediately on
2362          *  a SEQINT, so we should restart it when
2363          *  we're done.
2364          */
2365         ahd_unpause(ahd);
2366 }
2367
2368 void
2369 ahd_handle_scsiint(struct ahd_softc *ahd, u_int intstat)
2370 {
2371         struct scb      *scb;
2372         u_int            status0;
2373         u_int            status3;
2374         u_int            status;
2375         u_int            lqistat1;
2376         u_int            lqostat0;
2377         u_int            scbid;
2378         u_int            busfreetime;
2379
2380         ahd_update_modes(ahd);
2381         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
2382
2383         status3 = ahd_inb(ahd, SSTAT3) & (NTRAMPERR|OSRAMPERR);
2384         status0 = ahd_inb(ahd, SSTAT0) & (IOERR|OVERRUN|SELDI|SELDO);
2385         status = ahd_inb(ahd, SSTAT1) & (SELTO|SCSIRSTI|BUSFREE|SCSIPERR);
2386         lqistat1 = ahd_inb(ahd, LQISTAT1);
2387         lqostat0 = ahd_inb(ahd, LQOSTAT0);
2388         busfreetime = ahd_inb(ahd, SSTAT2) & BUSFREETIME;
2389
2390         /*
2391          * Ignore external resets after a bus reset.
2392          */
2393         if (((status & SCSIRSTI) != 0) && (ahd->flags & AHD_BUS_RESET_ACTIVE)) {
2394                 ahd_outb(ahd, CLRSINT1, CLRSCSIRSTI);
2395                 return;
2396         }
2397
2398         /*
2399          * Clear bus reset flag
2400          */
2401         ahd->flags &= ~AHD_BUS_RESET_ACTIVE;
2402
2403         if ((status0 & (SELDI|SELDO)) != 0) {
2404                 u_int simode0;
2405
2406                 ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
2407                 simode0 = ahd_inb(ahd, SIMODE0);
2408                 status0 &= simode0 & (IOERR|OVERRUN|SELDI|SELDO);
2409                 ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
2410         }
2411         scbid = ahd_get_scbptr(ahd);
2412         scb = ahd_lookup_scb(ahd, scbid);
2413         if (scb != NULL
2414          && (ahd_inb(ahd, SEQ_FLAGS) & NOT_IDENTIFIED) != 0)
2415                 scb = NULL;
2416
2417         if ((status0 & IOERR) != 0) {
2418                 u_int now_lvd;
2419
2420                 now_lvd = ahd_inb(ahd, SBLKCTL) & ENAB40;
2421                 printf("%s: Transceiver State Has Changed to %s mode\n",
2422                        ahd_name(ahd), now_lvd ? "LVD" : "SE");
2423                 ahd_outb(ahd, CLRSINT0, CLRIOERR);
2424                 /*
2425                  * A change in I/O mode is equivalent to a bus reset.
2426                  */
2427                 ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
2428                 ahd_pause(ahd);
2429                 ahd_setup_iocell_workaround(ahd);
2430                 ahd_unpause(ahd);
2431         } else if ((status0 & OVERRUN) != 0) {
2432
2433                 printf("%s: SCSI offset overrun detected.  Resetting bus.\n",
2434                        ahd_name(ahd));
2435                 ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
2436         } else if ((status & SCSIRSTI) != 0) {
2437
2438                 printf("%s: Someone reset channel A\n", ahd_name(ahd));
2439                 ahd_reset_channel(ahd, 'A', /*Initiate Reset*/FALSE);
2440         } else if ((status & SCSIPERR) != 0) {
2441
2442                 /* Make sure the sequencer is in a safe location. */
2443                 ahd_clear_critical_section(ahd);
2444
2445                 ahd_handle_transmission_error(ahd);
2446         } else if (lqostat0 != 0) {
2447
2448                 printf("%s: lqostat0 == 0x%x!\n", ahd_name(ahd), lqostat0);
2449                 ahd_outb(ahd, CLRLQOINT0, lqostat0);
2450                 if ((ahd->bugs & AHD_CLRLQO_AUTOCLR_BUG) != 0)
2451                         ahd_outb(ahd, CLRLQOINT1, 0);
2452         } else if ((status & SELTO) != 0) {
2453                 u_int  scbid;
2454
2455                 /* Stop the selection */
2456                 ahd_outb(ahd, SCSISEQ0, 0);
2457
2458                 /* Make sure the sequencer is in a safe location. */
2459                 ahd_clear_critical_section(ahd);
2460
2461                 /* No more pending messages */
2462                 ahd_clear_msg_state(ahd);
2463
2464                 /* Clear interrupt state */
2465                 ahd_outb(ahd, CLRSINT1, CLRSELTIMEO|CLRBUSFREE|CLRSCSIPERR);
2466
2467                 /*
2468                  * Although the driver does not care about the
2469                  * 'Selection in Progress' status bit, the busy
2470                  * LED does.  SELINGO is only cleared by a sucessfull
2471                  * selection, so we must manually clear it to insure
2472                  * the LED turns off just incase no future successful
2473                  * selections occur (e.g. no devices on the bus).
2474                  */
2475                 ahd_outb(ahd, CLRSINT0, CLRSELINGO);
2476
2477                 scbid = ahd_inw(ahd, WAITING_TID_HEAD);
2478                 scb = ahd_lookup_scb(ahd, scbid);
2479                 if (scb == NULL) {
2480                         printf("%s: ahd_intr - referenced scb not "
2481                                "valid during SELTO scb(0x%x)\n",
2482                                ahd_name(ahd), scbid);
2483                         ahd_dump_card_state(ahd);
2484                 } else {
2485                         struct ahd_devinfo devinfo;
2486 #ifdef AHD_DEBUG
2487                         if ((ahd_debug & AHD_SHOW_SELTO) != 0) {
2488                                 ahd_print_path(ahd, scb);
2489                                 printf("Saw Selection Timeout for SCB 0x%x\n",
2490                                        scbid);
2491                         }
2492 #endif
2493                         ahd_scb_devinfo(ahd, &devinfo, scb);
2494                         ahd_set_transaction_status(scb, CAM_SEL_TIMEOUT);
2495                         ahd_freeze_devq(ahd, scb);
2496
2497                         /*
2498                          * Cancel any pending transactions on the device
2499                          * now that it seems to be missing.  This will
2500                          * also revert us to async/narrow transfers until
2501                          * we can renegotiate with the device.
2502                          */
2503                         ahd_handle_devreset(ahd, &devinfo,
2504                                             CAM_LUN_WILDCARD,
2505                                             CAM_SEL_TIMEOUT,
2506                                             "Selection Timeout",
2507                                             /*verbose_level*/1);
2508                 }
2509                 ahd_outb(ahd, CLRINT, CLRSCSIINT);
2510                 ahd_iocell_first_selection(ahd);
2511                 ahd_unpause(ahd);
2512         } else if ((status0 & (SELDI|SELDO)) != 0) {
2513
2514                 ahd_iocell_first_selection(ahd);
2515                 ahd_unpause(ahd);
2516         } else if (status3 != 0) {
2517                 printf("%s: SCSI Cell parity error SSTAT3 == 0x%x\n",
2518                        ahd_name(ahd), status3);
2519                 ahd_outb(ahd, CLRSINT3, status3);
2520         } else if ((lqistat1 & (LQIPHASE_LQ|LQIPHASE_NLQ)) != 0) {
2521
2522                 /* Make sure the sequencer is in a safe location. */
2523                 ahd_clear_critical_section(ahd);
2524
2525                 ahd_handle_lqiphase_error(ahd, lqistat1);
2526         } else if ((lqistat1 & LQICRCI_NLQ) != 0) {
2527                 /*
2528                  * This status can be delayed during some
2529                  * streaming operations.  The SCSIPHASE
2530                  * handler has already dealt with this case
2531                  * so just clear the error.
2532                  */
2533                 ahd_outb(ahd, CLRLQIINT1, CLRLQICRCI_NLQ);
2534         } else if ((status & BUSFREE) != 0
2535                 || (lqistat1 & LQOBUSFREE) != 0) {
2536                 u_int lqostat1;
2537                 int   restart;
2538                 int   clear_fifo;
2539                 int   packetized;
2540                 u_int mode;
2541
2542                 /*
2543                  * Clear our selection hardware as soon as possible.
2544                  * We may have an entry in the waiting Q for this target,
2545                  * that is affected by this busfree and we don't want to
2546                  * go about selecting the target while we handle the event.
2547                  */
2548                 ahd_outb(ahd, SCSISEQ0, 0);
2549
2550                 /* Make sure the sequencer is in a safe location. */
2551                 ahd_clear_critical_section(ahd);
2552
2553                 /*
2554                  * Determine what we were up to at the time of
2555                  * the busfree.
2556                  */
2557                 mode = AHD_MODE_SCSI;
2558                 busfreetime = ahd_inb(ahd, SSTAT2) & BUSFREETIME;
2559                 lqostat1 = ahd_inb(ahd, LQOSTAT1);
2560                 switch (busfreetime) {
2561                 case BUSFREE_DFF0:
2562                 case BUSFREE_DFF1:
2563                 {
2564                         u_int   scbid;
2565                         struct  scb *scb;
2566
2567                         mode = busfreetime == BUSFREE_DFF0
2568                              ? AHD_MODE_DFF0 : AHD_MODE_DFF1;
2569                         ahd_set_modes(ahd, mode, mode);
2570                         scbid = ahd_get_scbptr(ahd);
2571                         scb = ahd_lookup_scb(ahd, scbid);
2572                         if (scb == NULL) {
2573                                 printf("%s: Invalid SCB %d in DFF%d "
2574                                        "during unexpected busfree\n",
2575                                        ahd_name(ahd), scbid, mode);
2576                                 packetized = 0;
2577                         } else
2578                                 packetized = (scb->flags & SCB_PACKETIZED) != 0;
2579                         clear_fifo = 1;
2580                         break;
2581                 }
2582                 case BUSFREE_LQO:
2583                         clear_fifo = 0;
2584                         packetized = 1;
2585                         break;
2586                 default:
2587                         clear_fifo = 0;
2588                         packetized =  (lqostat1 & LQOBUSFREE) != 0;
2589                         if (!packetized
2590                          && ahd_inb(ahd, LASTPHASE) == P_BUSFREE
2591                          && (ahd_inb(ahd, SSTAT0) & SELDI) == 0
2592                          && ((ahd_inb(ahd, SSTAT0) & SELDO) == 0
2593                           || (ahd_inb(ahd, SCSISEQ0) & ENSELO) == 0))
2594                                 /*
2595                                  * Assume packetized if we are not
2596                                  * on the bus in a non-packetized
2597                                  * capacity and any pending selection
2598                                  * was a packetized selection.
2599                                  */
2600                                 packetized = 1;
2601                         break;
2602                 }
2603
2604 #ifdef AHD_DEBUG
2605                 if ((ahd_debug & AHD_SHOW_MISC) != 0)
2606                         printf("Saw Busfree.  Busfreetime = 0x%x.\n",
2607                                busfreetime);
2608 #endif
2609                 /*
2610                  * Busfrees that occur in non-packetized phases are
2611                  * handled by the nonpkt_busfree handler.
2612                  */
2613                 if (packetized && ahd_inb(ahd, LASTPHASE) == P_BUSFREE) {
2614                         restart = ahd_handle_pkt_busfree(ahd, busfreetime);
2615                 } else {
2616                         packetized = 0;
2617                         restart = ahd_handle_nonpkt_busfree(ahd);
2618                 }
2619                 /*
2620                  * Clear the busfree interrupt status.  The setting of
2621                  * the interrupt is a pulse, so in a perfect world, we
2622                  * would not need to muck with the ENBUSFREE logic.  This
2623                  * would ensure that if the bus moves on to another
2624                  * connection, busfree protection is still in force.  If
2625                  * BUSFREEREV is broken, however, we must manually clear
2626                  * the ENBUSFREE if the busfree occurred during a non-pack
2627                  * connection so that we don't get false positives during
2628                  * future, packetized, connections.
2629                  */
2630                 ahd_outb(ahd, CLRSINT1, CLRBUSFREE);
2631                 if (packetized == 0
2632                  && (ahd->bugs & AHD_BUSFREEREV_BUG) != 0)
2633                         ahd_outb(ahd, SIMODE1,
2634                                  ahd_inb(ahd, SIMODE1) & ~ENBUSFREE);
2635
2636                 if (clear_fifo)
2637                         ahd_clear_fifo(ahd, mode);
2638
2639                 ahd_clear_msg_state(ahd);
2640                 ahd_outb(ahd, CLRINT, CLRSCSIINT);
2641                 if (restart) {
2642                         ahd_restart(ahd);
2643                 } else {
2644                         ahd_unpause(ahd);
2645                 }
2646         } else {
2647                 printf("%s: Missing case in ahd_handle_scsiint. status = %x\n",
2648                        ahd_name(ahd), status);
2649                 ahd_dump_card_state(ahd);
2650                 ahd_clear_intstat(ahd);
2651                 ahd_unpause(ahd);
2652         }
2653 }
2654
2655 static void
2656 ahd_handle_transmission_error(struct ahd_softc *ahd)
2657 {
2658         struct  scb *scb;
2659         u_int   scbid;
2660         u_int   lqistat1;
2661         u_int   lqistat2;
2662         u_int   msg_out;
2663         u_int   curphase;
2664         u_int   lastphase;
2665         u_int   perrdiag;
2666         u_int   cur_col;
2667         int     silent;
2668
2669         scb = NULL;
2670         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
2671         lqistat1 = ahd_inb(ahd, LQISTAT1) & ~(LQIPHASE_LQ|LQIPHASE_NLQ);
2672         lqistat2 = ahd_inb(ahd, LQISTAT2);
2673         if ((lqistat1 & (LQICRCI_NLQ|LQICRCI_LQ)) == 0
2674          && (ahd->bugs & AHD_NLQICRC_DELAYED_BUG) != 0) {
2675                 u_int lqistate;
2676
2677                 ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
2678                 lqistate = ahd_inb(ahd, LQISTATE);
2679                 if ((lqistate >= 0x1E && lqistate <= 0x24)
2680                  || (lqistate == 0x29)) {
2681 #ifdef AHD_DEBUG
2682                         if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) {
2683                                 printf("%s: NLQCRC found via LQISTATE\n",
2684                                        ahd_name(ahd));
2685                         }
2686 #endif
2687                         lqistat1 |= LQICRCI_NLQ;
2688                 }
2689                 ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
2690         }
2691
2692         ahd_outb(ahd, CLRLQIINT1, lqistat1);
2693         lastphase = ahd_inb(ahd, LASTPHASE);
2694         curphase = ahd_inb(ahd, SCSISIGI) & PHASE_MASK;
2695         perrdiag = ahd_inb(ahd, PERRDIAG);
2696         msg_out = MSG_INITIATOR_DET_ERR;
2697         ahd_outb(ahd, CLRSINT1, CLRSCSIPERR);
2698         
2699         /*
2700          * Try to find the SCB associated with this error.
2701          */
2702         silent = FALSE;
2703         if (lqistat1 == 0
2704          || (lqistat1 & LQICRCI_NLQ) != 0) {
2705                 if ((lqistat1 & (LQICRCI_NLQ|LQIOVERI_NLQ)) != 0)
2706                         ahd_set_active_fifo(ahd);
2707                 scbid = ahd_get_scbptr(ahd);
2708                 scb = ahd_lookup_scb(ahd, scbid);
2709                 if (scb != NULL && SCB_IS_SILENT(scb))
2710                         silent = TRUE;
2711         }
2712
2713         cur_col = 0;
2714         if (silent == FALSE) {
2715                 printf("%s: Transmission error detected\n", ahd_name(ahd));
2716                 ahd_lqistat1_print(lqistat1, &cur_col, 50);
2717                 ahd_lastphase_print(lastphase, &cur_col, 50);
2718                 ahd_scsisigi_print(curphase, &cur_col, 50);
2719                 ahd_perrdiag_print(perrdiag, &cur_col, 50);
2720                 printf("\n");
2721                 ahd_dump_card_state(ahd);
2722         }
2723
2724         if ((lqistat1 & (LQIOVERI_LQ|LQIOVERI_NLQ)) != 0) {
2725                 if (silent == FALSE) {
2726                         printf("%s: Gross protocol error during incoming "
2727                                "packet.  lqistat1 == 0x%x.  Resetting bus.\n",
2728                                ahd_name(ahd), lqistat1);
2729                 }
2730                 ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
2731                 return;
2732         } else if ((lqistat1 & LQICRCI_LQ) != 0) {
2733                 /*
2734                  * A CRC error has been detected on an incoming LQ.
2735                  * The bus is currently hung on the last ACK.
2736                  * Hit LQIRETRY to release the last ack, and
2737                  * wait for the sequencer to determine that ATNO
2738                  * is asserted while in message out to take us
2739                  * to our host message loop.  No NONPACKREQ or
2740                  * LQIPHASE type errors will occur in this
2741                  * scenario.  After this first LQIRETRY, the LQI
2742                  * manager will be in ISELO where it will
2743                  * happily sit until another packet phase begins.
2744                  * Unexpected bus free detection is enabled
2745                  * through any phases that occur after we release
2746                  * this last ack until the LQI manager sees a
2747                  * packet phase.  This implies we may have to
2748                  * ignore a perfectly valid "unexected busfree"
2749                  * after our "initiator detected error" message is
2750                  * sent.  A busfree is the expected response after
2751                  * we tell the target that it's L_Q was corrupted.
2752                  * (SPI4R09 10.7.3.3.3)
2753                  */
2754                 ahd_outb(ahd, LQCTL2, LQIRETRY);
2755                 printf("LQIRetry for LQICRCI_LQ to release ACK\n");
2756         } else if ((lqistat1 & LQICRCI_NLQ) != 0) {
2757                 /*
2758                  * We detected a CRC error in a NON-LQ packet.
2759                  * The hardware has varying behavior in this situation
2760                  * depending on whether this packet was part of a
2761                  * stream or not.
2762                  *
2763                  * PKT by PKT mode:
2764                  * The hardware has already acked the complete packet.
2765                  * If the target honors our outstanding ATN condition,
2766                  * we should be (or soon will be) in MSGOUT phase.
2767                  * This will trigger the LQIPHASE_LQ status bit as the
2768                  * hardware was expecting another LQ.  Unexpected
2769                  * busfree detection is enabled.  Once LQIPHASE_LQ is
2770                  * true (first entry into host message loop is much
2771                  * the same), we must clear LQIPHASE_LQ and hit
2772                  * LQIRETRY so the hardware is ready to handle
2773                  * a future LQ.  NONPACKREQ will not be asserted again
2774                  * once we hit LQIRETRY until another packet is
2775                  * processed.  The target may either go busfree
2776                  * or start another packet in response to our message.
2777                  *
2778                  * Read Streaming P0 asserted:
2779                  * If we raise ATN and the target completes the entire
2780                  * stream (P0 asserted during the last packet), the
2781                  * hardware will ack all data and return to the ISTART
2782                  * state.  When the target reponds to our ATN condition,
2783                  * LQIPHASE_LQ will be asserted.  We should respond to
2784                  * this with an LQIRETRY to prepare for any future
2785                  * packets.  NONPACKREQ will not be asserted again
2786                  * once we hit LQIRETRY until another packet is
2787                  * processed.  The target may either go busfree or
2788                  * start another packet in response to our message.
2789                  * Busfree detection is enabled.
2790                  *
2791                  * Read Streaming P0 not asserted:
2792                  * If we raise ATN and the target transitions to
2793                  * MSGOUT in or after a packet where P0 is not
2794                  * asserted, the hardware will assert LQIPHASE_NLQ.
2795                  * We should respond to the LQIPHASE_NLQ with an
2796                  * LQIRETRY.  Should the target stay in a non-pkt
2797                  * phase after we send our message, the hardware
2798                  * will assert LQIPHASE_LQ.  Recovery is then just as
2799                  * listed above for the read streaming with P0 asserted.
2800                  * Busfree detection is enabled.
2801                  */
2802                 if (silent == FALSE)
2803                         printf("LQICRC_NLQ\n");
2804                 if (scb == NULL) {
2805                         printf("%s: No SCB valid for LQICRC_NLQ.  "
2806                                "Resetting bus\n", ahd_name(ahd));
2807                         ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
2808                         return;
2809                 }
2810         } else if ((lqistat1 & LQIBADLQI) != 0) {
2811                 printf("Need to handle BADLQI!\n");
2812                 ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
2813                 return;
2814         } else if ((perrdiag & (PARITYERR|PREVPHASE)) == PARITYERR) {
2815                 if ((curphase & ~P_DATAIN_DT) != 0) {
2816                         /* Ack the byte.  So we can continue. */
2817                         if (silent == FALSE)
2818                                 printf("Acking %s to clear perror\n",
2819                                     ahd_lookup_phase_entry(curphase)->phasemsg);
2820                         ahd_inb(ahd, SCSIDAT);
2821                 }
2822         
2823                 if (curphase == P_MESGIN)
2824                         msg_out = MSG_PARITY_ERROR;
2825         }
2826
2827         /*
2828          * We've set the hardware to assert ATN if we 
2829          * get a parity error on "in" phases, so all we
2830          * need to do is stuff the message buffer with
2831          * the appropriate message.  "In" phases have set
2832          * mesg_out to something other than MSG_NOP.
2833          */
2834         ahd->send_msg_perror = msg_out;
2835         if (scb != NULL && msg_out == MSG_INITIATOR_DET_ERR)
2836                 scb->flags |= SCB_TRANSMISSION_ERROR;
2837         ahd_outb(ahd, MSG_OUT, HOST_MSG);
2838         ahd_outb(ahd, CLRINT, CLRSCSIINT);
2839         ahd_unpause(ahd);
2840 }
2841
2842 static void
2843 ahd_handle_lqiphase_error(struct ahd_softc *ahd, u_int lqistat1)
2844 {
2845         /*
2846          * Clear the sources of the interrupts.
2847          */
2848         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
2849         ahd_outb(ahd, CLRLQIINT1, lqistat1);
2850
2851         /*
2852          * If the "illegal" phase changes were in response
2853          * to our ATN to flag a CRC error, AND we ended up
2854          * on packet boundaries, clear the error, restart the
2855          * LQI manager as appropriate, and go on our merry
2856          * way toward sending the message.  Otherwise, reset
2857          * the bus to clear the error.
2858          */
2859         ahd_set_active_fifo(ahd);
2860         if ((ahd_inb(ahd, SCSISIGO) & ATNO) != 0
2861          && (ahd_inb(ahd, MDFFSTAT) & DLZERO) != 0) {
2862                 if ((lqistat1 & LQIPHASE_LQ) != 0) {
2863                         printf("LQIRETRY for LQIPHASE_LQ\n");
2864                         ahd_outb(ahd, LQCTL2, LQIRETRY);
2865                 } else if ((lqistat1 & LQIPHASE_NLQ) != 0) {
2866                         printf("LQIRETRY for LQIPHASE_NLQ\n");
2867                         ahd_outb(ahd, LQCTL2, LQIRETRY);
2868                 } else
2869                         panic("ahd_handle_lqiphase_error: No phase errors\n");
2870                 ahd_dump_card_state(ahd);
2871                 ahd_outb(ahd, CLRINT, CLRSCSIINT);
2872                 ahd_unpause(ahd);
2873         } else {
2874                 printf("Reseting Channel for LQI Phase error\n");
2875                 ahd_dump_card_state(ahd);
2876                 ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
2877         }
2878 }
2879
2880 /*
2881  * Packetized unexpected or expected busfree.
2882  * Entered in mode based on busfreetime.
2883  */
2884 static int
2885 ahd_handle_pkt_busfree(struct ahd_softc *ahd, u_int busfreetime)
2886 {
2887         u_int lqostat1;
2888
2889         AHD_ASSERT_MODES(ahd, ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK),
2890                          ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK));
2891         lqostat1 = ahd_inb(ahd, LQOSTAT1);
2892         if ((lqostat1 & LQOBUSFREE) != 0) {
2893                 struct scb *scb;
2894                 u_int scbid;
2895                 u_int saved_scbptr;
2896                 u_int waiting_h;
2897                 u_int waiting_t;
2898                 u_int next;
2899
2900                 /*
2901                  * The LQO manager detected an unexpected busfree
2902                  * either:
2903                  *
2904                  * 1) During an outgoing LQ.
2905                  * 2) After an outgoing LQ but before the first
2906                  *    REQ of the command packet.
2907                  * 3) During an outgoing command packet.
2908                  *
2909                  * In all cases, CURRSCB is pointing to the
2910                  * SCB that encountered the failure.  Clean
2911                  * up the queue, clear SELDO and LQOBUSFREE,
2912                  * and allow the sequencer to restart the select
2913                  * out at its lesure.
2914                  */
2915                 ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
2916                 scbid = ahd_inw(ahd, CURRSCB);
2917                 scb = ahd_lookup_scb(ahd, scbid);
2918                 if (scb == NULL)
2919                        panic("SCB not valid during LQOBUSFREE");
2920                 /*
2921                  * Clear the status.
2922                  */
2923                 ahd_outb(ahd, CLRLQOINT1, CLRLQOBUSFREE);
2924                 if ((ahd->bugs & AHD_CLRLQO_AUTOCLR_BUG) != 0)
2925                         ahd_outb(ahd, CLRLQOINT1, 0);
2926                 ahd_outb(ahd, SCSISEQ0, ahd_inb(ahd, SCSISEQ0) & ~ENSELO);
2927                 ahd_flush_device_writes(ahd);
2928                 ahd_outb(ahd, CLRSINT0, CLRSELDO);
2929
2930                 /*
2931                  * Return the LQO manager to its idle loop.  It will
2932                  * not do this automatically if the busfree occurs
2933                  * after the first REQ of either the LQ or command
2934                  * packet or between the LQ and command packet.
2935                  */
2936                 ahd_outb(ahd, LQCTL2, ahd_inb(ahd, LQCTL2) | LQOTOIDLE);
2937
2938                 /*
2939                  * Update the waiting for selection queue so
2940                  * we restart on the correct SCB.
2941                  */
2942                 waiting_h = ahd_inw(ahd, WAITING_TID_HEAD);
2943                 saved_scbptr = ahd_get_scbptr(ahd);
2944                 if (waiting_h != scbid) {
2945
2946                         ahd_outw(ahd, WAITING_TID_HEAD, scbid);
2947                         waiting_t = ahd_inw(ahd, WAITING_TID_TAIL);
2948                         if (waiting_t == waiting_h) {
2949                                 ahd_outw(ahd, WAITING_TID_TAIL, scbid);
2950                                 next = SCB_LIST_NULL;
2951                         } else {
2952                                 ahd_set_scbptr(ahd, waiting_h);
2953                                 next = ahd_inw_scbram(ahd, SCB_NEXT2);
2954                         }
2955                         ahd_set_scbptr(ahd, scbid);
2956                         ahd_outw(ahd, SCB_NEXT2, next);
2957                 }
2958                 ahd_set_scbptr(ahd, saved_scbptr);
2959                 if (scb->crc_retry_count < AHD_MAX_LQ_CRC_ERRORS) {
2960                         if (SCB_IS_SILENT(scb) == FALSE) {
2961                                 ahd_print_path(ahd, scb);
2962                                 printf("Probable outgoing LQ CRC error.  "
2963                                        "Retrying command\n");
2964                         }
2965                         scb->crc_retry_count++;
2966                 } else {
2967                         ahd_set_transaction_status(scb, CAM_UNCOR_PARITY);
2968                         ahd_freeze_scb(scb);
2969                         ahd_freeze_devq(ahd, scb);
2970                 }
2971                 /* Return unpausing the sequencer. */
2972                 return (0);
2973         } else if ((ahd_inb(ahd, PERRDIAG) & PARITYERR) != 0) {
2974                 /*
2975                  * Ignore what are really parity errors that
2976                  * occur on the last REQ of a free running
2977                  * clock prior to going busfree.  Some drives
2978                  * do not properly active negate just before
2979                  * going busfree resulting in a parity glitch.
2980                  */
2981                 ahd_outb(ahd, CLRSINT1, CLRSCSIPERR|CLRBUSFREE);
2982 #ifdef AHD_DEBUG
2983                 if ((ahd_debug & AHD_SHOW_MASKED_ERRORS) != 0)
2984                         printf("%s: Parity on last REQ detected "
2985                                "during busfree phase.\n",
2986                                ahd_name(ahd));
2987 #endif
2988                 /* Return unpausing the sequencer. */
2989                 return (0);
2990         }
2991         if (ahd->src_mode != AHD_MODE_SCSI) {
2992                 u_int   scbid;
2993                 struct  scb *scb;
2994
2995                 scbid = ahd_get_scbptr(ahd);
2996                 scb = ahd_lookup_scb(ahd, scbid);
2997                 ahd_print_path(ahd, scb);
2998                 printf("Unexpected PKT busfree condition\n");
2999                 ahd_dump_card_state(ahd);
3000                 ahd_abort_scbs(ahd, SCB_GET_TARGET(ahd, scb), 'A',
3001                                SCB_GET_LUN(scb), SCB_GET_TAG(scb),
3002                                ROLE_INITIATOR, CAM_UNEXP_BUSFREE);
3003
3004                 /* Return restarting the sequencer. */
3005                 return (1);
3006         }
3007         printf("%s: Unexpected PKT busfree condition\n", ahd_name(ahd));
3008         ahd_dump_card_state(ahd);
3009         /* Restart the sequencer. */
3010         return (1);
3011 }
3012
3013 /*
3014  * Non-packetized unexpected or expected busfree.
3015  */
3016 static int
3017 ahd_handle_nonpkt_busfree(struct ahd_softc *ahd)
3018 {
3019         struct  ahd_devinfo devinfo;
3020         struct  scb *scb;
3021         u_int   lastphase;
3022         u_int   saved_scsiid;
3023         u_int   saved_lun;
3024         u_int   target;
3025         u_int   initiator_role_id;
3026         u_int   scbid;
3027         u_int   ppr_busfree;
3028         int     printerror;
3029
3030         /*
3031          * Look at what phase we were last in.  If its message out,
3032          * chances are pretty good that the busfree was in response
3033          * to one of our abort requests.
3034          */
3035         lastphase = ahd_inb(ahd, LASTPHASE);
3036         saved_scsiid = ahd_inb(ahd, SAVED_SCSIID);
3037         saved_lun = ahd_inb(ahd, SAVED_LUN);
3038         target = SCSIID_TARGET(ahd, saved_scsiid);
3039         initiator_role_id = SCSIID_OUR_ID(saved_scsiid);
3040         ahd_compile_devinfo(&devinfo, initiator_role_id,
3041                             target, saved_lun, 'A', ROLE_INITIATOR);
3042         printerror = 1;
3043
3044         scbid = ahd_get_scbptr(ahd);
3045         scb = ahd_lookup_scb(ahd, scbid);
3046         if (scb != NULL
3047          && (ahd_inb(ahd, SEQ_FLAGS) & NOT_IDENTIFIED) != 0)
3048                 scb = NULL;
3049
3050         ppr_busfree = (ahd->msg_flags & MSG_FLAG_EXPECT_PPR_BUSFREE) != 0;
3051         if (lastphase == P_MESGOUT) {
3052                 u_int tag;
3053
3054                 tag = SCB_LIST_NULL;
3055                 if (ahd_sent_msg(ahd, AHDMSG_1B, MSG_ABORT_TAG, TRUE)
3056                  || ahd_sent_msg(ahd, AHDMSG_1B, MSG_ABORT, TRUE)) {
3057                         int found;
3058                         int sent_msg;
3059
3060                         if (scb == NULL) {
3061                                 ahd_print_devinfo(ahd, &devinfo);
3062                                 printf("Abort for unidentified "
3063                                        "connection completed.\n");
3064                                 /* restart the sequencer. */
3065                                 return (1);
3066                         }
3067                         sent_msg = ahd->msgout_buf[ahd->msgout_index - 1];
3068                         ahd_print_path(ahd, scb);
3069                         printf("SCB %d - Abort%s Completed.\n",
3070                                SCB_GET_TAG(scb),
3071                                sent_msg == MSG_ABORT_TAG ? "" : " Tag");
3072
3073                         if (sent_msg == MSG_ABORT_TAG)
3074                                 tag = SCB_GET_TAG(scb);
3075
3076                         if ((scb->flags & SCB_EXTERNAL_RESET) != 0) {
3077                                 /*
3078                                  * This abort is in response to an
3079                                  * unexpected switch to command phase
3080                                  * for a packetized connection.  Since
3081                                  * the identify message was never sent,
3082                                  * "saved lun" is 0.  We really want to
3083                                  * abort only the SCB that encountered
3084                                  * this error, which could have a different
3085                                  * lun.  The SCB will be retried so the OS
3086                                  * will see the UA after renegotiating to
3087                                  * packetized.
3088                                  */
3089                                 tag = SCB_GET_TAG(scb);
3090                                 saved_lun = scb->hscb->lun;
3091                         }
3092                         found = ahd_abort_scbs(ahd, target, 'A', saved_lun,
3093                                                tag, ROLE_INITIATOR,
3094                                                CAM_REQ_ABORTED);
3095                         printf("found == 0x%x\n", found);
3096                         printerror = 0;
3097                 } else if (ahd_sent_msg(ahd, AHDMSG_1B,
3098                                         MSG_BUS_DEV_RESET, TRUE)) {
3099 #ifdef __FreeBSD__
3100                         /*
3101                          * Don't mark the user's request for this BDR
3102                          * as completing with CAM_BDR_SENT.  CAM3
3103                          * specifies CAM_REQ_CMP.
3104                          */
3105                         if (scb != NULL
3106                          && scb->io_ctx->ccb_h.func_code== XPT_RESET_DEV
3107                          && ahd_match_scb(ahd, scb, target, 'A',
3108                                           CAM_LUN_WILDCARD, SCB_LIST_NULL,
3109                                           ROLE_INITIATOR))
3110                                 ahd_set_transaction_status(scb, CAM_REQ_CMP);
3111 #endif
3112                         ahd_handle_devreset(ahd, &devinfo, CAM_LUN_WILDCARD,
3113                                             CAM_BDR_SENT, "Bus Device Reset",
3114                                             /*verbose_level*/0);
3115                         printerror = 0;
3116                 } else if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_PPR, FALSE)
3117                         && ppr_busfree == 0) {
3118                         struct ahd_initiator_tinfo *tinfo;
3119                         struct ahd_tmode_tstate *tstate;
3120
3121                         /*
3122                          * PPR Rejected.
3123                          *
3124                          * If the previous negotiation was packetized,
3125                          * this could be because the device has been
3126                          * reset without our knowledge.  Force our
3127                          * current negotiation to async and retry the
3128                          * negotiation.  Otherwise retry the command
3129                          * with non-ppr negotiation.
3130                          */
3131 #ifdef AHD_DEBUG
3132                         if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
3133                                 printf("PPR negotiation rejected busfree.\n");
3134 #endif
3135                         tinfo = ahd_fetch_transinfo(ahd, devinfo.channel,
3136                                                     devinfo.our_scsiid,
3137                                                     devinfo.target, &tstate);
3138                         if ((tinfo->curr.ppr_options & MSG_EXT_PPR_IU_REQ)!=0) {
3139                                 ahd_set_width(ahd, &devinfo,
3140                                               MSG_EXT_WDTR_BUS_8_BIT,
3141                                               AHD_TRANS_CUR,
3142                                               /*paused*/TRUE);
3143                                 ahd_set_syncrate(ahd, &devinfo,
3144                                                 /*period*/0, /*offset*/0,
3145                                                 /*ppr_options*/0,
3146                                                 AHD_TRANS_CUR,
3147                                                 /*paused*/TRUE);
3148                                 /*
3149                                  * The expect PPR busfree handler below
3150                                  * will effect the retry and necessary
3151                                  * abort.
3152                                  */
3153                         } else {
3154                                 tinfo->curr.transport_version = 2;
3155                                 tinfo->goal.transport_version = 2;
3156                                 tinfo->goal.ppr_options = 0;
3157                                 /*
3158                                  * Remove any SCBs in the waiting for selection
3159                                  * queue that may also be for this target so
3160                                  * that command ordering is preserved.
3161                                  */
3162                                 ahd_freeze_devq(ahd, scb);
3163                                 ahd_qinfifo_requeue_tail(ahd, scb);
3164                                 printerror = 0;
3165                         }
3166                 } else if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_WDTR, FALSE)
3167                         && ppr_busfree == 0) {
3168                         /*
3169                          * Negotiation Rejected.  Go-narrow and
3170                          * retry command.
3171                          */
3172 #ifdef AHD_DEBUG
3173                         if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
3174                                 printf("WDTR negotiation rejected busfree.\n");
3175 #endif
3176                         ahd_set_width(ahd, &devinfo,
3177                                       MSG_EXT_WDTR_BUS_8_BIT,
3178                                       AHD_TRANS_CUR|AHD_TRANS_GOAL,
3179                                       /*paused*/TRUE);
3180                         /*
3181                          * Remove any SCBs in the waiting for selection
3182                          * queue that may also be for this target so that
3183                          * command ordering is preserved.
3184                          */
3185                         ahd_freeze_devq(ahd, scb);
3186                         ahd_qinfifo_requeue_tail(ahd, scb);
3187                         printerror = 0;
3188                 } else if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_SDTR, FALSE)
3189                         && ppr_busfree == 0) {
3190                         /*
3191                          * Negotiation Rejected.  Go-async and
3192                          * retry command.
3193                          */
3194 #ifdef AHD_DEBUG
3195                         if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
3196                                 printf("SDTR negotiation rejected busfree.\n");
3197 #endif
3198                         ahd_set_syncrate(ahd, &devinfo,
3199                                         /*period*/0, /*offset*/0,
3200                                         /*ppr_options*/0,
3201                                         AHD_TRANS_CUR|AHD_TRANS_GOAL,
3202                                         /*paused*/TRUE);
3203                         /*
3204                          * Remove any SCBs in the waiting for selection
3205                          * queue that may also be for this target so that
3206                          * command ordering is preserved.
3207                          */
3208                         ahd_freeze_devq(ahd, scb);
3209                         ahd_qinfifo_requeue_tail(ahd, scb);
3210                         printerror = 0;
3211                 } else if ((ahd->msg_flags & MSG_FLAG_EXPECT_IDE_BUSFREE) != 0
3212                         && ahd_sent_msg(ahd, AHDMSG_1B,
3213                                          MSG_INITIATOR_DET_ERR, TRUE)) {
3214
3215 #ifdef AHD_DEBUG
3216                         if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
3217                                 printf("Expected IDE Busfree\n");
3218 #endif
3219                         printerror = 0;
3220                 } else if ((ahd->msg_flags & MSG_FLAG_EXPECT_QASREJ_BUSFREE)
3221                         && ahd_sent_msg(ahd, AHDMSG_1B,
3222                                         MSG_MESSAGE_REJECT, TRUE)) {
3223
3224 #ifdef AHD_DEBUG
3225                         if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
3226                                 printf("Expected QAS Reject Busfree\n");
3227 #endif
3228                         printerror = 0;
3229                 }
3230         }
3231
3232         /*
3233          * The busfree required flag is honored at the end of
3234          * the message phases.  We check it last in case we
3235          * had to send some other message that caused a busfree.
3236          */
3237         if (printerror != 0
3238          && (lastphase == P_MESGIN || lastphase == P_MESGOUT)
3239          && ((ahd->msg_flags & MSG_FLAG_EXPECT_PPR_BUSFREE) != 0)) {
3240
3241                 ahd_freeze_devq(ahd, scb);
3242                 ahd_set_transaction_status(scb, CAM_REQUEUE_REQ);
3243                 ahd_freeze_scb(scb);
3244                 if ((ahd->msg_flags & MSG_FLAG_IU_REQ_CHANGED) != 0) {
3245                         ahd_abort_scbs(ahd, SCB_GET_TARGET(ahd, scb),
3246                                        SCB_GET_CHANNEL(ahd, scb),
3247                                        SCB_GET_LUN(scb), SCB_LIST_NULL,
3248                                        ROLE_INITIATOR, CAM_REQ_ABORTED);
3249                 } else {
3250 #ifdef AHD_DEBUG
3251                         if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
3252                                 printf("PPR Negotiation Busfree.\n");
3253 #endif
3254                         ahd_done(ahd, scb);
3255                 }
3256                 printerror = 0;
3257         }
3258         if (printerror != 0) {
3259                 int aborted;
3260
3261                 aborted = 0;
3262                 if (scb != NULL) {
3263                         u_int tag;
3264
3265                         if ((scb->hscb->control & TAG_ENB) != 0)
3266                                 tag = SCB_GET_TAG(scb);
3267                         else
3268                                 tag = SCB_LIST_NULL;
3269                         ahd_print_path(ahd, scb);
3270                         aborted = ahd_abort_scbs(ahd, target, 'A',
3271                                        SCB_GET_LUN(scb), tag,
3272                                        ROLE_INITIATOR,
3273                                        CAM_UNEXP_BUSFREE);
3274                 } else {
3275                         /*
3276                          * We had not fully identified this connection,
3277                          * so we cannot abort anything.
3278                          */
3279                         printf("%s: ", ahd_name(ahd));
3280                 }
3281                 printf("Unexpected busfree %s, %d SCBs aborted, "
3282                        "PRGMCNT == 0x%x\n",
3283                        ahd_lookup_phase_entry(lastphase)->phasemsg,
3284                        aborted,
3285                        ahd_inw(ahd, PRGMCNT));
3286                 ahd_dump_card_state(ahd);
3287                 if (lastphase != P_BUSFREE)
3288                         ahd_force_renegotiation(ahd, &devinfo);
3289         }
3290         /* Always restart the sequencer. */
3291         return (1);
3292 }
3293
3294 static void
3295 ahd_handle_proto_violation(struct ahd_softc *ahd)
3296 {
3297         struct  ahd_devinfo devinfo;
3298         struct  scb *scb;
3299         u_int   scbid;
3300         u_int   seq_flags;
3301         u_int   curphase;
3302         u_int   lastphase;
3303         int     found;
3304
3305         ahd_fetch_devinfo(ahd, &devinfo);
3306         scbid = ahd_get_scbptr(ahd);
3307         scb = ahd_lookup_scb(ahd, scbid);
3308         seq_flags = ahd_inb(ahd, SEQ_FLAGS);
3309         curphase = ahd_inb(ahd, SCSISIGI) & PHASE_MASK;
3310         lastphase = ahd_inb(ahd, LASTPHASE);
3311         if ((seq_flags & NOT_IDENTIFIED) != 0) {
3312
3313                 /*
3314                  * The reconnecting target either did not send an
3315                  * identify message, or did, but we didn't find an SCB
3316                  * to match.
3317                  */
3318                 ahd_print_devinfo(ahd, &devinfo);
3319                 printf("Target did not send an IDENTIFY message. "
3320                        "LASTPHASE = 0x%x.\n", lastphase);
3321                 scb = NULL;
3322         } else if (scb == NULL) {
3323                 /*
3324                  * We don't seem to have an SCB active for this
3325                  * transaction.  Print an error and reset the bus.
3326                  */
3327                 ahd_print_devinfo(ahd, &devinfo);
3328                 printf("No SCB found during protocol violation\n");
3329                 goto proto_violation_reset;
3330         } else {
3331                 ahd_set_transaction_status(scb, CAM_SEQUENCE_FAIL);
3332                 if ((seq_flags & NO_CDB_SENT) != 0) {
3333                         ahd_print_path(ahd, scb);
3334                         printf("No or incomplete CDB sent to device.\n");
3335                 } else if ((ahd_inb_scbram(ahd, SCB_CONTROL)
3336                           & STATUS_RCVD) == 0) {
3337                         /*
3338                          * The target never bothered to provide status to
3339                          * us prior to completing the command.  Since we don't
3340                          * know the disposition of this command, we must attempt
3341                          * to abort it.  Assert ATN and prepare to send an abort
3342                          * message.
3343                          */
3344                         ahd_print_path(ahd, scb);
3345                         printf("Completed command without status.\n");
3346                 } else {
3347                         ahd_print_path(ahd, scb);
3348                         printf("Unknown protocol violation.\n");
3349                         ahd_dump_card_state(ahd);
3350                 }
3351         }
3352         if ((lastphase & ~P_DATAIN_DT) == 0
3353          || lastphase == P_COMMAND) {
3354 proto_violation_reset:
3355                 /*
3356                  * Target either went directly to data
3357                  * phase or didn't respond to our ATN.
3358                  * The only safe thing to do is to blow
3359                  * it away with a bus reset.
3360                  */
3361                 found = ahd_reset_channel(ahd, 'A', TRUE);
3362                 printf("%s: Issued Channel %c Bus Reset. "
3363                        "%d SCBs aborted\n", ahd_name(ahd), 'A', found);
3364         } else {
3365                 /*
3366                  * Leave the selection hardware off in case
3367                  * this abort attempt will affect yet to
3368                  * be sent commands.
3369                  */
3370                 ahd_outb(ahd, SCSISEQ0,
3371                          ahd_inb(ahd, SCSISEQ0) & ~ENSELO);
3372                 ahd_assert_atn(ahd);
3373                 ahd_outb(ahd, MSG_OUT, HOST_MSG);
3374                 if (scb == NULL) {
3375                         ahd_print_devinfo(ahd, &devinfo);
3376                         ahd->msgout_buf[0] = MSG_ABORT_TASK;
3377                         ahd->msgout_len = 1;
3378                         ahd->msgout_index = 0;
3379                         ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
3380                 } else {
3381                         ahd_print_path(ahd, scb);
3382                         scb->flags |= SCB_ABORT;
3383                 }
3384                 printf("Protocol violation %s.  Attempting to abort.\n",
3385                        ahd_lookup_phase_entry(curphase)->phasemsg);
3386         }
3387 }
3388
3389 /*
3390  * Force renegotiation to occur the next time we initiate
3391  * a command to the current device.
3392  */
3393 static void
3394 ahd_force_renegotiation(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
3395 {
3396         struct  ahd_initiator_tinfo *targ_info;
3397         struct  ahd_tmode_tstate *tstate;
3398
3399 #ifdef AHD_DEBUG
3400         if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
3401                 ahd_print_devinfo(ahd, devinfo);
3402                 printf("Forcing renegotiation\n");
3403         }
3404 #endif
3405         targ_info = ahd_fetch_transinfo(ahd,
3406                                         devinfo->channel,
3407                                         devinfo->our_scsiid,
3408                                         devinfo->target,
3409                                         &tstate);
3410         ahd_update_neg_request(ahd, devinfo, tstate,
3411                                targ_info, AHD_NEG_IF_NON_ASYNC);
3412 }
3413
3414 #define AHD_MAX_STEPS 2000
3415 static void
3416 ahd_clear_critical_section(struct ahd_softc *ahd)
3417 {
3418         ahd_mode_state  saved_modes;
3419         int             stepping;
3420         int             steps;
3421         int             first_instr;
3422         u_int           simode0;
3423         u_int           simode1;
3424         u_int           simode3;
3425         u_int           lqimode0;
3426         u_int           lqimode1;
3427         u_int           lqomode0;
3428         u_int           lqomode1;
3429
3430         if (ahd->num_critical_sections == 0)
3431                 return;
3432
3433         stepping = FALSE;
3434         steps = 0;
3435         first_instr = 0;
3436         simode0 = 0;
3437         simode1 = 0;
3438         simode3 = 0;
3439         lqimode0 = 0;
3440         lqimode1 = 0;
3441         lqomode0 = 0;
3442         lqomode1 = 0;
3443         saved_modes = ahd_save_modes(ahd);
3444         for (;;) {
3445                 struct  cs *cs;
3446                 u_int   seqaddr;
3447                 u_int   i;
3448
3449                 ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
3450                 seqaddr = ahd_inw(ahd, CURADDR);
3451
3452                 cs = ahd->critical_sections;
3453                 for (i = 0; i < ahd->num_critical_sections; i++, cs++) {
3454                         
3455                         if (cs->begin < seqaddr && cs->end >= seqaddr)
3456                                 break;
3457                 }
3458
3459                 if (i == ahd->num_critical_sections)
3460                         break;
3461
3462                 if (steps > AHD_MAX_STEPS) {
3463                         printf("%s: Infinite loop in critical section\n"
3464                                "%s: First Instruction 0x%x now 0x%x\n",
3465                                ahd_name(ahd), ahd_name(ahd), first_instr,
3466                                seqaddr);
3467                         ahd_dump_card_state(ahd);
3468                         panic("critical section loop");
3469                 }
3470
3471                 steps++;
3472 #ifdef AHD_DEBUG
3473                 if ((ahd_debug & AHD_SHOW_MISC) != 0)
3474                         printf("%s: Single stepping at 0x%x\n", ahd_name(ahd),
3475                                seqaddr);
3476 #endif
3477                 if (stepping == FALSE) {
3478
3479                         first_instr = seqaddr;
3480                         ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
3481                         simode0 = ahd_inb(ahd, SIMODE0);
3482                         simode3 = ahd_inb(ahd, SIMODE3);
3483                         lqimode0 = ahd_inb(ahd, LQIMODE0);
3484                         lqimode1 = ahd_inb(ahd, LQIMODE1);
3485                         lqomode0 = ahd_inb(ahd, LQOMODE0);
3486                         lqomode1 = ahd_inb(ahd, LQOMODE1);
3487                         ahd_outb(ahd, SIMODE0, 0);
3488                         ahd_outb(ahd, SIMODE3, 0);
3489                         ahd_outb(ahd, LQIMODE0, 0);
3490                         ahd_outb(ahd, LQIMODE1, 0);
3491                         ahd_outb(ahd, LQOMODE0, 0);
3492                         ahd_outb(ahd, LQOMODE1, 0);
3493                         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
3494                         simode1 = ahd_inb(ahd, SIMODE1);
3495                         /*
3496                          * We don't clear ENBUSFREE.  Unfortunately
3497                          * we cannot re-enable busfree detection within
3498                          * the current connection, so we must leave it
3499                          * on while single stepping.
3500                          */
3501                         ahd_outb(ahd, SIMODE1, simode1 & ENBUSFREE);
3502                         ahd_outb(ahd, SEQCTL0, ahd_inb(ahd, SEQCTL0) | STEP);
3503                         stepping = TRUE;
3504                 }
3505                 ahd_outb(ahd, CLRSINT1, CLRBUSFREE);
3506                 ahd_outb(ahd, CLRINT, CLRSCSIINT);
3507                 ahd_set_modes(ahd, ahd->saved_src_mode, ahd->saved_dst_mode);
3508                 ahd_outb(ahd, HCNTRL, ahd->unpause);
3509                 while (!ahd_is_paused(ahd))
3510                         ahd_delay(200);
3511                 ahd_update_modes(ahd);
3512         }
3513         if (stepping) {
3514                 ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
3515                 ahd_outb(ahd, SIMODE0, simode0);
3516                 ahd_outb(ahd, SIMODE3, simode3);
3517                 ahd_outb(ahd, LQIMODE0, lqimode0);
3518                 ahd_outb(ahd, LQIMODE1, lqimode1);
3519                 ahd_outb(ahd, LQOMODE0, lqomode0);
3520                 ahd_outb(ahd, LQOMODE1, lqomode1);
3521                 ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
3522                 ahd_outb(ahd, SEQCTL0, ahd_inb(ahd, SEQCTL0) & ~STEP);
3523                 ahd_outb(ahd, SIMODE1, simode1);
3524                 /*
3525                  * SCSIINT seems to glitch occassionally when
3526                  * the interrupt masks are restored.  Clear SCSIINT
3527                  * one more time so that only persistent errors
3528                  * are seen as a real interrupt.
3529                  */
3530                 ahd_outb(ahd, CLRINT, CLRSCSIINT);
3531         }
3532         ahd_restore_modes(ahd, saved_modes);
3533 }
3534
3535 /*
3536  * Clear any pending interrupt status.
3537  */
3538 static void
3539 ahd_clear_intstat(struct ahd_softc *ahd)
3540 {
3541         AHD_ASSERT_MODES(ahd, ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK),
3542                          ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK));
3543         /* Clear any interrupt conditions this may have caused */
3544         ahd_outb(ahd, CLRLQIINT0, CLRLQIATNQAS|CLRLQICRCT1|CLRLQICRCT2
3545                                  |CLRLQIBADLQT|CLRLQIATNLQ|CLRLQIATNCMD);
3546         ahd_outb(ahd, CLRLQIINT1, CLRLQIPHASE_LQ|CLRLQIPHASE_NLQ|CLRLIQABORT
3547                                  |CLRLQICRCI_LQ|CLRLQICRCI_NLQ|CLRLQIBADLQI
3548                                  |CLRLQIOVERI_LQ|CLRLQIOVERI_NLQ|CLRNONPACKREQ);
3549         ahd_outb(ahd, CLRLQOINT0, CLRLQOTARGSCBPERR|CLRLQOSTOPT2|CLRLQOATNLQ
3550                                  |CLRLQOATNPKT|CLRLQOTCRC);
3551         ahd_outb(ahd, CLRLQOINT1, CLRLQOINITSCBPERR|CLRLQOSTOPI2|CLRLQOBADQAS
3552                                  |CLRLQOBUSFREE|CLRLQOPHACHGINPKT);
3553         if ((ahd->bugs & AHD_CLRLQO_AUTOCLR_BUG) != 0) {
3554                 ahd_outb(ahd, CLRLQOINT0, 0);
3555                 ahd_outb(ahd, CLRLQOINT1, 0);
3556         }
3557         ahd_outb(ahd, CLRSINT3, CLRNTRAMPERR|CLROSRAMPERR);
3558         ahd_outb(ahd, CLRSINT1, CLRSELTIMEO|CLRATNO|CLRSCSIRSTI
3559                                 |CLRBUSFREE|CLRSCSIPERR|CLRREQINIT);
3560         ahd_outb(ahd, CLRSINT0, CLRSELDO|CLRSELDI|CLRSELINGO
3561                                 |CLRIOERR|CLROVERRUN);
3562         ahd_outb(ahd, CLRINT, CLRSCSIINT);
3563 }
3564
3565 /**************************** Debugging Routines ******************************/
3566 #ifdef AHD_DEBUG
3567 uint32_t ahd_debug = AHD_DEBUG_OPTS;
3568 #endif
3569
3570 #if 0
3571 void
3572 ahd_print_scb(struct scb *scb)
3573 {
3574         struct hardware_scb *hscb;
3575         int i;
3576
3577         hscb = scb->hscb;
3578         printf("scb:%p control:0x%x scsiid:0x%x lun:%d cdb_len:%d\n",
3579                (void *)scb,
3580                hscb->control,
3581                hscb->scsiid,
3582                hscb->lun,
3583                hscb->cdb_len);
3584         printf("Shared Data: ");
3585         for (i = 0; i < sizeof(hscb->shared_data.idata.cdb); i++)
3586                 printf("%#02x", hscb->shared_data.idata.cdb[i]);
3587         printf("        dataptr:%#x%x datacnt:%#x sgptr:%#x tag:%#x\n",
3588                (uint32_t)((ahd_le64toh(hscb->dataptr) >> 32) & 0xFFFFFFFF),
3589                (uint32_t)(ahd_le64toh(hscb->dataptr) & 0xFFFFFFFF),
3590                ahd_le32toh(hscb->datacnt),
3591                ahd_le32toh(hscb->sgptr),
3592                SCB_GET_TAG(scb));
3593         ahd_dump_sglist(scb);
3594 }
3595 #endif  /*  0  */
3596
3597 /************************* Transfer Negotiation *******************************/
3598 /*
3599  * Allocate per target mode instance (ID we respond to as a target)
3600  * transfer negotiation data structures.
3601  */
3602 static struct ahd_tmode_tstate *
3603 ahd_alloc_tstate(struct ahd_softc *ahd, u_int scsi_id, char channel)
3604 {
3605         struct ahd_tmode_tstate *master_tstate;
3606         struct ahd_tmode_tstate *tstate;
3607         int i;
3608
3609         master_tstate = ahd->enabled_targets[ahd->our_id];
3610         if (ahd->enabled_targets[scsi_id] != NULL
3611          && ahd->enabled_targets[scsi_id] != master_tstate)
3612                 panic("%s: ahd_alloc_tstate - Target already allocated",
3613                       ahd_name(ahd));
3614         tstate = malloc(sizeof(*tstate), M_DEVBUF, M_NOWAIT);
3615         if (tstate == NULL)
3616                 return (NULL);
3617
3618         /*
3619          * If we have allocated a master tstate, copy user settings from
3620          * the master tstate (taken from SRAM or the EEPROM) for this
3621          * channel, but reset our current and goal settings to async/narrow
3622          * until an initiator talks to us.
3623          */
3624         if (master_tstate != NULL) {
3625                 memcpy(tstate, master_tstate, sizeof(*tstate));
3626                 memset(tstate->enabled_luns, 0, sizeof(tstate->enabled_luns));
3627                 for (i = 0; i < 16; i++) {
3628                         memset(&tstate->transinfo[i].curr, 0,
3629                               sizeof(tstate->transinfo[i].curr));
3630                         memset(&tstate->transinfo[i].goal, 0,
3631                               sizeof(tstate->transinfo[i].goal));
3632                 }
3633         } else
3634                 memset(tstate, 0, sizeof(*tstate));
3635         ahd->enabled_targets[scsi_id] = tstate;
3636         return (tstate);
3637 }
3638
3639 #ifdef AHD_TARGET_MODE
3640 /*
3641  * Free per target mode instance (ID we respond to as a target)
3642  * transfer negotiation data structures.
3643  */
3644 static void
3645 ahd_free_tstate(struct ahd_softc *ahd, u_int scsi_id, char channel, int force)
3646 {
3647         struct ahd_tmode_tstate *tstate;
3648
3649         /*
3650          * Don't clean up our "master" tstate.
3651          * It has our default user settings.
3652          */
3653         if (scsi_id == ahd->our_id
3654          && force == FALSE)
3655                 return;
3656
3657         tstate = ahd->enabled_targets[scsi_id];
3658         if (tstate != NULL)
3659                 free(tstate, M_DEVBUF);
3660         ahd->enabled_targets[scsi_id] = NULL;
3661 }
3662 #endif
3663
3664 /*
3665  * Called when we have an active connection to a target on the bus,
3666  * this function finds the nearest period to the input period limited
3667  * by the capabilities of the bus connectivity of and sync settings for
3668  * the target.
3669  */
3670 void
3671 ahd_devlimited_syncrate(struct ahd_softc *ahd,
3672                         struct ahd_initiator_tinfo *tinfo,
3673                         u_int *period, u_int *ppr_options, role_t role)
3674 {
3675         struct  ahd_transinfo *transinfo;
3676         u_int   maxsync;
3677
3678         if ((ahd_inb(ahd, SBLKCTL) & ENAB40) != 0
3679          && (ahd_inb(ahd, SSTAT2) & EXP_ACTIVE) == 0) {
3680                 maxsync = AHD_SYNCRATE_PACED;
3681         } else {
3682                 maxsync = AHD_SYNCRATE_ULTRA;
3683                 /* Can't do DT related options on an SE bus */
3684                 *ppr_options &= MSG_EXT_PPR_QAS_REQ;
3685         }
3686         /*
3687          * Never allow a value higher than our current goal
3688          * period otherwise we may allow a target initiated
3689          * negotiation to go above the limit as set by the
3690          * user.  In the case of an initiator initiated
3691          * sync negotiation, we limit based on the user
3692          * setting.  This allows the system to still accept
3693          * incoming negotiations even if target initiated
3694          * negotiation is not performed.
3695          */
3696         if (role == ROLE_TARGET)
3697                 transinfo = &tinfo->user;
3698         else 
3699                 transinfo = &tinfo->goal;
3700         *ppr_options &= (transinfo->ppr_options|MSG_EXT_PPR_PCOMP_EN);
3701         if (transinfo->width == MSG_EXT_WDTR_BUS_8_BIT) {
3702                 maxsync = max(maxsync, (u_int)AHD_SYNCRATE_ULTRA2);
3703                 *ppr_options &= ~MSG_EXT_PPR_DT_REQ;
3704         }
3705         if (transinfo->period == 0) {
3706                 *period = 0;
3707                 *ppr_options = 0;
3708         } else {
3709                 *period = max(*period, (u_int)transinfo->period);
3710                 ahd_find_syncrate(ahd, period, ppr_options, maxsync);
3711         }
3712 }
3713
3714 /*
3715  * Look up the valid period to SCSIRATE conversion in our table.
3716  * Return the period and offset that should be sent to the target
3717  * if this was the beginning of an SDTR.
3718  */
3719 void
3720 ahd_find_syncrate(struct ahd_softc *ahd, u_int *period,
3721                   u_int *ppr_options, u_int maxsync)
3722 {
3723         if (*period < maxsync)
3724                 *period = maxsync;
3725
3726         if ((*ppr_options & MSG_EXT_PPR_DT_REQ) != 0
3727          && *period > AHD_SYNCRATE_MIN_DT)
3728                 *ppr_options &= ~MSG_EXT_PPR_DT_REQ;
3729                 
3730         if (*period > AHD_SYNCRATE_MIN)
3731                 *period = 0;
3732
3733         /* Honor PPR option conformance rules. */
3734         if (*period > AHD_SYNCRATE_PACED)
3735                 *ppr_options &= ~MSG_EXT_PPR_RTI;
3736
3737         if ((*ppr_options & MSG_EXT_PPR_IU_REQ) == 0)
3738                 *ppr_options &= (MSG_EXT_PPR_DT_REQ|MSG_EXT_PPR_QAS_REQ);
3739
3740         if ((*ppr_options & MSG_EXT_PPR_DT_REQ) == 0)
3741                 *ppr_options &= MSG_EXT_PPR_QAS_REQ;
3742
3743         /* Skip all PACED only entries if IU is not available */
3744         if ((*ppr_options & MSG_EXT_PPR_IU_REQ) == 0
3745          && *period < AHD_SYNCRATE_DT)
3746                 *period = AHD_SYNCRATE_DT;
3747
3748         /* Skip all DT only entries if DT is not available */
3749         if ((*ppr_options & MSG_EXT_PPR_DT_REQ) == 0
3750          && *period < AHD_SYNCRATE_ULTRA2)
3751                 *period = AHD_SYNCRATE_ULTRA2;
3752 }
3753
3754 /*
3755  * Truncate the given synchronous offset to a value the
3756  * current adapter type and syncrate are capable of.
3757  */
3758 static void
3759 ahd_validate_offset(struct ahd_softc *ahd,
3760                     struct ahd_initiator_tinfo *tinfo,
3761                     u_int period, u_int *offset, int wide,
3762                     role_t role)
3763 {
3764         u_int maxoffset;
3765
3766         /* Limit offset to what we can do */
3767         if (period == 0)
3768                 maxoffset = 0;
3769         else if (period <= AHD_SYNCRATE_PACED) {
3770                 if ((ahd->bugs & AHD_PACED_NEGTABLE_BUG) != 0)
3771                         maxoffset = MAX_OFFSET_PACED_BUG;
3772                 else
3773                         maxoffset = MAX_OFFSET_PACED;
3774         } else
3775                 maxoffset = MAX_OFFSET_NON_PACED;
3776         *offset = min(*offset, maxoffset);
3777         if (tinfo != NULL) {
3778                 if (role == ROLE_TARGET)
3779                         *offset = min(*offset, (u_int)tinfo->user.offset);
3780                 else
3781                         *offset = min(*offset, (u_int)tinfo->goal.offset);
3782         }
3783 }
3784
3785 /*
3786  * Truncate the given transfer width parameter to a value the
3787  * current adapter type is capable of.
3788  */
3789 static void
3790 ahd_validate_width(struct ahd_softc *ahd, struct ahd_initiator_tinfo *tinfo,
3791                    u_int *bus_width, role_t role)
3792 {
3793         switch (*bus_width) {
3794         default:
3795                 if (ahd->features & AHD_WIDE) {
3796                         /* Respond Wide */
3797                         *bus_width = MSG_EXT_WDTR_BUS_16_BIT;
3798                         break;
3799                 }
3800                 /* FALLTHROUGH */
3801         case MSG_EXT_WDTR_BUS_8_BIT:
3802                 *bus_width = MSG_EXT_WDTR_BUS_8_BIT;
3803                 break;
3804         }
3805         if (tinfo != NULL) {
3806                 if (role == ROLE_TARGET)
3807                         *bus_width = min((u_int)tinfo->user.width, *bus_width);
3808                 else
3809                         *bus_width = min((u_int)tinfo->goal.width, *bus_width);
3810         }
3811 }
3812
3813 /*
3814  * Update the bitmask of targets for which the controller should
3815  * negotiate with at the next convenient oportunity.  This currently
3816  * means the next time we send the initial identify messages for
3817  * a new transaction.
3818  */
3819 int
3820 ahd_update_neg_request(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
3821                        struct ahd_tmode_tstate *tstate,
3822                        struct ahd_initiator_tinfo *tinfo, ahd_neg_type neg_type)
3823 {
3824         u_int auto_negotiate_orig;
3825
3826         auto_negotiate_orig = tstate->auto_negotiate;
3827         if (neg_type == AHD_NEG_ALWAYS) {
3828                 /*
3829                  * Force our "current" settings to be
3830                  * unknown so that unless a bus reset
3831                  * occurs the need to renegotiate is
3832                  * recorded persistently.
3833                  */
3834                 if ((ahd->features & AHD_WIDE) != 0)
3835                         tinfo->curr.width = AHD_WIDTH_UNKNOWN;
3836                 tinfo->curr.period = AHD_PERIOD_UNKNOWN;
3837                 tinfo->curr.offset = AHD_OFFSET_UNKNOWN;
3838         }
3839         if (tinfo->curr.period != tinfo->goal.period
3840          || tinfo->curr.width != tinfo->goal.width
3841          || tinfo->curr.offset != tinfo->goal.offset
3842          || tinfo->curr.ppr_options != tinfo->goal.ppr_options
3843          || (neg_type == AHD_NEG_IF_NON_ASYNC
3844           && (tinfo->goal.offset != 0
3845            || tinfo->goal.width != MSG_EXT_WDTR_BUS_8_BIT
3846            || tinfo->goal.ppr_options != 0)))
3847                 tstate->auto_negotiate |= devinfo->target_mask;
3848         else
3849                 tstate->auto_negotiate &= ~devinfo->target_mask;
3850
3851         return (auto_negotiate_orig != tstate->auto_negotiate);
3852 }
3853
3854 /*
3855  * Update the user/goal/curr tables of synchronous negotiation
3856  * parameters as well as, in the case of a current or active update,
3857  * any data structures on the host controller.  In the case of an
3858  * active update, the specified target is currently talking to us on
3859  * the bus, so the transfer parameter update must take effect
3860  * immediately.
3861  */
3862 void
3863 ahd_set_syncrate(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
3864                  u_int period, u_int offset, u_int ppr_options,
3865                  u_int type, int paused)
3866 {
3867         struct  ahd_initiator_tinfo *tinfo;
3868         struct  ahd_tmode_tstate *tstate;
3869         u_int   old_period;
3870         u_int   old_offset;
3871         u_int   old_ppr;
3872         int     active;
3873         int     update_needed;
3874
3875         active = (type & AHD_TRANS_ACTIVE) == AHD_TRANS_ACTIVE;
3876         update_needed = 0;
3877
3878         if (period == 0 || offset == 0) {
3879                 period = 0;
3880                 offset = 0;
3881         }
3882
3883         tinfo = ahd_fetch_transinfo(ahd, devinfo->channel, devinfo->our_scsiid,
3884                                     devinfo->target, &tstate);
3885
3886         if ((type & AHD_TRANS_USER) != 0) {
3887                 tinfo->user.period = period;
3888                 tinfo->user.offset = offset;
3889                 tinfo->user.ppr_options = ppr_options;
3890         }
3891
3892         if ((type & AHD_TRANS_GOAL) != 0) {
3893                 tinfo->goal.period = period;
3894                 tinfo->goal.offset = offset;
3895                 tinfo->goal.ppr_options = ppr_options;
3896         }
3897
3898         old_period = tinfo->curr.period;
3899         old_offset = tinfo->curr.offset;
3900         old_ppr    = tinfo->curr.ppr_options;
3901
3902         if ((type & AHD_TRANS_CUR) != 0
3903          && (old_period != period
3904           || old_offset != offset
3905           || old_ppr != ppr_options)) {
3906
3907                 update_needed++;
3908
3909                 tinfo->curr.period = period;
3910                 tinfo->curr.offset = offset;
3911                 tinfo->curr.ppr_options = ppr_options;
3912
3913                 ahd_send_async(ahd, devinfo->channel, devinfo->target,
3914                                CAM_LUN_WILDCARD, AC_TRANSFER_NEG);
3915                 if (bootverbose) {
3916                         if (offset != 0) {
3917                                 int options;
3918
3919                                 printf("%s: target %d synchronous with "
3920                                        "period = 0x%x, offset = 0x%x",
3921                                        ahd_name(ahd), devinfo->target,
3922                                        period, offset);
3923                                 options = 0;
3924                                 if ((ppr_options & MSG_EXT_PPR_RD_STRM) != 0) {
3925                                         printf("(RDSTRM");
3926                                         options++;
3927                                 }
3928                                 if ((ppr_options & MSG_EXT_PPR_DT_REQ) != 0) {
3929                                         printf("%s", options ? "|DT" : "(DT");
3930                                         options++;
3931                                 }
3932                                 if ((ppr_options & MSG_EXT_PPR_IU_REQ) != 0) {
3933                                         printf("%s", options ? "|IU" : "(IU");
3934                                         options++;
3935                                 }
3936                                 if ((ppr_options & MSG_EXT_PPR_RTI) != 0) {
3937                                         printf("%s", options ? "|RTI" : "(RTI");
3938                                         options++;
3939                                 }
3940                                 if ((ppr_options & MSG_EXT_PPR_QAS_REQ) != 0) {
3941                                         printf("%s", options ? "|QAS" : "(QAS");
3942                                         options++;
3943                                 }
3944                                 if (options != 0)
3945                                         printf(")\n");
3946                                 else
3947                                         printf("\n");
3948                         } else {
3949                                 printf("%s: target %d using "
3950                                        "asynchronous transfers%s\n",
3951                                        ahd_name(ahd), devinfo->target,
3952                                        (ppr_options & MSG_EXT_PPR_QAS_REQ) != 0
3953                                      ?  "(QAS)" : "");
3954                         }
3955                 }
3956         }
3957         /*
3958          * Always refresh the neg-table to handle the case of the
3959          * sequencer setting the ENATNO bit for a MK_MESSAGE request.
3960          * We will always renegotiate in that case if this is a
3961          * packetized request.  Also manage the busfree expected flag
3962          * from this common routine so that we catch changes due to
3963          * WDTR or SDTR messages.
3964          */
3965         if ((type & AHD_TRANS_CUR) != 0) {
3966                 if (!paused)
3967                         ahd_pause(ahd);
3968                 ahd_update_neg_table(ahd, devinfo, &tinfo->curr);
3969                 if (!paused)
3970                         ahd_unpause(ahd);
3971                 if (ahd->msg_type != MSG_TYPE_NONE) {
3972                         if ((old_ppr & MSG_EXT_PPR_IU_REQ)
3973                          != (ppr_options & MSG_EXT_PPR_IU_REQ)) {
3974 #ifdef AHD_DEBUG
3975                                 if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
3976                                         ahd_print_devinfo(ahd, devinfo);
3977                                         printf("Expecting IU Change busfree\n");
3978                                 }
3979 #endif
3980                                 ahd->msg_flags |= MSG_FLAG_EXPECT_PPR_BUSFREE
3981                                                |  MSG_FLAG_IU_REQ_CHANGED;
3982                         }
3983                         if ((old_ppr & MSG_EXT_PPR_IU_REQ) != 0) {
3984 #ifdef AHD_DEBUG
3985                                 if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
3986                                         printf("PPR with IU_REQ outstanding\n");
3987 #endif
3988                                 ahd->msg_flags |= MSG_FLAG_EXPECT_PPR_BUSFREE;
3989                         }
3990                 }
3991         }
3992
3993         update_needed += ahd_update_neg_request(ahd, devinfo, tstate,
3994                                                 tinfo, AHD_NEG_TO_GOAL);
3995
3996         if (update_needed && active)
3997                 ahd_update_pending_scbs(ahd);
3998 }
3999
4000 /*
4001  * Update the user/goal/curr tables of wide negotiation
4002  * parameters as well as, in the case of a current or active update,
4003  * any data structures on the host controller.  In the case of an
4004  * active update, the specified target is currently talking to us on
4005  * the bus, so the transfer parameter update must take effect
4006  * immediately.
4007  */
4008 void
4009 ahd_set_width(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
4010               u_int width, u_int type, int paused)
4011 {
4012         struct  ahd_initiator_tinfo *tinfo;
4013         struct  ahd_tmode_tstate *tstate;
4014         u_int   oldwidth;
4015         int     active;
4016         int     update_needed;
4017
4018         active = (type & AHD_TRANS_ACTIVE) == AHD_TRANS_ACTIVE;
4019         update_needed = 0;
4020         tinfo = ahd_fetch_transinfo(ahd, devinfo->channel, devinfo->our_scsiid,
4021                                     devinfo->target, &tstate);
4022
4023         if ((type & AHD_TRANS_USER) != 0)
4024                 tinfo->user.width = width;
4025
4026         if ((type & AHD_TRANS_GOAL) != 0)
4027                 tinfo->goal.width = width;
4028
4029         oldwidth = tinfo->curr.width;
4030         if ((type & AHD_TRANS_CUR) != 0 && oldwidth != width) {
4031
4032                 update_needed++;
4033
4034                 tinfo->curr.width = width;
4035                 ahd_send_async(ahd, devinfo->channel, devinfo->target,
4036                                CAM_LUN_WILDCARD, AC_TRANSFER_NEG);
4037                 if (bootverbose) {
4038                         printf("%s: target %d using %dbit transfers\n",
4039                                ahd_name(ahd), devinfo->target,
4040                                8 * (0x01 << width));
4041                 }
4042         }
4043
4044         if ((type & AHD_TRANS_CUR) != 0) {
4045                 if (!paused)
4046                         ahd_pause(ahd);
4047                 ahd_update_neg_table(ahd, devinfo, &tinfo->curr);
4048                 if (!paused)
4049                         ahd_unpause(ahd);
4050         }
4051
4052         update_needed += ahd_update_neg_request(ahd, devinfo, tstate,
4053                                                 tinfo, AHD_NEG_TO_GOAL);
4054         if (update_needed && active)
4055                 ahd_update_pending_scbs(ahd);
4056
4057 }
4058
4059 /*
4060  * Update the current state of tagged queuing for a given target.
4061  */
4062 static void
4063 ahd_set_tags(struct ahd_softc *ahd, struct scsi_cmnd *cmd,
4064              struct ahd_devinfo *devinfo, ahd_queue_alg alg)
4065 {
4066         struct scsi_device *sdev = cmd->device;
4067
4068         ahd_platform_set_tags(ahd, sdev, devinfo, alg);
4069         ahd_send_async(ahd, devinfo->channel, devinfo->target,
4070                        devinfo->lun, AC_TRANSFER_NEG);
4071 }
4072
4073 static void
4074 ahd_update_neg_table(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
4075                      struct ahd_transinfo *tinfo)
4076 {
4077         ahd_mode_state  saved_modes;
4078         u_int           period;
4079         u_int           ppr_opts;
4080         u_int           con_opts;
4081         u_int           offset;
4082         u_int           saved_negoaddr;
4083         uint8_t         iocell_opts[sizeof(ahd->iocell_opts)];
4084
4085         saved_modes = ahd_save_modes(ahd);
4086         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
4087
4088         saved_negoaddr = ahd_inb(ahd, NEGOADDR);
4089         ahd_outb(ahd, NEGOADDR, devinfo->target);
4090         period = tinfo->period;
4091         offset = tinfo->offset;
4092         memcpy(iocell_opts, ahd->iocell_opts, sizeof(ahd->iocell_opts)); 
4093         ppr_opts = tinfo->ppr_options & (MSG_EXT_PPR_QAS_REQ|MSG_EXT_PPR_DT_REQ
4094                                         |MSG_EXT_PPR_IU_REQ|MSG_EXT_PPR_RTI);
4095         con_opts = 0;
4096         if (period == 0)
4097                 period = AHD_SYNCRATE_ASYNC;
4098         if (period == AHD_SYNCRATE_160) {
4099
4100                 if ((ahd->bugs & AHD_PACED_NEGTABLE_BUG) != 0) {
4101                         /*
4102                          * When the SPI4 spec was finalized, PACE transfers
4103                          * was not made a configurable option in the PPR
4104                          * message.  Instead it is assumed to be enabled for
4105                          * any syncrate faster than 80MHz.  Nevertheless,
4106                          * Harpoon2A4 allows this to be configurable.
4107                          *
4108                          * Harpoon2A4 also assumes at most 2 data bytes per
4109                          * negotiated REQ/ACK offset.  Paced transfers take
4110                          * 4, so we must adjust our offset.
4111                          */
4112                         ppr_opts |= PPROPT_PACE;
4113                         offset *= 2;
4114
4115                         /*
4116                          * Harpoon2A assumed that there would be a
4117                          * fallback rate between 160MHz and 80Mhz,
4118                          * so 7 is used as the period factor rather
4119                          * than 8 for 160MHz.
4120                          */
4121                         period = AHD_SYNCRATE_REVA_160;
4122                 }
4123                 if ((tinfo->ppr_options & MSG_EXT_PPR_PCOMP_EN) == 0)
4124                         iocell_opts[AHD_PRECOMP_SLEW_INDEX] &=
4125                             ~AHD_PRECOMP_MASK;
4126         } else {
4127                 /*
4128                  * Precomp should be disabled for non-paced transfers.
4129                  */
4130                 iocell_opts[AHD_PRECOMP_SLEW_INDEX] &= ~AHD_PRECOMP_MASK;
4131
4132                 if ((ahd->features & AHD_NEW_IOCELL_OPTS) != 0
4133                  && (ppr_opts & MSG_EXT_PPR_DT_REQ) != 0
4134                  && (ppr_opts & MSG_EXT_PPR_IU_REQ) == 0) {
4135                         /*
4136                          * Slow down our CRC interval to be
4137                          * compatible with non-packetized
4138                          * U160 devices that can't handle a
4139                          * CRC at full speed.
4140                          */
4141                         con_opts |= ENSLOWCRC;
4142                 }
4143
4144                 if ((ahd->bugs & AHD_PACED_NEGTABLE_BUG) != 0) {
4145                         /*
4146                          * On H2A4, revert to a slower slewrate
4147                          * on non-paced transfers.
4148                          */
4149                         iocell_opts[AHD_PRECOMP_SLEW_INDEX] &=
4150                             ~AHD_SLEWRATE_MASK;
4151                 }
4152         }
4153
4154         ahd_outb(ahd, ANNEXCOL, AHD_ANNEXCOL_PRECOMP_SLEW);
4155         ahd_outb(ahd, ANNEXDAT, iocell_opts[AHD_PRECOMP_SLEW_INDEX]);
4156         ahd_outb(ahd, ANNEXCOL, AHD_ANNEXCOL_AMPLITUDE);
4157         ahd_outb(ahd, ANNEXDAT, iocell_opts[AHD_AMPLITUDE_INDEX]);
4158
4159         ahd_outb(ahd, NEGPERIOD, period);
4160         ahd_outb(ahd, NEGPPROPTS, ppr_opts);
4161         ahd_outb(ahd, NEGOFFSET, offset);
4162
4163         if (tinfo->width == MSG_EXT_WDTR_BUS_16_BIT)
4164                 con_opts |= WIDEXFER;
4165
4166         /*
4167          * Slow down our CRC interval to be
4168          * compatible with packetized U320 devices
4169          * that can't handle a CRC at full speed
4170          */
4171         if (ahd->features & AHD_AIC79XXB_SLOWCRC) {
4172                 con_opts |= ENSLOWCRC;
4173         }
4174
4175         /*
4176          * During packetized transfers, the target will
4177          * give us the oportunity to send command packets
4178          * without us asserting attention.
4179          */
4180         if ((tinfo->ppr_options & MSG_EXT_PPR_IU_REQ) == 0)
4181                 con_opts |= ENAUTOATNO;
4182         ahd_outb(ahd, NEGCONOPTS, con_opts);
4183         ahd_outb(ahd, NEGOADDR, saved_negoaddr);
4184         ahd_restore_modes(ahd, saved_modes);
4185 }
4186
4187 /*
4188  * When the transfer settings for a connection change, setup for
4189  * negotiation in pending SCBs to effect the change as quickly as
4190  * possible.  We also cancel any negotiations that are scheduled
4191  * for inflight SCBs that have not been started yet.
4192  */
4193 static void
4194 ahd_update_pending_scbs(struct ahd_softc *ahd)
4195 {
4196         struct          scb *pending_scb;
4197         int             pending_scb_count;
4198         int             paused;
4199         u_int           saved_scbptr;
4200         ahd_mode_state  saved_modes;
4201
4202         /*
4203          * Traverse the pending SCB list and ensure that all of the
4204          * SCBs there have the proper settings.  We can only safely
4205          * clear the negotiation required flag (setting requires the
4206          * execution queue to be modified) and this is only possible
4207          * if we are not already attempting to select out for this
4208          * SCB.  For this reason, all callers only call this routine
4209          * if we are changing the negotiation settings for the currently
4210          * active transaction on the bus.
4211          */
4212         pending_scb_count = 0;
4213         LIST_FOREACH(pending_scb, &ahd->pending_scbs, pending_links) {
4214                 struct ahd_devinfo devinfo;
4215                 struct ahd_initiator_tinfo *tinfo;
4216                 struct ahd_tmode_tstate *tstate;
4217
4218                 ahd_scb_devinfo(ahd, &devinfo, pending_scb);
4219                 tinfo = ahd_fetch_transinfo(ahd, devinfo.channel,
4220                                             devinfo.our_scsiid,
4221                                             devinfo.target, &tstate);
4222                 if ((tstate->auto_negotiate & devinfo.target_mask) == 0
4223                  && (pending_scb->flags & SCB_AUTO_NEGOTIATE) != 0) {
4224                         pending_scb->flags &= ~SCB_AUTO_NEGOTIATE;
4225                         pending_scb->hscb->control &= ~MK_MESSAGE;
4226                 }
4227                 ahd_sync_scb(ahd, pending_scb,
4228                              BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
4229                 pending_scb_count++;
4230         }
4231
4232         if (pending_scb_count == 0)
4233                 return;
4234
4235         if (ahd_is_paused(ahd)) {
4236                 paused = 1;
4237         } else {
4238                 paused = 0;
4239                 ahd_pause(ahd);
4240         }
4241
4242         /*
4243          * Force the sequencer to reinitialize the selection for
4244          * the command at the head of the execution queue if it
4245          * has already been setup.  The negotiation changes may
4246          * effect whether we select-out with ATN.  It is only
4247          * safe to clear ENSELO when the bus is not free and no
4248          * selection is in progres or completed.
4249          */
4250         saved_modes = ahd_save_modes(ahd);
4251         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
4252         if ((ahd_inb(ahd, SCSISIGI) & BSYI) != 0
4253          && (ahd_inb(ahd, SSTAT0) & (SELDO|SELINGO)) == 0)
4254                 ahd_outb(ahd, SCSISEQ0, ahd_inb(ahd, SCSISEQ0) & ~ENSELO);
4255         saved_scbptr = ahd_get_scbptr(ahd);
4256         /* Ensure that the hscbs down on the card match the new information */
4257         LIST_FOREACH(pending_scb, &ahd->pending_scbs, pending_links) {
4258                 u_int   scb_tag;
4259                 u_int   control;
4260
4261                 scb_tag = SCB_GET_TAG(pending_scb);
4262                 ahd_set_scbptr(ahd, scb_tag);
4263                 control = ahd_inb_scbram(ahd, SCB_CONTROL);
4264                 control &= ~MK_MESSAGE;
4265                 control |= pending_scb->hscb->control & MK_MESSAGE;
4266                 ahd_outb(ahd, SCB_CONTROL, control);
4267         }
4268         ahd_set_scbptr(ahd, saved_scbptr);
4269         ahd_restore_modes(ahd, saved_modes);
4270
4271         if (paused == 0)
4272                 ahd_unpause(ahd);
4273 }
4274
4275 /**************************** Pathing Information *****************************/
4276 static void
4277 ahd_fetch_devinfo(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
4278 {
4279         ahd_mode_state  saved_modes;
4280         u_int           saved_scsiid;
4281         role_t          role;
4282         int             our_id;
4283
4284         saved_modes = ahd_save_modes(ahd);
4285         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
4286
4287         if (ahd_inb(ahd, SSTAT0) & TARGET)
4288                 role = ROLE_TARGET;
4289         else
4290                 role = ROLE_INITIATOR;
4291
4292         if (role == ROLE_TARGET
4293          && (ahd_inb(ahd, SEQ_FLAGS) & CMDPHASE_PENDING) != 0) {
4294                 /* We were selected, so pull our id from TARGIDIN */
4295                 our_id = ahd_inb(ahd, TARGIDIN) & OID;
4296         } else if (role == ROLE_TARGET)
4297                 our_id = ahd_inb(ahd, TOWNID);
4298         else
4299                 our_id = ahd_inb(ahd, IOWNID);
4300
4301         saved_scsiid = ahd_inb(ahd, SAVED_SCSIID);
4302         ahd_compile_devinfo(devinfo,
4303                             our_id,
4304                             SCSIID_TARGET(ahd, saved_scsiid),
4305                             ahd_inb(ahd, SAVED_LUN),
4306                             SCSIID_CHANNEL(ahd, saved_scsiid),
4307                             role);
4308         ahd_restore_modes(ahd, saved_modes);
4309 }
4310
4311 void
4312 ahd_print_devinfo(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
4313 {
4314         printf("%s:%c:%d:%d: ", ahd_name(ahd), 'A',
4315                devinfo->target, devinfo->lun);
4316 }
4317
4318 static struct ahd_phase_table_entry*
4319 ahd_lookup_phase_entry(int phase)
4320 {
4321         struct ahd_phase_table_entry *entry;
4322         struct ahd_phase_table_entry *last_entry;
4323
4324         /*
4325          * num_phases doesn't include the default entry which
4326          * will be returned if the phase doesn't match.
4327          */
4328         last_entry = &ahd_phase_table[num_phases];
4329         for (entry = ahd_phase_table; entry < last_entry; entry++) {
4330                 if (phase == entry->phase)
4331                         break;
4332         }
4333         return (entry);
4334 }
4335
4336 void
4337 ahd_compile_devinfo(struct ahd_devinfo *devinfo, u_int our_id, u_int target,
4338                     u_int lun, char channel, role_t role)
4339 {
4340         devinfo->our_scsiid = our_id;
4341         devinfo->target = target;
4342         devinfo->lun = lun;
4343         devinfo->target_offset = target;
4344         devinfo->channel = channel;
4345         devinfo->role = role;
4346         if (channel == 'B')
4347                 devinfo->target_offset += 8;
4348         devinfo->target_mask = (0x01 << devinfo->target_offset);
4349 }
4350
4351 static void
4352 ahd_scb_devinfo(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
4353                 struct scb *scb)
4354 {
4355         role_t  role;
4356         int     our_id;
4357
4358         our_id = SCSIID_OUR_ID(scb->hscb->scsiid);
4359         role = ROLE_INITIATOR;
4360         if ((scb->hscb->control & TARGET_SCB) != 0)
4361                 role = ROLE_TARGET;
4362         ahd_compile_devinfo(devinfo, our_id, SCB_GET_TARGET(ahd, scb),
4363                             SCB_GET_LUN(scb), SCB_GET_CHANNEL(ahd, scb), role);
4364 }
4365
4366
4367 /************************ Message Phase Processing ****************************/
4368 /*
4369  * When an initiator transaction with the MK_MESSAGE flag either reconnects
4370  * or enters the initial message out phase, we are interrupted.  Fill our
4371  * outgoing message buffer with the appropriate message and beging handing
4372  * the message phase(s) manually.
4373  */
4374 static void
4375 ahd_setup_initiator_msgout(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
4376                            struct scb *scb)
4377 {
4378         /*
4379          * To facilitate adding multiple messages together,
4380          * each routine should increment the index and len
4381          * variables instead of setting them explicitly.
4382          */
4383         ahd->msgout_index = 0;
4384         ahd->msgout_len = 0;
4385
4386         if (ahd_currently_packetized(ahd))
4387                 ahd->msg_flags |= MSG_FLAG_PACKETIZED;
4388
4389         if (ahd->send_msg_perror
4390          && ahd_inb(ahd, MSG_OUT) == HOST_MSG) {
4391                 ahd->msgout_buf[ahd->msgout_index++] = ahd->send_msg_perror;
4392                 ahd->msgout_len++;
4393                 ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
4394 #ifdef AHD_DEBUG
4395                 if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
4396                         printf("Setting up for Parity Error delivery\n");
4397 #endif
4398                 return;
4399         } else if (scb == NULL) {
4400                 printf("%s: WARNING. No pending message for "
4401                        "I_T msgin.  Issuing NO-OP\n", ahd_name(ahd));
4402                 ahd->msgout_buf[ahd->msgout_index++] = MSG_NOOP;
4403                 ahd->msgout_len++;
4404                 ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
4405                 return;
4406         }
4407
4408         if ((scb->flags & SCB_DEVICE_RESET) == 0
4409          && (scb->flags & SCB_PACKETIZED) == 0
4410          && ahd_inb(ahd, MSG_OUT) == MSG_IDENTIFYFLAG) {
4411                 u_int identify_msg;
4412
4413                 identify_msg = MSG_IDENTIFYFLAG | SCB_GET_LUN(scb);
4414                 if ((scb->hscb->control & DISCENB) != 0)
4415                         identify_msg |= MSG_IDENTIFY_DISCFLAG;
4416                 ahd->msgout_buf[ahd->msgout_index++] = identify_msg;
4417                 ahd->msgout_len++;
4418
4419                 if ((scb->hscb->control & TAG_ENB) != 0) {
4420                         ahd->msgout_buf[ahd->msgout_index++] =
4421                             scb->hscb->control & (TAG_ENB|SCB_TAG_TYPE);
4422                         ahd->msgout_buf[ahd->msgout_index++] = SCB_GET_TAG(scb);
4423                         ahd->msgout_len += 2;
4424                 }
4425         }
4426
4427         if (scb->flags & SCB_DEVICE_RESET) {
4428                 ahd->msgout_buf[ahd->msgout_index++] = MSG_BUS_DEV_RESET;
4429                 ahd->msgout_len++;
4430                 ahd_print_path(ahd, scb);
4431                 printf("Bus Device Reset Message Sent\n");
4432                 /*
4433                  * Clear our selection hardware in advance of
4434                  * the busfree.  We may have an entry in the waiting
4435                  * Q for this target, and we don't want to go about
4436                  * selecting while we handle the busfree and blow it
4437                  * away.
4438                  */
4439                 ahd_outb(ahd, SCSISEQ0, 0);
4440         } else if ((scb->flags & SCB_ABORT) != 0) {
4441
4442                 if ((scb->hscb->control & TAG_ENB) != 0) {
4443                         ahd->msgout_buf[ahd->msgout_index++] = MSG_ABORT_TAG;
4444                 } else {
4445                         ahd->msgout_buf[ahd->msgout_index++] = MSG_ABORT;
4446                 }
4447                 ahd->msgout_len++;
4448                 ahd_print_path(ahd, scb);
4449                 printf("Abort%s Message Sent\n",
4450                        (scb->hscb->control & TAG_ENB) != 0 ? " Tag" : "");
4451                 /*
4452                  * Clear our selection hardware in advance of
4453                  * the busfree.  We may have an entry in the waiting
4454                  * Q for this target, and we don't want to go about
4455                  * selecting while we handle the busfree and blow it
4456                  * away.
4457                  */
4458                 ahd_outb(ahd, SCSISEQ0, 0);
4459         } else if ((scb->flags & (SCB_AUTO_NEGOTIATE|SCB_NEGOTIATE)) != 0) {
4460                 ahd_build_transfer_msg(ahd, devinfo);
4461                 /*
4462                  * Clear our selection hardware in advance of potential
4463                  * PPR IU status change busfree.  We may have an entry in
4464                  * the waiting Q for this target, and we don't want to go
4465                  * about selecting while we handle the busfree and blow
4466                  * it away.
4467                  */
4468                 ahd_outb(ahd, SCSISEQ0, 0);
4469         } else {
4470                 printf("ahd_intr: AWAITING_MSG for an SCB that "
4471                        "does not have a waiting message\n");
4472                 printf("SCSIID = %x, target_mask = %x\n", scb->hscb->scsiid,
4473                        devinfo->target_mask);
4474                 panic("SCB = %d, SCB Control = %x:%x, MSG_OUT = %x "
4475                       "SCB flags = %x", SCB_GET_TAG(scb), scb->hscb->control,
4476                       ahd_inb_scbram(ahd, SCB_CONTROL), ahd_inb(ahd, MSG_OUT),
4477                       scb->flags);
4478         }
4479
4480         /*
4481          * Clear the MK_MESSAGE flag from the SCB so we aren't
4482          * asked to send this message again.
4483          */
4484         ahd_outb(ahd, SCB_CONTROL,
4485                  ahd_inb_scbram(ahd, SCB_CONTROL) & ~MK_MESSAGE);
4486         scb->hscb->control &= ~MK_MESSAGE;
4487         ahd->msgout_index = 0;
4488         ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
4489 }
4490
4491 /*
4492  * Build an appropriate transfer negotiation message for the
4493  * currently active target.
4494  */
4495 static void
4496 ahd_build_transfer_msg(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
4497 {
4498         /*
4499          * We need to initiate transfer negotiations.
4500          * If our current and goal settings are identical,
4501          * we want to renegotiate due to a check condition.
4502          */
4503         struct  ahd_initiator_tinfo *tinfo;
4504         struct  ahd_tmode_tstate *tstate;
4505         int     dowide;
4506         int     dosync;
4507         int     doppr;
4508         u_int   period;
4509         u_int   ppr_options;
4510         u_int   offset;
4511
4512         tinfo = ahd_fetch_transinfo(ahd, devinfo->channel, devinfo->our_scsiid,
4513                                     devinfo->target, &tstate);
4514         /*
4515          * Filter our period based on the current connection.
4516          * If we can't perform DT transfers on this segment (not in LVD
4517          * mode for instance), then our decision to issue a PPR message
4518          * may change.
4519          */
4520         period = tinfo->goal.period;
4521         offset = tinfo->goal.offset;
4522         ppr_options = tinfo->goal.ppr_options;
4523         /* Target initiated PPR is not allowed in the SCSI spec */
4524         if (devinfo->role == ROLE_TARGET)
4525                 ppr_options = 0;
4526         ahd_devlimited_syncrate(ahd, tinfo, &period,
4527                                 &ppr_options, devinfo->role);
4528         dowide = tinfo->curr.width != tinfo->goal.width;
4529         dosync = tinfo->curr.offset != offset || tinfo->curr.period != period;
4530         /*
4531          * Only use PPR if we have options that need it, even if the device
4532          * claims to support it.  There might be an expander in the way
4533          * that doesn't.
4534          */
4535         doppr = ppr_options != 0;
4536
4537         if (!dowide && !dosync && !doppr) {
4538                 dowide = tinfo->goal.width != MSG_EXT_WDTR_BUS_8_BIT;
4539                 dosync = tinfo->goal.offset != 0;
4540         }
4541
4542         if (!dowide && !dosync && !doppr) {
4543                 /*
4544                  * Force async with a WDTR message if we have a wide bus,
4545                  * or just issue an SDTR with a 0 offset.
4546                  */
4547                 if ((ahd->features & AHD_WIDE) != 0)
4548                         dowide = 1;
4549                 else
4550                         dosync = 1;
4551
4552                 if (bootverbose) {
4553                         ahd_print_devinfo(ahd, devinfo);
4554                         printf("Ensuring async\n");
4555                 }
4556         }
4557         /* Target initiated PPR is not allowed in the SCSI spec */
4558         if (devinfo->role == ROLE_TARGET)
4559                 doppr = 0;
4560
4561         /*
4562          * Both the PPR message and SDTR message require the
4563          * goal syncrate to be limited to what the target device
4564          * is capable of handling (based on whether an LVD->SE
4565          * expander is on the bus), so combine these two cases.
4566          * Regardless, guarantee that if we are using WDTR and SDTR
4567          * messages that WDTR comes first.
4568          */
4569         if (doppr || (dosync && !dowide)) {
4570
4571                 offset = tinfo->goal.offset;
4572                 ahd_validate_offset(ahd, tinfo, period, &offset,
4573                                     doppr ? tinfo->goal.width
4574                                           : tinfo->curr.width,
4575                                     devinfo->role);
4576                 if (doppr) {
4577                         ahd_construct_ppr(ahd, devinfo, period, offset,
4578                                           tinfo->goal.width, ppr_options);
4579                 } else {
4580                         ahd_construct_sdtr(ahd, devinfo, period, offset);
4581                 }
4582         } else {
4583                 ahd_construct_wdtr(ahd, devinfo, tinfo->goal.width);
4584         }
4585 }
4586
4587 /*
4588  * Build a synchronous negotiation message in our message
4589  * buffer based on the input parameters.
4590  */
4591 static void
4592 ahd_construct_sdtr(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
4593                    u_int period, u_int offset)
4594 {
4595         if (offset == 0)
4596                 period = AHD_ASYNC_XFER_PERIOD;
4597         ahd->msgout_index += spi_populate_sync_msg(
4598                         ahd->msgout_buf + ahd->msgout_index, period, offset);
4599         ahd->msgout_len += 5;
4600         if (bootverbose) {
4601                 printf("(%s:%c:%d:%d): Sending SDTR period %x, offset %x\n",
4602                        ahd_name(ahd), devinfo->channel, devinfo->target,
4603                        devinfo->lun, period, offset);
4604         }
4605 }
4606
4607 /*
4608  * Build a wide negotiateion message in our message
4609  * buffer based on the input parameters.
4610  */
4611 static void
4612 ahd_construct_wdtr(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
4613                    u_int bus_width)
4614 {
4615         ahd->msgout_index += spi_populate_width_msg(
4616                         ahd->msgout_buf + ahd->msgout_index, bus_width);
4617         ahd->msgout_len += 4;
4618         if (bootverbose) {
4619                 printf("(%s:%c:%d:%d): Sending WDTR %x\n",
4620                        ahd_name(ahd), devinfo->channel, devinfo->target,
4621                        devinfo->lun, bus_width);
4622         }
4623 }
4624
4625 /*
4626  * Build a parallel protocol request message in our message
4627  * buffer based on the input parameters.
4628  */
4629 static void
4630 ahd_construct_ppr(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
4631                   u_int period, u_int offset, u_int bus_width,
4632                   u_int ppr_options)
4633 {
4634         /*
4635          * Always request precompensation from
4636          * the other target if we are running
4637          * at paced syncrates.
4638          */
4639         if (period <= AHD_SYNCRATE_PACED)
4640                 ppr_options |= MSG_EXT_PPR_PCOMP_EN;
4641         if (offset == 0)
4642                 period = AHD_ASYNC_XFER_PERIOD;
4643         ahd->msgout_index += spi_populate_ppr_msg(
4644                         ahd->msgout_buf + ahd->msgout_index, period, offset,
4645                         bus_width, ppr_options);
4646         ahd->msgout_len += 8;
4647         if (bootverbose) {
4648                 printf("(%s:%c:%d:%d): Sending PPR bus_width %x, period %x, "
4649                        "offset %x, ppr_options %x\n", ahd_name(ahd),
4650                        devinfo->channel, devinfo->target, devinfo->lun,
4651                        bus_width, period, offset, ppr_options);
4652         }
4653 }
4654
4655 /*
4656  * Clear any active message state.
4657  */
4658 static void
4659 ahd_clear_msg_state(struct ahd_softc *ahd)
4660 {
4661         ahd_mode_state saved_modes;
4662
4663         saved_modes = ahd_save_modes(ahd);
4664         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
4665         ahd->send_msg_perror = 0;
4666         ahd->msg_flags = MSG_FLAG_NONE;
4667         ahd->msgout_len = 0;
4668         ahd->msgin_index = 0;
4669         ahd->msg_type = MSG_TYPE_NONE;
4670         if ((ahd_inb(ahd, SCSISIGO) & ATNO) != 0) {
4671                 /*
4672                  * The target didn't care to respond to our
4673                  * message request, so clear ATN.
4674                  */
4675                 ahd_outb(ahd, CLRSINT1, CLRATNO);
4676         }
4677         ahd_outb(ahd, MSG_OUT, MSG_NOOP);
4678         ahd_outb(ahd, SEQ_FLAGS2,
4679                  ahd_inb(ahd, SEQ_FLAGS2) & ~TARGET_MSG_PENDING);
4680         ahd_restore_modes(ahd, saved_modes);
4681 }
4682
4683 /*
4684  * Manual message loop handler.
4685  */
4686 static void
4687 ahd_handle_message_phase(struct ahd_softc *ahd)
4688 {
4689         struct  ahd_devinfo devinfo;
4690         u_int   bus_phase;
4691         int     end_session;
4692
4693         ahd_fetch_devinfo(ahd, &devinfo);
4694         end_session = FALSE;
4695         bus_phase = ahd_inb(ahd, LASTPHASE);
4696
4697         if ((ahd_inb(ahd, LQISTAT2) & LQIPHASE_OUTPKT) != 0) {
4698                 printf("LQIRETRY for LQIPHASE_OUTPKT\n");
4699                 ahd_outb(ahd, LQCTL2, LQIRETRY);
4700         }
4701 reswitch:
4702         switch (ahd->msg_type) {
4703         case MSG_TYPE_INITIATOR_MSGOUT:
4704         {
4705                 int lastbyte;
4706                 int phasemis;
4707                 int msgdone;
4708
4709                 if (ahd->msgout_len == 0 && ahd->send_msg_perror == 0)
4710                         panic("HOST_MSG_LOOP interrupt with no active message");
4711
4712 #ifdef AHD_DEBUG
4713                 if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
4714                         ahd_print_devinfo(ahd, &devinfo);
4715                         printf("INITIATOR_MSG_OUT");
4716                 }
4717 #endif
4718                 phasemis = bus_phase != P_MESGOUT;
4719                 if (phasemis) {
4720 #ifdef AHD_DEBUG
4721                         if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
4722                                 printf(" PHASEMIS %s\n",
4723                                        ahd_lookup_phase_entry(bus_phase)
4724                                                              ->phasemsg);
4725                         }
4726 #endif
4727                         if (bus_phase == P_MESGIN) {
4728                                 /*
4729                                  * Change gears and see if
4730                                  * this messages is of interest to
4731                                  * us or should be passed back to
4732                                  * the sequencer.
4733                                  */
4734                                 ahd_outb(ahd, CLRSINT1, CLRATNO);
4735                                 ahd->send_msg_perror = 0;
4736                                 ahd->msg_type = MSG_TYPE_INITIATOR_MSGIN;
4737                                 ahd->msgin_index = 0;
4738                                 goto reswitch;
4739                         }
4740                         end_session = TRUE;
4741                         break;
4742                 }
4743
4744                 if (ahd->send_msg_perror) {
4745                         ahd_outb(ahd, CLRSINT1, CLRATNO);
4746                         ahd_outb(ahd, CLRSINT1, CLRREQINIT);
4747 #ifdef AHD_DEBUG
4748                         if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
4749                                 printf(" byte 0x%x\n", ahd->send_msg_perror);
4750 #endif
4751                         /*
4752                          * If we are notifying the target of a CRC error
4753                          * during packetized operations, the target is
4754                          * within its rights to acknowledge our message
4755                          * with a busfree.
4756                          */
4757                         if ((ahd->msg_flags & MSG_FLAG_PACKETIZED) != 0
4758                          && ahd->send_msg_perror == MSG_INITIATOR_DET_ERR)
4759                                 ahd->msg_flags |= MSG_FLAG_EXPECT_IDE_BUSFREE;
4760
4761                         ahd_outb(ahd, RETURN_2, ahd->send_msg_perror);
4762                         ahd_outb(ahd, RETURN_1, CONT_MSG_LOOP_WRITE);
4763                         break;
4764                 }
4765
4766                 msgdone = ahd->msgout_index == ahd->msgout_len;
4767                 if (msgdone) {
4768                         /*
4769                          * The target has requested a retry.
4770                          * Re-assert ATN, reset our message index to
4771                          * 0, and try again.
4772                          */
4773                         ahd->msgout_index = 0;
4774                         ahd_assert_atn(ahd);
4775                 }
4776
4777                 lastbyte = ahd->msgout_index == (ahd->msgout_len - 1);
4778                 if (lastbyte) {
4779                         /* Last byte is signified by dropping ATN */
4780                         ahd_outb(ahd, CLRSINT1, CLRATNO);
4781                 }
4782
4783                 /*
4784                  * Clear our interrupt status and present
4785                  * the next byte on the bus.
4786                  */
4787                 ahd_outb(ahd, CLRSINT1, CLRREQINIT);
4788 #ifdef AHD_DEBUG
4789                 if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
4790                         printf(" byte 0x%x\n",
4791                                ahd->msgout_buf[ahd->msgout_index]);
4792 #endif
4793                 ahd_outb(ahd, RETURN_2, ahd->msgout_buf[ahd->msgout_index++]);
4794                 ahd_outb(ahd, RETURN_1, CONT_MSG_LOOP_WRITE);
4795                 break;
4796         }
4797         case MSG_TYPE_INITIATOR_MSGIN:
4798         {
4799                 int phasemis;
4800                 int message_done;
4801
4802 #ifdef AHD_DEBUG
4803                 if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
4804                         ahd_print_devinfo(ahd, &devinfo);
4805                         printf("INITIATOR_MSG_IN");
4806                 }
4807 #endif
4808                 phasemis = bus_phase != P_MESGIN;
4809                 if (phasemis) {
4810 #ifdef AHD_DEBUG
4811                         if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
4812                                 printf(" PHASEMIS %s\n",
4813                                        ahd_lookup_phase_entry(bus_phase)
4814                                                              ->phasemsg);
4815                         }
4816 #endif
4817                         ahd->msgin_index = 0;
4818                         if (bus_phase == P_MESGOUT
4819                          && (ahd->send_msg_perror != 0
4820                           || (ahd->msgout_len != 0
4821                            && ahd->msgout_index == 0))) {
4822                                 ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
4823                                 goto reswitch;
4824                         }
4825                         end_session = TRUE;
4826                         break;
4827                 }
4828
4829                 /* Pull the byte in without acking it */
4830                 ahd->msgin_buf[ahd->msgin_index] = ahd_inb(ahd, SCSIBUS);
4831 #ifdef AHD_DEBUG
4832                 if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
4833                         printf(" byte 0x%x\n",
4834                                ahd->msgin_buf[ahd->msgin_index]);
4835 #endif
4836
4837                 message_done = ahd_parse_msg(ahd, &devinfo);
4838
4839                 if (message_done) {
4840                         /*
4841                          * Clear our incoming message buffer in case there
4842                          * is another message following this one.
4843                          */
4844                         ahd->msgin_index = 0;
4845
4846                         /*
4847                          * If this message illicited a response,
4848                          * assert ATN so the target takes us to the
4849                          * message out phase.
4850                          */
4851                         if (ahd->msgout_len != 0) {
4852 #ifdef AHD_DEBUG
4853                                 if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
4854                                         ahd_print_devinfo(ahd, &devinfo);
4855                                         printf("Asserting ATN for response\n");
4856                                 }
4857 #endif
4858                                 ahd_assert_atn(ahd);
4859                         }
4860                 } else 
4861                         ahd->msgin_index++;
4862
4863                 if (message_done == MSGLOOP_TERMINATED) {
4864                         end_session = TRUE;
4865                 } else {
4866                         /* Ack the byte */
4867                         ahd_outb(ahd, CLRSINT1, CLRREQINIT);
4868                         ahd_outb(ahd, RETURN_1, CONT_MSG_LOOP_READ);
4869                 }
4870                 break;
4871         }
4872         case MSG_TYPE_TARGET_MSGIN:
4873         {
4874                 int msgdone;
4875                 int msgout_request;
4876
4877                 /*
4878                  * By default, the message loop will continue.
4879                  */
4880                 ahd_outb(ahd, RETURN_1, CONT_MSG_LOOP_TARG);
4881
4882                 if (ahd->msgout_len == 0)
4883                         panic("Target MSGIN with no active message");
4884
4885                 /*
4886                  * If we interrupted a mesgout session, the initiator
4887                  * will not know this until our first REQ.  So, we
4888                  * only honor mesgout requests after we've sent our
4889                  * first byte.
4890                  */
4891                 if ((ahd_inb(ahd, SCSISIGI) & ATNI) != 0
4892                  && ahd->msgout_index > 0)
4893                         msgout_request = TRUE;
4894                 else
4895                         msgout_request = FALSE;
4896
4897                 if (msgout_request) {
4898
4899                         /*
4900                          * Change gears and see if
4901                          * this messages is of interest to
4902                          * us or should be passed back to
4903                          * the sequencer.
4904                          */
4905                         ahd->msg_type = MSG_TYPE_TARGET_MSGOUT;
4906                         ahd_outb(ahd, SCSISIGO, P_MESGOUT | BSYO);
4907                         ahd->msgin_index = 0;
4908                         /* Dummy read to REQ for first byte */
4909                         ahd_inb(ahd, SCSIDAT);
4910                         ahd_outb(ahd, SXFRCTL0,
4911                                  ahd_inb(ahd, SXFRCTL0) | SPIOEN);
4912                         break;
4913                 }
4914
4915                 msgdone = ahd->msgout_index == ahd->msgout_len;
4916                 if (msgdone) {
4917                         ahd_outb(ahd, SXFRCTL0,
4918                                  ahd_inb(ahd, SXFRCTL0) & ~SPIOEN);
4919                         end_session = TRUE;
4920                         break;
4921                 }
4922
4923                 /*
4924                  * Present the next byte on the bus.
4925                  */
4926                 ahd_outb(ahd, SXFRCTL0, ahd_inb(ahd, SXFRCTL0) | SPIOEN);
4927                 ahd_outb(ahd, SCSIDAT, ahd->msgout_buf[ahd->msgout_index++]);
4928                 break;
4929         }
4930         case MSG_TYPE_TARGET_MSGOUT:
4931         {
4932                 int lastbyte;
4933                 int msgdone;
4934
4935                 /*
4936                  * By default, the message loop will continue.
4937                  */
4938                 ahd_outb(ahd, RETURN_1, CONT_MSG_LOOP_TARG);
4939
4940                 /*
4941                  * The initiator signals that this is
4942                  * the last byte by dropping ATN.
4943                  */
4944                 lastbyte = (ahd_inb(ahd, SCSISIGI) & ATNI) == 0;
4945
4946                 /*
4947                  * Read the latched byte, but turn off SPIOEN first
4948                  * so that we don't inadvertently cause a REQ for the
4949                  * next byte.
4950                  */
4951                 ahd_outb(ahd, SXFRCTL0, ahd_inb(ahd, SXFRCTL0) & ~SPIOEN);
4952                 ahd->msgin_buf[ahd->msgin_index] = ahd_inb(ahd, SCSIDAT);
4953                 msgdone = ahd_parse_msg(ahd, &devinfo);
4954                 if (msgdone == MSGLOOP_TERMINATED) {
4955                         /*
4956                          * The message is *really* done in that it caused
4957                          * us to go to bus free.  The sequencer has already
4958                          * been reset at this point, so pull the ejection
4959                          * handle.
4960                          */
4961                         return;
4962                 }
4963                 
4964                 ahd->msgin_index++;
4965
4966                 /*
4967                  * XXX Read spec about initiator dropping ATN too soon
4968                  *     and use msgdone to detect it.
4969                  */
4970                 if (msgdone == MSGLOOP_MSGCOMPLETE) {
4971                         ahd->msgin_index = 0;
4972
4973                         /*
4974                          * If this message illicited a response, transition
4975                          * to the Message in phase and send it.
4976                          */
4977                         if (ahd->msgout_len != 0) {
4978                                 ahd_outb(ahd, SCSISIGO, P_MESGIN | BSYO);
4979                                 ahd_outb(ahd, SXFRCTL0,
4980                                          ahd_inb(ahd, SXFRCTL0) | SPIOEN);
4981                                 ahd->msg_type = MSG_TYPE_TARGET_MSGIN;
4982                                 ahd->msgin_index = 0;
4983                                 break;
4984                         }
4985                 }
4986
4987                 if (lastbyte)
4988                         end_session = TRUE;
4989                 else {
4990                         /* Ask for the next byte. */
4991                         ahd_outb(ahd, SXFRCTL0,
4992                                  ahd_inb(ahd, SXFRCTL0) | SPIOEN);
4993                 }
4994
4995                 break;
4996         }
4997         default:
4998                 panic("Unknown REQINIT message type");
4999         }
5000
5001         if (end_session) {
5002                 if ((ahd->msg_flags & MSG_FLAG_PACKETIZED) != 0) {
5003                         printf("%s: Returning to Idle Loop\n",
5004                                ahd_name(ahd));
5005                         ahd_clear_msg_state(ahd);
5006
5007                         /*
5008                          * Perform the equivalent of a clear_target_state.
5009                          */
5010                         ahd_outb(ahd, LASTPHASE, P_BUSFREE);
5011                         ahd_outb(ahd, SEQ_FLAGS, NOT_IDENTIFIED|NO_CDB_SENT);
5012                         ahd_outb(ahd, SEQCTL0, FASTMODE|SEQRESET);
5013                 } else {
5014                         ahd_clear_msg_state(ahd);
5015                         ahd_outb(ahd, RETURN_1, EXIT_MSG_LOOP);
5016                 }
5017         }
5018 }
5019
5020 /*
5021  * See if we sent a particular extended message to the target.
5022  * If "full" is true, return true only if the target saw the full
5023  * message.  If "full" is false, return true if the target saw at
5024  * least the first byte of the message.
5025  */
5026 static int
5027 ahd_sent_msg(struct ahd_softc *ahd, ahd_msgtype type, u_int msgval, int full)
5028 {
5029         int found;
5030         u_int index;
5031
5032         found = FALSE;
5033         index = 0;
5034
5035         while (index < ahd->msgout_len) {
5036                 if (ahd->msgout_buf[index] == MSG_EXTENDED) {
5037                         u_int end_index;
5038
5039                         end_index = index + 1 + ahd->msgout_buf[index + 1];
5040                         if (ahd->msgout_buf[index+2] == msgval
5041                          && type == AHDMSG_EXT) {
5042
5043                                 if (full) {
5044                                         if (ahd->msgout_index > end_index)
5045                                                 found = TRUE;
5046                                 } else if (ahd->msgout_index > index)
5047                                         found = TRUE;
5048                         }
5049                         index = end_index;
5050                 } else if (ahd->msgout_buf[index] >= MSG_SIMPLE_TASK
5051                         && ahd->msgout_buf[index] <= MSG_IGN_WIDE_RESIDUE) {
5052
5053                         /* Skip tag type and tag id or residue param*/
5054                         index += 2;
5055                 } else {
5056                         /* Single byte message */
5057                         if (type == AHDMSG_1B
5058                          && ahd->msgout_index > index
5059                          && (ahd->msgout_buf[index] == msgval
5060                           || ((ahd->msgout_buf[index] & MSG_IDENTIFYFLAG) != 0
5061                            && msgval == MSG_IDENTIFYFLAG)))
5062                                 found = TRUE;
5063                         index++;
5064                 }
5065
5066                 if (found)
5067                         break;
5068         }
5069         return (found);
5070 }
5071
5072 /*
5073  * Wait for a complete incoming message, parse it, and respond accordingly.
5074  */
5075 static int
5076 ahd_parse_msg(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
5077 {
5078         struct  ahd_initiator_tinfo *tinfo;
5079         struct  ahd_tmode_tstate *tstate;
5080         int     reject;
5081         int     done;
5082         int     response;
5083
5084         done = MSGLOOP_IN_PROG;
5085         response = FALSE;
5086         reject = FALSE;
5087         tinfo = ahd_fetch_transinfo(ahd, devinfo->channel, devinfo->our_scsiid,
5088                                     devinfo->target, &tstate);
5089
5090         /*
5091          * Parse as much of the message as is available,
5092          * rejecting it if we don't support it.  When
5093          * the entire message is available and has been
5094          * handled, return MSGLOOP_MSGCOMPLETE, indicating
5095          * that we have parsed an entire message.
5096          *
5097          * In the case of extended messages, we accept the length
5098          * byte outright and perform more checking once we know the
5099          * extended message type.
5100          */
5101         switch (ahd->msgin_buf[0]) {
5102         case MSG_DISCONNECT:
5103         case MSG_SAVEDATAPOINTER:
5104         case MSG_CMDCOMPLETE:
5105         case MSG_RESTOREPOINTERS:
5106         case MSG_IGN_WIDE_RESIDUE:
5107                 /*
5108                  * End our message loop as these are messages
5109                  * the sequencer handles on its own.
5110                  */
5111                 done = MSGLOOP_TERMINATED;
5112                 break;
5113         case MSG_MESSAGE_REJECT:
5114                 response = ahd_handle_msg_reject(ahd, devinfo);
5115                 /* FALLTHROUGH */
5116         case MSG_NOOP:
5117                 done = MSGLOOP_MSGCOMPLETE;
5118                 break;
5119         case MSG_EXTENDED:
5120         {
5121                 /* Wait for enough of the message to begin validation */
5122                 if (ahd->msgin_index < 2)
5123                         break;
5124                 switch (ahd->msgin_buf[2]) {
5125                 case MSG_EXT_SDTR:
5126                 {
5127                         u_int    period;
5128                         u_int    ppr_options;
5129                         u_int    offset;
5130                         u_int    saved_offset;
5131                         
5132                         if (ahd->msgin_buf[1] != MSG_EXT_SDTR_LEN) {
5133                                 reject = TRUE;
5134                                 break;
5135                         }
5136
5137                         /*
5138                          * Wait until we have both args before validating
5139                          * and acting on this message.
5140                          *
5141                          * Add one to MSG_EXT_SDTR_LEN to account for
5142                          * the extended message preamble.
5143                          */
5144                         if (ahd->msgin_index < (MSG_EXT_SDTR_LEN + 1))
5145                                 break;
5146
5147                         period = ahd->msgin_buf[3];
5148                         ppr_options = 0;
5149                         saved_offset = offset = ahd->msgin_buf[4];
5150                         ahd_devlimited_syncrate(ahd, tinfo, &period,
5151                                                 &ppr_options, devinfo->role);
5152                         ahd_validate_offset(ahd, tinfo, period, &offset,
5153                                             tinfo->curr.width, devinfo->role);
5154                         if (bootverbose) {
5155                                 printf("(%s:%c:%d:%d): Received "
5156                                        "SDTR period %x, offset %x\n\t"
5157                                        "Filtered to period %x, offset %x\n",
5158                                        ahd_name(ahd), devinfo->channel,
5159                                        devinfo->target, devinfo->lun,
5160                                        ahd->msgin_buf[3], saved_offset,
5161                                        period, offset);
5162                         }
5163                         ahd_set_syncrate(ahd, devinfo, period,
5164                                          offset, ppr_options,
5165                                          AHD_TRANS_ACTIVE|AHD_TRANS_GOAL,
5166                                          /*paused*/TRUE);
5167
5168                         /*
5169                          * See if we initiated Sync Negotiation
5170                          * and didn't have to fall down to async
5171                          * transfers.
5172                          */
5173                         if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_SDTR, TRUE)) {
5174                                 /* We started it */
5175                                 if (saved_offset != offset) {
5176                                         /* Went too low - force async */
5177                                         reject = TRUE;
5178                                 }
5179                         } else {
5180                                 /*
5181                                  * Send our own SDTR in reply
5182                                  */
5183                                 if (bootverbose
5184                                  && devinfo->role == ROLE_INITIATOR) {
5185                                         printf("(%s:%c:%d:%d): Target "
5186                                                "Initiated SDTR\n",
5187                                                ahd_name(ahd), devinfo->channel,
5188                                                devinfo->target, devinfo->lun);
5189                                 }
5190                                 ahd->msgout_index = 0;
5191                                 ahd->msgout_len = 0;
5192                                 ahd_construct_sdtr(ahd, devinfo,
5193                                                    period, offset);
5194                                 ahd->msgout_index = 0;
5195                                 response = TRUE;
5196                         }
5197                         done = MSGLOOP_MSGCOMPLETE;
5198                         break;
5199                 }
5200                 case MSG_EXT_WDTR:
5201                 {
5202                         u_int bus_width;
5203                         u_int saved_width;
5204                         u_int sending_reply;
5205
5206                         sending_reply = FALSE;
5207                         if (ahd->msgin_buf[1] != MSG_EXT_WDTR_LEN) {
5208                                 reject = TRUE;
5209                                 break;
5210                         }
5211
5212                         /*
5213                          * Wait until we have our arg before validating
5214                          * and acting on this message.
5215                          *
5216                          * Add one to MSG_EXT_WDTR_LEN to account for
5217                          * the extended message preamble.
5218                          */
5219                         if (ahd->msgin_index < (MSG_EXT_WDTR_LEN + 1))
5220                                 break;
5221
5222                         bus_width = ahd->msgin_buf[3];
5223                         saved_width = bus_width;
5224                         ahd_validate_width(ahd, tinfo, &bus_width,
5225                                            devinfo->role);
5226                         if (bootverbose) {
5227                                 printf("(%s:%c:%d:%d): Received WDTR "
5228                                        "%x filtered to %x\n",
5229                                        ahd_name(ahd), devinfo->channel,
5230                                        devinfo->target, devinfo->lun,
5231                                        saved_width, bus_width);
5232                         }
5233
5234                         if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_WDTR, TRUE)) {
5235                                 /*
5236                                  * Don't send a WDTR back to the
5237                                  * target, since we asked first.
5238                                  * If the width went higher than our
5239                                  * request, reject it.
5240                                  */
5241                                 if (saved_width > bus_width) {
5242                                         reject = TRUE;
5243                                         printf("(%s:%c:%d:%d): requested %dBit "
5244                                                "transfers.  Rejecting...\n",
5245                                                ahd_name(ahd), devinfo->channel,
5246                                                devinfo->target, devinfo->lun,
5247                                                8 * (0x01 << bus_width));
5248                                         bus_width = 0;
5249                                 }
5250                         } else {
5251                                 /*
5252                                  * Send our own WDTR in reply
5253                                  */
5254                                 if (bootverbose
5255                                  && devinfo->role == ROLE_INITIATOR) {
5256                                         printf("(%s:%c:%d:%d): Target "
5257                                                "Initiated WDTR\n",
5258                                                ahd_name(ahd), devinfo->channel,
5259                                                devinfo->target, devinfo->lun);
5260                                 }
5261                                 ahd->msgout_index = 0;
5262                                 ahd->msgout_len = 0;
5263                                 ahd_construct_wdtr(ahd, devinfo, bus_width);
5264                                 ahd->msgout_index = 0;
5265                                 response = TRUE;
5266                                 sending_reply = TRUE;
5267                         }
5268                         /*
5269                          * After a wide message, we are async, but
5270                          * some devices don't seem to honor this portion
5271                          * of the spec.  Force a renegotiation of the
5272                          * sync component of our transfer agreement even
5273                          * if our goal is async.  By updating our width
5274                          * after forcing the negotiation, we avoid
5275                          * renegotiating for width.
5276                          */
5277                         ahd_update_neg_request(ahd, devinfo, tstate,
5278                                                tinfo, AHD_NEG_ALWAYS);
5279                         ahd_set_width(ahd, devinfo, bus_width,
5280                                       AHD_TRANS_ACTIVE|AHD_TRANS_GOAL,
5281                                       /*paused*/TRUE);
5282                         if (sending_reply == FALSE && reject == FALSE) {
5283
5284                                 /*
5285                                  * We will always have an SDTR to send.
5286                                  */
5287                                 ahd->msgout_index = 0;
5288                                 ahd->msgout_len = 0;
5289                                 ahd_build_transfer_msg(ahd, devinfo);
5290                                 ahd->msgout_index = 0;
5291                                 response = TRUE;
5292                         }
5293                         done = MSGLOOP_MSGCOMPLETE;
5294                         break;
5295                 }
5296                 case MSG_EXT_PPR:
5297                 {
5298                         u_int   period;
5299                         u_int   offset;
5300                         u_int   bus_width;
5301                         u_int   ppr_options;
5302                         u_int   saved_width;
5303                         u_int   saved_offset;
5304                         u_int   saved_ppr_options;
5305
5306                         if (ahd->msgin_buf[1] != MSG_EXT_PPR_LEN) {
5307                                 reject = TRUE;
5308                                 break;
5309                         }
5310
5311                         /*
5312                          * Wait until we have all args before validating
5313                          * and acting on this message.
5314                          *
5315                          * Add one to MSG_EXT_PPR_LEN to account for
5316                          * the extended message preamble.
5317                          */
5318                         if (ahd->msgin_index < (MSG_EXT_PPR_LEN + 1))
5319                                 break;
5320
5321                         period = ahd->msgin_buf[3];
5322                         offset = ahd->msgin_buf[5];
5323                         bus_width = ahd->msgin_buf[6];
5324                         saved_width = bus_width;
5325                         ppr_options = ahd->msgin_buf[7];
5326                         /*
5327                          * According to the spec, a DT only
5328                          * period factor with no DT option
5329                          * set implies async.
5330                          */
5331                         if ((ppr_options & MSG_EXT_PPR_DT_REQ) == 0
5332                          && period <= 9)
5333                                 offset = 0;
5334                         saved_ppr_options = ppr_options;
5335                         saved_offset = offset;
5336
5337                         /*
5338                          * Transfer options are only available if we
5339                          * are negotiating wide.
5340                          */
5341                         if (bus_width == 0)
5342                                 ppr_options &= MSG_EXT_PPR_QAS_REQ;
5343
5344                         ahd_validate_width(ahd, tinfo, &bus_width,
5345                                            devinfo->role);
5346                         ahd_devlimited_syncrate(ahd, tinfo, &period,
5347                                                 &ppr_options, devinfo->role);
5348                         ahd_validate_offset(ahd, tinfo, period, &offset,
5349                                             bus_width, devinfo->role);
5350
5351                         if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_PPR, TRUE)) {
5352                                 /*
5353                                  * If we are unable to do any of the
5354                                  * requested options (we went too low),
5355                                  * then we'll have to reject the message.
5356                                  */
5357                                 if (saved_width > bus_width
5358                                  || saved_offset != offset
5359                                  || saved_ppr_options != ppr_options) {
5360                                         reject = TRUE;
5361                                         period = 0;
5362                                         offset = 0;
5363                                         bus_width = 0;
5364                                         ppr_options = 0;
5365                                 }
5366                         } else {
5367                                 if (devinfo->role != ROLE_TARGET)
5368                                         printf("(%s:%c:%d:%d): Target "
5369                                                "Initiated PPR\n",
5370                                                ahd_name(ahd), devinfo->channel,
5371                                                devinfo->target, devinfo->lun);
5372                                 else
5373                                         printf("(%s:%c:%d:%d): Initiator "
5374                                                "Initiated PPR\n",
5375                                                ahd_name(ahd), devinfo->channel,
5376                                                devinfo->target, devinfo->lun);
5377                                 ahd->msgout_index = 0;
5378                                 ahd->msgout_len = 0;
5379                                 ahd_construct_ppr(ahd, devinfo, period, offset,
5380                                                   bus_width, ppr_options);
5381                                 ahd->msgout_index = 0;
5382                                 response = TRUE;
5383                         }
5384                         if (bootverbose) {
5385                                 printf("(%s:%c:%d:%d): Received PPR width %x, "
5386                                        "period %x, offset %x,options %x\n"
5387                                        "\tFiltered to width %x, period %x, "
5388                                        "offset %x, options %x\n",
5389                                        ahd_name(ahd), devinfo->channel,
5390                                        devinfo->target, devinfo->lun,
5391                                        saved_width, ahd->msgin_buf[3],
5392                                        saved_offset, saved_ppr_options,
5393                                        bus_width, period, offset, ppr_options);
5394                         }
5395                         ahd_set_width(ahd, devinfo, bus_width,
5396                                       AHD_TRANS_ACTIVE|AHD_TRANS_GOAL,
5397                                       /*paused*/TRUE);
5398                         ahd_set_syncrate(ahd, devinfo, period,
5399                                          offset, ppr_options,
5400                                          AHD_TRANS_ACTIVE|AHD_TRANS_GOAL,
5401                                          /*paused*/TRUE);
5402
5403                         done = MSGLOOP_MSGCOMPLETE;
5404                         break;
5405                 }
5406                 default:
5407                         /* Unknown extended message.  Reject it. */
5408                         reject = TRUE;
5409                         break;
5410                 }
5411                 break;
5412         }
5413 #ifdef AHD_TARGET_MODE
5414         case MSG_BUS_DEV_RESET:
5415                 ahd_handle_devreset(ahd, devinfo, CAM_LUN_WILDCARD,
5416                                     CAM_BDR_SENT,
5417                                     "Bus Device Reset Received",
5418                                     /*verbose_level*/0);
5419                 ahd_restart(ahd);
5420                 done = MSGLOOP_TERMINATED;
5421                 break;
5422         case MSG_ABORT_TAG:
5423         case MSG_ABORT:
5424         case MSG_CLEAR_QUEUE:
5425         {
5426                 int tag;
5427
5428                 /* Target mode messages */
5429                 if (devinfo->role != ROLE_TARGET) {
5430                         reject = TRUE;
5431                         break;
5432                 }
5433                 tag = SCB_LIST_NULL;
5434                 if (ahd->msgin_buf[0] == MSG_ABORT_TAG)
5435                         tag = ahd_inb(ahd, INITIATOR_TAG);
5436                 ahd_abort_scbs(ahd, devinfo->target, devinfo->channel,
5437                                devinfo->lun, tag, ROLE_TARGET,
5438                                CAM_REQ_ABORTED);
5439
5440                 tstate = ahd->enabled_targets[devinfo->our_scsiid];
5441                 if (tstate != NULL) {
5442                         struct ahd_tmode_lstate* lstate;
5443
5444                         lstate = tstate->enabled_luns[devinfo->lun];
5445                         if (lstate != NULL) {
5446                                 ahd_queue_lstate_event(ahd, lstate,
5447                                                        devinfo->our_scsiid,
5448                                                        ahd->msgin_buf[0],
5449                                                        /*arg*/tag);
5450                                 ahd_send_lstate_events(ahd, lstate);
5451                         }
5452                 }
5453                 ahd_restart(ahd);
5454                 done = MSGLOOP_TERMINATED;
5455                 break;
5456         }
5457 #endif
5458         case MSG_QAS_REQUEST:
5459 #ifdef AHD_DEBUG
5460                 if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
5461                         printf("%s: QAS request.  SCSISIGI == 0x%x\n",
5462                                ahd_name(ahd), ahd_inb(ahd, SCSISIGI));
5463 #endif
5464                 ahd->msg_flags |= MSG_FLAG_EXPECT_QASREJ_BUSFREE;
5465                 /* FALLTHROUGH */
5466         case MSG_TERM_IO_PROC:
5467         default:
5468                 reject = TRUE;
5469                 break;
5470         }
5471
5472         if (reject) {
5473                 /*
5474                  * Setup to reject the message.
5475                  */
5476                 ahd->msgout_index = 0;
5477                 ahd->msgout_len = 1;
5478                 ahd->msgout_buf[0] = MSG_MESSAGE_REJECT;
5479                 done = MSGLOOP_MSGCOMPLETE;
5480                 response = TRUE;
5481         }
5482
5483         if (done != MSGLOOP_IN_PROG && !response)
5484                 /* Clear the outgoing message buffer */
5485                 ahd->msgout_len = 0;
5486
5487         return (done);
5488 }
5489
5490 /*
5491  * Process a message reject message.
5492  */
5493 static int
5494 ahd_handle_msg_reject(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
5495 {
5496         /*
5497          * What we care about here is if we had an
5498          * outstanding SDTR or WDTR message for this
5499          * target.  If we did, this is a signal that
5500          * the target is refusing negotiation.
5501          */
5502         struct scb *scb;
5503         struct ahd_initiator_tinfo *tinfo;
5504         struct ahd_tmode_tstate *tstate;
5505         u_int scb_index;
5506         u_int last_msg;
5507         int   response = 0;
5508
5509         scb_index = ahd_get_scbptr(ahd);
5510         scb = ahd_lookup_scb(ahd, scb_index);
5511         tinfo = ahd_fetch_transinfo(ahd, devinfo->channel,
5512                                     devinfo->our_scsiid,
5513                                     devinfo->target, &tstate);
5514         /* Might be necessary */
5515         last_msg = ahd_inb(ahd, LAST_MSG);
5516
5517         if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_PPR, /*full*/FALSE)) {
5518                 if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_PPR, /*full*/TRUE)
5519                  && tinfo->goal.period <= AHD_SYNCRATE_PACED) {
5520                         /*
5521                          * Target may not like our SPI-4 PPR Options.
5522                          * Attempt to negotiate 80MHz which will turn
5523                          * off these options.
5524                          */
5525                         if (bootverbose) {
5526                                 printf("(%s:%c:%d:%d): PPR Rejected. "
5527                                        "Trying simple U160 PPR\n",
5528                                        ahd_name(ahd), devinfo->channel,
5529                                        devinfo->target, devinfo->lun);
5530                         }
5531                         tinfo->goal.period = AHD_SYNCRATE_DT;
5532                         tinfo->goal.ppr_options &= MSG_EXT_PPR_IU_REQ
5533                                                 |  MSG_EXT_PPR_QAS_REQ
5534                                                 |  MSG_EXT_PPR_DT_REQ;
5535                 } else {
5536                         /*
5537                          * Target does not support the PPR message.
5538                          * Attempt to negotiate SPI-2 style.
5539                          */
5540                         if (bootverbose) {
5541                                 printf("(%s:%c:%d:%d): PPR Rejected. "
5542                                        "Trying WDTR/SDTR\n",
5543                                        ahd_name(ahd), devinfo->channel,
5544                                        devinfo->target, devinfo->lun);
5545                         }
5546                         tinfo->goal.ppr_options = 0;
5547                         tinfo->curr.transport_version = 2;
5548                         tinfo->goal.transport_version = 2;
5549                 }
5550                 ahd->msgout_index = 0;
5551                 ahd->msgout_len = 0;
5552                 ahd_build_transfer_msg(ahd, devinfo);
5553                 ahd->msgout_index = 0;
5554                 response = 1;
5555         } else if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_WDTR, /*full*/FALSE)) {
5556
5557                 /* note 8bit xfers */
5558                 printf("(%s:%c:%d:%d): refuses WIDE negotiation.  Using "
5559                        "8bit transfers\n", ahd_name(ahd),
5560                        devinfo->channel, devinfo->target, devinfo->lun);
5561                 ahd_set_width(ahd, devinfo, MSG_EXT_WDTR_BUS_8_BIT,
5562                               AHD_TRANS_ACTIVE|AHD_TRANS_GOAL,
5563                               /*paused*/TRUE);
5564                 /*
5565                  * No need to clear the sync rate.  If the target
5566                  * did not accept the command, our syncrate is
5567                  * unaffected.  If the target started the negotiation,
5568                  * but rejected our response, we already cleared the
5569                  * sync rate before sending our WDTR.
5570                  */
5571                 if (tinfo->goal.offset != tinfo->curr.offset) {
5572
5573                         /* Start the sync negotiation */
5574                         ahd->msgout_index = 0;
5575                         ahd->msgout_len = 0;
5576                         ahd_build_transfer_msg(ahd, devinfo);
5577                         ahd->msgout_index = 0;
5578                         response = 1;
5579                 }
5580         } else if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_SDTR, /*full*/FALSE)) {
5581                 /* note asynch xfers and clear flag */
5582                 ahd_set_syncrate(ahd, devinfo, /*period*/0,
5583                                  /*offset*/0, /*ppr_options*/0,
5584                                  AHD_TRANS_ACTIVE|AHD_TRANS_GOAL,
5585                                  /*paused*/TRUE);
5586                 printf("(%s:%c:%d:%d): refuses synchronous negotiation. "
5587                        "Using asynchronous transfers\n",
5588                        ahd_name(ahd), devinfo->channel,
5589                        devinfo->target, devinfo->lun);
5590         } else if ((scb->hscb->control & MSG_SIMPLE_TASK) != 0) {
5591                 int tag_type;
5592                 int mask;
5593
5594                 tag_type = (scb->hscb->control & MSG_SIMPLE_TASK);
5595
5596                 if (tag_type == MSG_SIMPLE_TASK) {
5597                         printf("(%s:%c:%d:%d): refuses tagged commands.  "
5598                                "Performing non-tagged I/O\n", ahd_name(ahd),
5599                                devinfo->channel, devinfo->target, devinfo->lun);
5600                         ahd_set_tags(ahd, scb->io_ctx, devinfo, AHD_QUEUE_NONE);
5601                         mask = ~0x23;
5602                 } else {
5603                         printf("(%s:%c:%d:%d): refuses %s tagged commands.  "
5604                                "Performing simple queue tagged I/O only\n",
5605                                ahd_name(ahd), devinfo->channel, devinfo->target,
5606                                devinfo->lun, tag_type == MSG_ORDERED_TASK
5607                                ? "ordered" : "head of queue");
5608                         ahd_set_tags(ahd, scb->io_ctx, devinfo, AHD_QUEUE_BASIC);
5609                         mask = ~0x03;
5610                 }
5611
5612                 /*
5613                  * Resend the identify for this CCB as the target
5614                  * may believe that the selection is invalid otherwise.
5615                  */
5616                 ahd_outb(ahd, SCB_CONTROL,
5617                          ahd_inb_scbram(ahd, SCB_CONTROL) & mask);
5618                 scb->hscb->control &= mask;
5619                 ahd_set_transaction_tag(scb, /*enabled*/FALSE,
5620                                         /*type*/MSG_SIMPLE_TASK);
5621                 ahd_outb(ahd, MSG_OUT, MSG_IDENTIFYFLAG);
5622                 ahd_assert_atn(ahd);
5623                 ahd_busy_tcl(ahd, BUILD_TCL(scb->hscb->scsiid, devinfo->lun),
5624                              SCB_GET_TAG(scb));
5625
5626                 /*
5627                  * Requeue all tagged commands for this target
5628                  * currently in our posession so they can be
5629                  * converted to untagged commands.
5630                  */
5631                 ahd_search_qinfifo(ahd, SCB_GET_TARGET(ahd, scb),
5632                                    SCB_GET_CHANNEL(ahd, scb),
5633                                    SCB_GET_LUN(scb), /*tag*/SCB_LIST_NULL,
5634                                    ROLE_INITIATOR, CAM_REQUEUE_REQ,
5635                                    SEARCH_COMPLETE);
5636         } else if (ahd_sent_msg(ahd, AHDMSG_1B, MSG_IDENTIFYFLAG, TRUE)) {
5637                 /*
5638                  * Most likely the device believes that we had
5639                  * previously negotiated packetized.
5640                  */
5641                 ahd->msg_flags |= MSG_FLAG_EXPECT_PPR_BUSFREE
5642                                |  MSG_FLAG_IU_REQ_CHANGED;
5643
5644                 ahd_force_renegotiation(ahd, devinfo);
5645                 ahd->msgout_index = 0;
5646                 ahd->msgout_len = 0;
5647                 ahd_build_transfer_msg(ahd, devinfo);
5648                 ahd->msgout_index = 0;
5649                 response = 1;
5650         } else {
5651                 /*
5652                  * Otherwise, we ignore it.
5653                  */
5654                 printf("%s:%c:%d: Message reject for %x -- ignored\n",
5655                        ahd_name(ahd), devinfo->channel, devinfo->target,
5656                        last_msg);
5657         }
5658         return (response);
5659 }
5660
5661 /*
5662  * Process an ingnore wide residue message.
5663  */
5664 static void
5665 ahd_handle_ign_wide_residue(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
5666 {
5667         u_int scb_index;
5668         struct scb *scb;
5669
5670         scb_index = ahd_get_scbptr(ahd);
5671         scb = ahd_lookup_scb(ahd, scb_index);
5672         /*
5673          * XXX Actually check data direction in the sequencer?
5674          * Perhaps add datadir to some spare bits in the hscb?
5675          */
5676         if ((ahd_inb(ahd, SEQ_FLAGS) & DPHASE) == 0
5677          || ahd_get_transfer_dir(scb) != CAM_DIR_IN) {
5678                 /*
5679                  * Ignore the message if we haven't
5680                  * seen an appropriate data phase yet.
5681                  */
5682         } else {
5683                 /*
5684                  * If the residual occurred on the last
5685                  * transfer and the transfer request was
5686                  * expected to end on an odd count, do
5687                  * nothing.  Otherwise, subtract a byte
5688                  * and update the residual count accordingly.
5689                  */
5690                 uint32_t sgptr;
5691
5692                 sgptr = ahd_inb_scbram(ahd, SCB_RESIDUAL_SGPTR);
5693                 if ((sgptr & SG_LIST_NULL) != 0
5694                  && (ahd_inb_scbram(ahd, SCB_TASK_ATTRIBUTE)
5695                      & SCB_XFERLEN_ODD) != 0) {
5696                         /*
5697                          * If the residual occurred on the last
5698                          * transfer and the transfer request was
5699                          * expected to end on an odd count, do
5700                          * nothing.
5701                          */
5702                 } else {
5703                         uint32_t data_cnt;
5704                         uint64_t data_addr;
5705                         uint32_t sglen;
5706
5707                         /* Pull in the rest of the sgptr */
5708                         sgptr = ahd_inl_scbram(ahd, SCB_RESIDUAL_SGPTR);
5709                         data_cnt = ahd_inl_scbram(ahd, SCB_RESIDUAL_DATACNT);
5710                         if ((sgptr & SG_LIST_NULL) != 0) {
5711                                 /*
5712                                  * The residual data count is not updated
5713                                  * for the command run to completion case.
5714                                  * Explicitly zero the count.
5715                                  */
5716                                 data_cnt &= ~AHD_SG_LEN_MASK;
5717                         }
5718                         data_addr = ahd_inq(ahd, SHADDR);
5719                         data_cnt += 1;
5720                         data_addr -= 1;
5721                         sgptr &= SG_PTR_MASK;
5722                         if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0) {
5723                                 struct ahd_dma64_seg *sg;
5724
5725                                 sg = ahd_sg_bus_to_virt(ahd, scb, sgptr);
5726
5727                                 /*
5728                                  * The residual sg ptr points to the next S/G
5729                                  * to load so we must go back one.
5730                                  */
5731                                 sg--;
5732                                 sglen = ahd_le32toh(sg->len) & AHD_SG_LEN_MASK;
5733                                 if (sg != scb->sg_list
5734                                  && sglen < (data_cnt & AHD_SG_LEN_MASK)) {
5735
5736                                         sg--;
5737                                         sglen = ahd_le32toh(sg->len);
5738                                         /*
5739                                          * Preserve High Address and SG_LIST
5740                                          * bits while setting the count to 1.
5741                                          */
5742                                         data_cnt = 1|(sglen&(~AHD_SG_LEN_MASK));
5743                                         data_addr = ahd_le64toh(sg->addr)
5744                                                   + (sglen & AHD_SG_LEN_MASK)
5745                                                   - 1;
5746
5747                                         /*
5748                                          * Increment sg so it points to the
5749                                          * "next" sg.
5750                                          */
5751                                         sg++;
5752                                         sgptr = ahd_sg_virt_to_bus(ahd, scb,
5753                                                                    sg);
5754                                 }
5755                         } else {
5756                                 struct ahd_dma_seg *sg;
5757
5758                                 sg = ahd_sg_bus_to_virt(ahd, scb, sgptr);
5759
5760                                 /*
5761                                  * The residual sg ptr points to the next S/G
5762                                  * to load so we must go back one.
5763                                  */
5764                                 sg--;
5765                                 sglen = ahd_le32toh(sg->len) & AHD_SG_LEN_MASK;
5766                                 if (sg != scb->sg_list
5767                                  && sglen < (data_cnt & AHD_SG_LEN_MASK)) {
5768
5769                                         sg--;
5770                                         sglen = ahd_le32toh(sg->len);
5771                                         /*
5772                                          * Preserve High Address and SG_LIST
5773                                          * bits while setting the count to 1.
5774                                          */
5775                                         data_cnt = 1|(sglen&(~AHD_SG_LEN_MASK));
5776                                         data_addr = ahd_le32toh(sg->addr)
5777                                                   + (sglen & AHD_SG_LEN_MASK)
5778                                                   - 1;
5779
5780                                         /*
5781                                          * Increment sg so it points to the
5782                                          * "next" sg.
5783                                          */
5784                                         sg++;
5785                                         sgptr = ahd_sg_virt_to_bus(ahd, scb,
5786                                                                   sg);
5787                                 }
5788                         }
5789                         /*
5790                          * Toggle the "oddness" of the transfer length
5791                          * to handle this mid-transfer ignore wide
5792                          * residue.  This ensures that the oddness is
5793                          * correct for subsequent data transfers.
5794                          */
5795                         ahd_outb(ahd, SCB_TASK_ATTRIBUTE,
5796                             ahd_inb_scbram(ahd, SCB_TASK_ATTRIBUTE)
5797                             ^ SCB_XFERLEN_ODD);
5798
5799                         ahd_outl(ahd, SCB_RESIDUAL_SGPTR, sgptr);
5800                         ahd_outl(ahd, SCB_RESIDUAL_DATACNT, data_cnt);
5801                         /*
5802                          * The FIFO's pointers will be updated if/when the
5803                          * sequencer re-enters a data phase.
5804                          */
5805                 }
5806         }
5807 }
5808
5809
5810 /*
5811  * Reinitialize the data pointers for the active transfer
5812  * based on its current residual.
5813  */
5814 static void
5815 ahd_reinitialize_dataptrs(struct ahd_softc *ahd)
5816 {
5817         struct           scb *scb;
5818         ahd_mode_state   saved_modes;
5819         u_int            scb_index;
5820         u_int            wait;
5821         uint32_t         sgptr;
5822         uint32_t         resid;
5823         uint64_t         dataptr;
5824
5825         AHD_ASSERT_MODES(ahd, AHD_MODE_DFF0_MSK|AHD_MODE_DFF1_MSK,
5826                          AHD_MODE_DFF0_MSK|AHD_MODE_DFF1_MSK);
5827                          
5828         scb_index = ahd_get_scbptr(ahd);
5829         scb = ahd_lookup_scb(ahd, scb_index);
5830
5831         /*
5832          * Release and reacquire the FIFO so we
5833          * have a clean slate.
5834          */
5835         ahd_outb(ahd, DFFSXFRCTL, CLRCHN);
5836         wait = 1000;
5837         while (--wait && !(ahd_inb(ahd, MDFFSTAT) & FIFOFREE))
5838                 ahd_delay(100);
5839         if (wait == 0) {
5840                 ahd_print_path(ahd, scb);
5841                 printf("ahd_reinitialize_dataptrs: Forcing FIFO free.\n");
5842                 ahd_outb(ahd, DFFSXFRCTL, RSTCHN|CLRSHCNT);
5843         }
5844         saved_modes = ahd_save_modes(ahd);
5845         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
5846         ahd_outb(ahd, DFFSTAT,
5847                  ahd_inb(ahd, DFFSTAT)
5848                 | (saved_modes == 0x11 ? CURRFIFO_1 : CURRFIFO_0));
5849
5850         /*
5851          * Determine initial values for data_addr and data_cnt
5852          * for resuming the data phase.
5853          */
5854         sgptr = ahd_inl_scbram(ahd, SCB_RESIDUAL_SGPTR);
5855         sgptr &= SG_PTR_MASK;
5856
5857         resid = (ahd_inb_scbram(ahd, SCB_RESIDUAL_DATACNT + 2) << 16)
5858               | (ahd_inb_scbram(ahd, SCB_RESIDUAL_DATACNT + 1) << 8)
5859               | ahd_inb_scbram(ahd, SCB_RESIDUAL_DATACNT);
5860
5861         if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0) {
5862                 struct ahd_dma64_seg *sg;
5863
5864                 sg = ahd_sg_bus_to_virt(ahd, scb, sgptr);
5865
5866                 /* The residual sg_ptr always points to the next sg */
5867                 sg--;
5868
5869                 dataptr = ahd_le64toh(sg->addr)
5870                         + (ahd_le32toh(sg->len) & AHD_SG_LEN_MASK)
5871                         - resid;
5872                 ahd_outl(ahd, HADDR + 4, dataptr >> 32);
5873         } else {
5874                 struct   ahd_dma_seg *sg;
5875
5876                 sg = ahd_sg_bus_to_virt(ahd, scb, sgptr);
5877
5878                 /* The residual sg_ptr always points to the next sg */
5879                 sg--;
5880
5881                 dataptr = ahd_le32toh(sg->addr)
5882                         + (ahd_le32toh(sg->len) & AHD_SG_LEN_MASK)
5883                         - resid;
5884                 ahd_outb(ahd, HADDR + 4,
5885                          (ahd_le32toh(sg->len) & ~AHD_SG_LEN_MASK) >> 24);
5886         }
5887         ahd_outl(ahd, HADDR, dataptr);
5888         ahd_outb(ahd, HCNT + 2, resid >> 16);
5889         ahd_outb(ahd, HCNT + 1, resid >> 8);
5890         ahd_outb(ahd, HCNT, resid);
5891 }
5892
5893 /*
5894  * Handle the effects of issuing a bus device reset message.
5895  */
5896 static void
5897 ahd_handle_devreset(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
5898                     u_int lun, cam_status status, char *message,
5899                     int verbose_level)
5900 {
5901 #ifdef AHD_TARGET_MODE
5902         struct ahd_tmode_tstate* tstate;
5903 #endif
5904         int found;
5905
5906         found = ahd_abort_scbs(ahd, devinfo->target, devinfo->channel,
5907                                lun, SCB_LIST_NULL, devinfo->role,
5908                                status);
5909
5910 #ifdef AHD_TARGET_MODE
5911         /*
5912          * Send an immediate notify ccb to all target mord peripheral
5913          * drivers affected by this action.
5914          */
5915         tstate = ahd->enabled_targets[devinfo->our_scsiid];
5916         if (tstate != NULL) {
5917                 u_int cur_lun;
5918                 u_int max_lun;
5919
5920                 if (lun != CAM_LUN_WILDCARD) {
5921                         cur_lun = 0;
5922                         max_lun = AHD_NUM_LUNS - 1;
5923                 } else {
5924                         cur_lun = lun;
5925                         max_lun = lun;
5926                 }
5927                 for (;cur_lun <= max_lun; cur_lun++) {
5928                         struct ahd_tmode_lstate* lstate;
5929
5930                         lstate = tstate->enabled_luns[cur_lun];
5931                         if (lstate == NULL)
5932                                 continue;
5933
5934                         ahd_queue_lstate_event(ahd, lstate, devinfo->our_scsiid,
5935                                                MSG_BUS_DEV_RESET, /*arg*/0);
5936                         ahd_send_lstate_events(ahd, lstate);
5937                 }
5938         }
5939 #endif
5940
5941         /*
5942          * Go back to async/narrow transfers and renegotiate.
5943          */
5944         ahd_set_width(ahd, devinfo, MSG_EXT_WDTR_BUS_8_BIT,
5945                       AHD_TRANS_CUR, /*paused*/TRUE);
5946         ahd_set_syncrate(ahd, devinfo, /*period*/0, /*offset*/0,
5947                          /*ppr_options*/0, AHD_TRANS_CUR,
5948                          /*paused*/TRUE);
5949         
5950         if (status != CAM_SEL_TIMEOUT)
5951                 ahd_send_async(ahd, devinfo->channel, devinfo->target,
5952                                CAM_LUN_WILDCARD, AC_SENT_BDR);
5953
5954         if (message != NULL && bootverbose)
5955                 printf("%s: %s on %c:%d. %d SCBs aborted\n", ahd_name(ahd),
5956                        message, devinfo->channel, devinfo->target, found);
5957 }
5958
5959 #ifdef AHD_TARGET_MODE
5960 static void
5961 ahd_setup_target_msgin(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
5962                        struct scb *scb)
5963 {
5964
5965         /*              
5966          * To facilitate adding multiple messages together,
5967          * each routine should increment the index and len
5968          * variables instead of setting them explicitly.
5969          */             
5970         ahd->msgout_index = 0;
5971         ahd->msgout_len = 0;
5972
5973         if (scb != NULL && (scb->flags & SCB_AUTO_NEGOTIATE) != 0)
5974                 ahd_build_transfer_msg(ahd, devinfo);
5975         else
5976                 panic("ahd_intr: AWAITING target message with no message");
5977
5978         ahd->msgout_index = 0;
5979         ahd->msg_type = MSG_TYPE_TARGET_MSGIN;
5980 }
5981 #endif
5982 /**************************** Initialization **********************************/
5983 static u_int
5984 ahd_sglist_size(struct ahd_softc *ahd)
5985 {
5986         bus_size_t list_size;
5987
5988         list_size = sizeof(struct ahd_dma_seg) * AHD_NSEG;
5989         if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0)
5990                 list_size = sizeof(struct ahd_dma64_seg) * AHD_NSEG;
5991         return (list_size);
5992 }
5993
5994 /*
5995  * Calculate the optimum S/G List allocation size.  S/G elements used
5996  * for a given transaction must be physically contiguous.  Assume the
5997  * OS will allocate full pages to us, so it doesn't make sense to request
5998  * less than a page.
5999  */
6000 static u_int
6001 ahd_sglist_allocsize(struct ahd_softc *ahd)
6002 {
6003         bus_size_t sg_list_increment;
6004         bus_size_t sg_list_size;
6005         bus_size_t max_list_size;
6006         bus_size_t best_list_size;
6007
6008         /* Start out with the minimum required for AHD_NSEG. */
6009         sg_list_increment = ahd_sglist_size(ahd);
6010         sg_list_size = sg_list_increment;
6011
6012         /* Get us as close as possible to a page in size. */
6013         while ((sg_list_size + sg_list_increment) <= PAGE_SIZE)
6014                 sg_list_size += sg_list_increment;
6015
6016         /*
6017          * Try to reduce the amount of wastage by allocating
6018          * multiple pages.
6019          */
6020         best_list_size = sg_list_size;
6021         max_list_size = roundup(sg_list_increment, PAGE_SIZE);
6022         if (max_list_size < 4 * PAGE_SIZE)
6023                 max_list_size = 4 * PAGE_SIZE;
6024         if (max_list_size > (AHD_SCB_MAX_ALLOC * sg_list_increment))
6025                 max_list_size = (AHD_SCB_MAX_ALLOC * sg_list_increment);
6026         while ((sg_list_size + sg_list_increment) <= max_list_size
6027            &&  (sg_list_size % PAGE_SIZE) != 0) {
6028                 bus_size_t new_mod;
6029                 bus_size_t best_mod;
6030
6031                 sg_list_size += sg_list_increment;
6032                 new_mod = sg_list_size % PAGE_SIZE;
6033                 best_mod = best_list_size % PAGE_SIZE;
6034                 if (new_mod > best_mod || new_mod == 0) {
6035                         best_list_size = sg_list_size;
6036                 }
6037         }
6038         return (best_list_size);
6039 }
6040
6041 /*
6042  * Allocate a controller structure for a new device
6043  * and perform initial initializion.
6044  */
6045 struct ahd_softc *
6046 ahd_alloc(void *platform_arg, char *name)
6047 {
6048         struct  ahd_softc *ahd;
6049
6050 #ifndef __FreeBSD__
6051         ahd = malloc(sizeof(*ahd), M_DEVBUF, M_NOWAIT);
6052         if (!ahd) {
6053                 printf("aic7xxx: cannot malloc softc!\n");
6054                 free(name, M_DEVBUF);
6055                 return NULL;
6056         }
6057 #else
6058         ahd = device_get_softc((device_t)platform_arg);
6059 #endif
6060         memset(ahd, 0, sizeof(*ahd));
6061         ahd->seep_config = malloc(sizeof(*ahd->seep_config),
6062                                   M_DEVBUF, M_NOWAIT);
6063         if (ahd->seep_config == NULL) {
6064 #ifndef __FreeBSD__
6065                 free(ahd, M_DEVBUF);
6066 #endif
6067                 free(name, M_DEVBUF);
6068                 return (NULL);
6069         }
6070         LIST_INIT(&ahd->pending_scbs);
6071         /* We don't know our unit number until the OSM sets it */
6072         ahd->name = name;
6073         ahd->unit = -1;
6074         ahd->description = NULL;
6075         ahd->bus_description = NULL;
6076         ahd->channel = 'A';
6077         ahd->chip = AHD_NONE;
6078         ahd->features = AHD_FENONE;
6079         ahd->bugs = AHD_BUGNONE;
6080         ahd->flags = AHD_SPCHK_ENB_A|AHD_RESET_BUS_A|AHD_TERM_ENB_A
6081                    | AHD_EXTENDED_TRANS_A|AHD_STPWLEVEL_A;
6082         ahd_timer_init(&ahd->reset_timer);
6083         ahd_timer_init(&ahd->stat_timer);
6084         ahd->int_coalescing_timer = AHD_INT_COALESCING_TIMER_DEFAULT;
6085         ahd->int_coalescing_maxcmds = AHD_INT_COALESCING_MAXCMDS_DEFAULT;
6086         ahd->int_coalescing_mincmds = AHD_INT_COALESCING_MINCMDS_DEFAULT;
6087         ahd->int_coalescing_threshold = AHD_INT_COALESCING_THRESHOLD_DEFAULT;
6088         ahd->int_coalescing_stop_threshold =
6089             AHD_INT_COALESCING_STOP_THRESHOLD_DEFAULT;
6090
6091         if (ahd_platform_alloc(ahd, platform_arg) != 0) {
6092                 ahd_free(ahd);
6093                 ahd = NULL;
6094         }
6095 #ifdef AHD_DEBUG
6096         if ((ahd_debug & AHD_SHOW_MEMORY) != 0) {
6097                 printf("%s: scb size = 0x%x, hscb size = 0x%x\n",
6098                        ahd_name(ahd), (u_int)sizeof(struct scb),
6099                        (u_int)sizeof(struct hardware_scb));
6100         }
6101 #endif
6102         return (ahd);
6103 }
6104
6105 int
6106 ahd_softc_init(struct ahd_softc *ahd)
6107 {
6108
6109         ahd->unpause = 0;
6110         ahd->pause = PAUSE; 
6111         return (0);
6112 }
6113
6114 void
6115 ahd_set_unit(struct ahd_softc *ahd, int unit)
6116 {
6117         ahd->unit = unit;
6118 }
6119
6120 void
6121 ahd_set_name(struct ahd_softc *ahd, char *name)
6122 {
6123         if (ahd->name != NULL)
6124                 free(ahd->name, M_DEVBUF);
6125         ahd->name = name;
6126 }
6127
6128 void
6129 ahd_free(struct ahd_softc *ahd)
6130 {
6131         int i;
6132
6133         switch (ahd->init_level) {
6134         default:
6135         case 5:
6136                 ahd_shutdown(ahd);
6137                 /* FALLTHROUGH */
6138         case 4:
6139                 ahd_dmamap_unload(ahd, ahd->shared_data_dmat,
6140                                   ahd->shared_data_map.dmamap);
6141                 /* FALLTHROUGH */
6142         case 3:
6143                 ahd_dmamem_free(ahd, ahd->shared_data_dmat, ahd->qoutfifo,
6144                                 ahd->shared_data_map.dmamap);
6145                 ahd_dmamap_destroy(ahd, ahd->shared_data_dmat,
6146                                    ahd->shared_data_map.dmamap);
6147                 /* FALLTHROUGH */
6148         case 2:
6149                 ahd_dma_tag_destroy(ahd, ahd->shared_data_dmat);
6150         case 1:
6151 #ifndef __linux__
6152                 ahd_dma_tag_destroy(ahd, ahd->buffer_dmat);
6153 #endif
6154                 break;
6155         case 0:
6156                 break;
6157         }
6158
6159 #ifndef __linux__
6160         ahd_dma_tag_destroy(ahd, ahd->parent_dmat);
6161 #endif
6162         ahd_platform_free(ahd);
6163         ahd_fini_scbdata(ahd);
6164         for (i = 0; i < AHD_NUM_TARGETS; i++) {
6165                 struct ahd_tmode_tstate *tstate;
6166
6167                 tstate = ahd->enabled_targets[i];
6168                 if (tstate != NULL) {
6169 #ifdef AHD_TARGET_MODE
6170                         int j;
6171
6172                         for (j = 0; j < AHD_NUM_LUNS; j++) {
6173                                 struct ahd_tmode_lstate *lstate;
6174
6175                                 lstate = tstate->enabled_luns[j];
6176                                 if (lstate != NULL) {
6177                                         xpt_free_path(lstate->path);
6178                                         free(lstate, M_DEVBUF);
6179                                 }
6180                         }
6181 #endif
6182                         free(tstate, M_DEVBUF);
6183                 }
6184         }
6185 #ifdef AHD_TARGET_MODE
6186         if (ahd->black_hole != NULL) {
6187                 xpt_free_path(ahd->black_hole->path);
6188                 free(ahd->black_hole, M_DEVBUF);
6189         }
6190 #endif
6191         if (ahd->name != NULL)
6192                 free(ahd->name, M_DEVBUF);
6193         if (ahd->seep_config != NULL)
6194                 free(ahd->seep_config, M_DEVBUF);
6195         if (ahd->saved_stack != NULL)
6196                 free(ahd->saved_stack, M_DEVBUF);
6197 #ifndef __FreeBSD__
6198         free(ahd, M_DEVBUF);
6199 #endif
6200         return;
6201 }
6202
6203 static void
6204 ahd_shutdown(void *arg)
6205 {
6206         struct  ahd_softc *ahd;
6207
6208         ahd = (struct ahd_softc *)arg;
6209
6210         /*
6211          * Stop periodic timer callbacks.
6212          */
6213         ahd_timer_stop(&ahd->reset_timer);
6214         ahd_timer_stop(&ahd->stat_timer);
6215
6216         /* This will reset most registers to 0, but not all */
6217         ahd_reset(ahd, /*reinit*/FALSE);
6218 }
6219
6220 /*
6221  * Reset the controller and record some information about it
6222  * that is only available just after a reset.  If "reinit" is
6223  * non-zero, this reset occured after initial configuration
6224  * and the caller requests that the chip be fully reinitialized
6225  * to a runable state.  Chip interrupts are *not* enabled after
6226  * a reinitialization.  The caller must enable interrupts via
6227  * ahd_intr_enable().
6228  */
6229 int
6230 ahd_reset(struct ahd_softc *ahd, int reinit)
6231 {
6232         u_int    sxfrctl1;
6233         int      wait;
6234         uint32_t cmd;
6235         
6236         /*
6237          * Preserve the value of the SXFRCTL1 register for all channels.
6238          * It contains settings that affect termination and we don't want
6239          * to disturb the integrity of the bus.
6240          */
6241         ahd_pause(ahd);
6242         ahd_update_modes(ahd);
6243         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
6244         sxfrctl1 = ahd_inb(ahd, SXFRCTL1);
6245
6246         cmd = ahd_pci_read_config(ahd->dev_softc, PCIR_COMMAND, /*bytes*/2);
6247         if ((ahd->bugs & AHD_PCIX_CHIPRST_BUG) != 0) {
6248                 uint32_t mod_cmd;
6249
6250                 /*
6251                  * A4 Razor #632
6252                  * During the assertion of CHIPRST, the chip
6253                  * does not disable its parity logic prior to
6254                  * the start of the reset.  This may cause a
6255                  * parity error to be detected and thus a
6256                  * spurious SERR or PERR assertion.  Disble
6257                  * PERR and SERR responses during the CHIPRST.
6258                  */
6259                 mod_cmd = cmd & ~(PCIM_CMD_PERRESPEN|PCIM_CMD_SERRESPEN);
6260                 ahd_pci_write_config(ahd->dev_softc, PCIR_COMMAND,
6261                                      mod_cmd, /*bytes*/2);
6262         }
6263         ahd_outb(ahd, HCNTRL, CHIPRST | ahd->pause);
6264
6265         /*
6266          * Ensure that the reset has finished.  We delay 1000us
6267          * prior to reading the register to make sure the chip
6268          * has sufficiently completed its reset to handle register
6269          * accesses.
6270          */
6271         wait = 1000;
6272         do {
6273                 ahd_delay(1000);
6274         } while (--wait && !(ahd_inb(ahd, HCNTRL) & CHIPRSTACK));
6275
6276         if (wait == 0) {
6277                 printf("%s: WARNING - Failed chip reset!  "
6278                        "Trying to initialize anyway.\n", ahd_name(ahd));
6279         }
6280         ahd_outb(ahd, HCNTRL, ahd->pause);
6281
6282         if ((ahd->bugs & AHD_PCIX_CHIPRST_BUG) != 0) {
6283                 /*
6284                  * Clear any latched PCI error status and restore
6285                  * previous SERR and PERR response enables.
6286                  */
6287                 ahd_pci_write_config(ahd->dev_softc, PCIR_STATUS + 1,
6288                                      0xFF, /*bytes*/1);
6289                 ahd_pci_write_config(ahd->dev_softc, PCIR_COMMAND,
6290                                      cmd, /*bytes*/2);
6291         }
6292
6293         /*
6294          * Mode should be SCSI after a chip reset, but lets
6295          * set it just to be safe.  We touch the MODE_PTR
6296          * register directly so as to bypass the lazy update
6297          * code in ahd_set_modes().
6298          */
6299         ahd_known_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
6300         ahd_outb(ahd, MODE_PTR,
6301                  ahd_build_mode_state(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI));
6302
6303         /*
6304          * Restore SXFRCTL1.
6305          *
6306          * We must always initialize STPWEN to 1 before we
6307          * restore the saved values.  STPWEN is initialized
6308          * to a tri-state condition which can only be cleared
6309          * by turning it on.
6310          */
6311         ahd_outb(ahd, SXFRCTL1, sxfrctl1|STPWEN);
6312         ahd_outb(ahd, SXFRCTL1, sxfrctl1);
6313
6314         /* Determine chip configuration */
6315         ahd->features &= ~AHD_WIDE;
6316         if ((ahd_inb(ahd, SBLKCTL) & SELWIDE) != 0)
6317                 ahd->features |= AHD_WIDE;
6318
6319         /*
6320          * If a recovery action has forced a chip reset,
6321          * re-initialize the chip to our liking.
6322          */
6323         if (reinit != 0)
6324                 ahd_chip_init(ahd);
6325
6326         return (0);
6327 }
6328
6329 /*
6330  * Determine the number of SCBs available on the controller
6331  */
6332 static int
6333 ahd_probe_scbs(struct ahd_softc *ahd) {
6334         int i;
6335
6336         AHD_ASSERT_MODES(ahd, ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK),
6337                          ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK));
6338         for (i = 0; i < AHD_SCB_MAX; i++) {
6339                 int j;
6340
6341                 ahd_set_scbptr(ahd, i);
6342                 ahd_outw(ahd, SCB_BASE, i);
6343                 for (j = 2; j < 64; j++)
6344                         ahd_outb(ahd, SCB_BASE+j, 0);
6345                 /* Start out life as unallocated (needing an abort) */
6346                 ahd_outb(ahd, SCB_CONTROL, MK_MESSAGE);
6347                 if (ahd_inw_scbram(ahd, SCB_BASE) != i)
6348                         break;
6349                 ahd_set_scbptr(ahd, 0);
6350                 if (ahd_inw_scbram(ahd, SCB_BASE) != 0)
6351                         break;
6352         }
6353         return (i);
6354 }
6355
6356 static void
6357 ahd_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nseg, int error) 
6358 {
6359         dma_addr_t *baddr;
6360
6361         baddr = (dma_addr_t *)arg;
6362         *baddr = segs->ds_addr;
6363 }
6364
6365 static void
6366 ahd_initialize_hscbs(struct ahd_softc *ahd)
6367 {
6368         int i;
6369
6370         for (i = 0; i < ahd->scb_data.maxhscbs; i++) {
6371                 ahd_set_scbptr(ahd, i);
6372
6373                 /* Clear the control byte. */
6374                 ahd_outb(ahd, SCB_CONTROL, 0);
6375
6376                 /* Set the next pointer */
6377                 ahd_outw(ahd, SCB_NEXT, SCB_LIST_NULL);
6378         }
6379 }
6380
6381 static int
6382 ahd_init_scbdata(struct ahd_softc *ahd)
6383 {
6384         struct  scb_data *scb_data;
6385         int     i;
6386
6387         scb_data = &ahd->scb_data;
6388         TAILQ_INIT(&scb_data->free_scbs);
6389         for (i = 0; i < AHD_NUM_TARGETS * AHD_NUM_LUNS_NONPKT; i++)
6390                 LIST_INIT(&scb_data->free_scb_lists[i]);
6391         LIST_INIT(&scb_data->any_dev_free_scb_list);
6392         SLIST_INIT(&scb_data->hscb_maps);
6393         SLIST_INIT(&scb_data->sg_maps);
6394         SLIST_INIT(&scb_data->sense_maps);
6395
6396         /* Determine the number of hardware SCBs and initialize them */
6397         scb_data->maxhscbs = ahd_probe_scbs(ahd);
6398         if (scb_data->maxhscbs == 0) {
6399                 printf("%s: No SCB space found\n", ahd_name(ahd));
6400                 return (ENXIO);
6401         }
6402
6403         ahd_initialize_hscbs(ahd);
6404
6405         /*
6406          * Create our DMA tags.  These tags define the kinds of device
6407          * accessible memory allocations and memory mappings we will
6408          * need to perform during normal operation.
6409          *
6410          * Unless we need to further restrict the allocation, we rely
6411          * on the restrictions of the parent dmat, hence the common
6412          * use of MAXADDR and MAXSIZE.
6413          */
6414
6415         /* DMA tag for our hardware scb structures */
6416         if (ahd_dma_tag_create(ahd, ahd->parent_dmat, /*alignment*/1,
6417                                /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
6418                                /*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
6419                                /*highaddr*/BUS_SPACE_MAXADDR,
6420                                /*filter*/NULL, /*filterarg*/NULL,
6421                                PAGE_SIZE, /*nsegments*/1,
6422                                /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
6423                                /*flags*/0, &scb_data->hscb_dmat) != 0) {
6424                 goto error_exit;
6425         }
6426
6427         scb_data->init_level++;
6428
6429         /* DMA tag for our S/G structures. */
6430         if (ahd_dma_tag_create(ahd, ahd->parent_dmat, /*alignment*/8,
6431                                /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
6432                                /*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
6433                                /*highaddr*/BUS_SPACE_MAXADDR,
6434                                /*filter*/NULL, /*filterarg*/NULL,
6435                                ahd_sglist_allocsize(ahd), /*nsegments*/1,
6436                                /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
6437                                /*flags*/0, &scb_data->sg_dmat) != 0) {
6438                 goto error_exit;
6439         }
6440 #ifdef AHD_DEBUG
6441         if ((ahd_debug & AHD_SHOW_MEMORY) != 0)
6442                 printf("%s: ahd_sglist_allocsize = 0x%x\n", ahd_name(ahd),
6443                        ahd_sglist_allocsize(ahd));
6444 #endif
6445
6446         scb_data->init_level++;
6447
6448         /* DMA tag for our sense buffers.  We allocate in page sized chunks */
6449         if (ahd_dma_tag_create(ahd, ahd->parent_dmat, /*alignment*/1,
6450                                /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
6451                                /*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
6452                                /*highaddr*/BUS_SPACE_MAXADDR,
6453                                /*filter*/NULL, /*filterarg*/NULL,
6454                                PAGE_SIZE, /*nsegments*/1,
6455                                /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
6456                                /*flags*/0, &scb_data->sense_dmat) != 0) {
6457                 goto error_exit;
6458         }
6459
6460         scb_data->init_level++;
6461
6462         /* Perform initial CCB allocation */
6463         ahd_alloc_scbs(ahd);
6464
6465         if (scb_data->numscbs == 0) {
6466                 printf("%s: ahd_init_scbdata - "
6467                        "Unable to allocate initial scbs\n",
6468                        ahd_name(ahd));
6469                 goto error_exit;
6470         }
6471
6472         /*
6473          * Note that we were successfull
6474          */
6475         return (0); 
6476
6477 error_exit:
6478
6479         return (ENOMEM);
6480 }
6481
6482 static struct scb *
6483 ahd_find_scb_by_tag(struct ahd_softc *ahd, u_int tag)
6484 {
6485         struct scb *scb;
6486
6487         /*
6488          * Look on the pending list.
6489          */
6490         LIST_FOREACH(scb, &ahd->pending_scbs, pending_links) {
6491                 if (SCB_GET_TAG(scb) == tag)
6492                         return (scb);
6493         }
6494
6495         /*
6496          * Then on all of the collision free lists.
6497          */
6498         TAILQ_FOREACH(scb, &ahd->scb_data.free_scbs, links.tqe) {
6499                 struct scb *list_scb;
6500
6501                 list_scb = scb;
6502                 do {
6503                         if (SCB_GET_TAG(list_scb) == tag)
6504                                 return (list_scb);
6505                         list_scb = LIST_NEXT(list_scb, collision_links);
6506                 } while (list_scb);
6507         }
6508
6509         /*
6510          * And finally on the generic free list.
6511          */
6512         LIST_FOREACH(scb, &ahd->scb_data.any_dev_free_scb_list, links.le) {
6513                 if (SCB_GET_TAG(scb) == tag)
6514                         return (scb);
6515         }
6516
6517         return (NULL);
6518 }
6519
6520 static void
6521 ahd_fini_scbdata(struct ahd_softc *ahd)
6522 {
6523         struct scb_data *scb_data;
6524
6525         scb_data = &ahd->scb_data;
6526         if (scb_data == NULL)
6527                 return;
6528
6529         switch (scb_data->init_level) {
6530         default:
6531         case 7:
6532         {
6533                 struct map_node *sns_map;
6534
6535                 while ((sns_map = SLIST_FIRST(&scb_data->sense_maps)) != NULL) {
6536                         SLIST_REMOVE_HEAD(&scb_data->sense_maps, links);
6537                         ahd_dmamap_unload(ahd, scb_data->sense_dmat,
6538                                           sns_map->dmamap);
6539                         ahd_dmamem_free(ahd, scb_data->sense_dmat,
6540                                         sns_map->vaddr, sns_map->dmamap);
6541                         free(sns_map, M_DEVBUF);
6542                 }
6543                 ahd_dma_tag_destroy(ahd, scb_data->sense_dmat);
6544                 /* FALLTHROUGH */
6545         }
6546         case 6:
6547         {
6548                 struct map_node *sg_map;
6549
6550                 while ((sg_map = SLIST_FIRST(&scb_data->sg_maps)) != NULL) {
6551                         SLIST_REMOVE_HEAD(&scb_data->sg_maps, links);
6552                         ahd_dmamap_unload(ahd, scb_data->sg_dmat,
6553                                           sg_map->dmamap);
6554                         ahd_dmamem_free(ahd, scb_data->sg_dmat,
6555                                         sg_map->vaddr, sg_map->dmamap);
6556                         free(sg_map, M_DEVBUF);
6557                 }
6558                 ahd_dma_tag_destroy(ahd, scb_data->sg_dmat);
6559                 /* FALLTHROUGH */
6560         }
6561         case 5:
6562         {
6563                 struct map_node *hscb_map;
6564
6565                 while ((hscb_map = SLIST_FIRST(&scb_data->hscb_maps)) != NULL) {
6566                         SLIST_REMOVE_HEAD(&scb_data->hscb_maps, links);
6567                         ahd_dmamap_unload(ahd, scb_data->hscb_dmat,
6568                                           hscb_map->dmamap);
6569                         ahd_dmamem_free(ahd, scb_data->hscb_dmat,
6570                                         hscb_map->vaddr, hscb_map->dmamap);
6571                         free(hscb_map, M_DEVBUF);
6572                 }
6573                 ahd_dma_tag_destroy(ahd, scb_data->hscb_dmat);
6574                 /* FALLTHROUGH */
6575         }
6576         case 4:
6577         case 3:
6578         case 2:
6579         case 1:
6580         case 0:
6581                 break;
6582         }
6583 }
6584
6585 /*
6586  * DSP filter Bypass must be enabled until the first selection
6587  * after a change in bus mode (Razor #491 and #493).
6588  */
6589 static void
6590 ahd_setup_iocell_workaround(struct ahd_softc *ahd)
6591 {
6592         ahd_mode_state saved_modes;
6593
6594         saved_modes = ahd_save_modes(ahd);
6595         ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
6596         ahd_outb(ahd, DSPDATACTL, ahd_inb(ahd, DSPDATACTL)
6597                | BYPASSENAB | RCVROFFSTDIS | XMITOFFSTDIS);
6598         ahd_outb(ahd, SIMODE0, ahd_inb(ahd, SIMODE0) | (ENSELDO|ENSELDI));
6599 #ifdef AHD_DEBUG
6600         if ((ahd_debug & AHD_SHOW_MISC) != 0)
6601                 printf("%s: Setting up iocell workaround\n", ahd_name(ahd));
6602 #endif
6603         ahd_restore_modes(ahd, saved_modes);
6604         ahd->flags &= ~AHD_HAD_FIRST_SEL;
6605 }
6606
6607 static void
6608 ahd_iocell_first_selection(struct ahd_softc *ahd)
6609 {
6610         ahd_mode_state  saved_modes;
6611         u_int           sblkctl;
6612
6613         if ((ahd->flags & AHD_HAD_FIRST_SEL) != 0)
6614                 return;
6615         saved_modes = ahd_save_modes(ahd);
6616         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
6617         sblkctl = ahd_inb(ahd, SBLKCTL);
6618         ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
6619 #ifdef AHD_DEBUG
6620         if ((ahd_debug & AHD_SHOW_MISC) != 0)
6621                 printf("%s: iocell first selection\n", ahd_name(ahd));
6622 #endif
6623         if ((sblkctl & ENAB40) != 0) {
6624                 ahd_outb(ahd, DSPDATACTL,
6625                          ahd_inb(ahd, DSPDATACTL) & ~BYPASSENAB);
6626 #ifdef AHD_DEBUG
6627                 if ((ahd_debug & AHD_SHOW_MISC) != 0)
6628                         printf("%s: BYPASS now disabled\n", ahd_name(ahd));
6629 #endif
6630         }
6631         ahd_outb(ahd, SIMODE0, ahd_inb(ahd, SIMODE0) & ~(ENSELDO|ENSELDI));
6632         ahd_outb(ahd, CLRINT, CLRSCSIINT);
6633         ahd_restore_modes(ahd, saved_modes);
6634         ahd->flags |= AHD_HAD_FIRST_SEL;
6635 }
6636
6637 /*************************** SCB Management ***********************************/
6638 static void
6639 ahd_add_col_list(struct ahd_softc *ahd, struct scb *scb, u_int col_idx)
6640 {
6641         struct  scb_list *free_list;
6642         struct  scb_tailq *free_tailq;
6643         struct  scb *first_scb;
6644
6645         scb->flags |= SCB_ON_COL_LIST;
6646         AHD_SET_SCB_COL_IDX(scb, col_idx);
6647         free_list = &ahd->scb_data.free_scb_lists[col_idx];
6648         free_tailq = &ahd->scb_data.free_scbs;
6649         first_scb = LIST_FIRST(free_list);
6650         if (first_scb != NULL) {
6651                 LIST_INSERT_AFTER(first_scb, scb, collision_links);
6652         } else {
6653                 LIST_INSERT_HEAD(free_list, scb, collision_links);
6654                 TAILQ_INSERT_TAIL(free_tailq, scb, links.tqe);
6655         }
6656 }
6657
6658 static void
6659 ahd_rem_col_list(struct ahd_softc *ahd, struct scb *scb)
6660 {
6661         struct  scb_list *free_list;
6662         struct  scb_tailq *free_tailq;
6663         struct  scb *first_scb;
6664         u_int   col_idx;
6665
6666         scb->flags &= ~SCB_ON_COL_LIST;
6667         col_idx = AHD_GET_SCB_COL_IDX(ahd, scb);
6668         free_list = &ahd->scb_data.free_scb_lists[col_idx];
6669         free_tailq = &ahd->scb_data.free_scbs;
6670         first_scb = LIST_FIRST(free_list);
6671         if (first_scb == scb) {
6672                 struct scb *next_scb;
6673
6674                 /*
6675                  * Maintain order in the collision free
6676                  * lists for fairness if this device has
6677                  * other colliding tags active.
6678                  */
6679                 next_scb = LIST_NEXT(scb, collision_links);
6680                 if (next_scb != NULL) {
6681                         TAILQ_INSERT_AFTER(free_tailq, scb,
6682                                            next_scb, links.tqe);
6683                 }
6684                 TAILQ_REMOVE(free_tailq, scb, links.tqe);
6685         }
6686         LIST_REMOVE(scb, collision_links);
6687 }
6688
6689 /*
6690  * Get a free scb. If there are none, see if we can allocate a new SCB.
6691  */
6692 struct scb *
6693 ahd_get_scb(struct ahd_softc *ahd, u_int col_idx)
6694 {
6695         struct scb *scb;
6696         int tries;
6697
6698         tries = 0;
6699 look_again:
6700         TAILQ_FOREACH(scb, &ahd->scb_data.free_scbs, links.tqe) {
6701                 if (AHD_GET_SCB_COL_IDX(ahd, scb) != col_idx) {
6702                         ahd_rem_col_list(ahd, scb);
6703                         goto found;
6704                 }
6705         }
6706         if ((scb = LIST_FIRST(&ahd->scb_data.any_dev_free_scb_list)) == NULL) {
6707
6708                 if (tries++ != 0)
6709                         return (NULL);
6710                 ahd_alloc_scbs(ahd);
6711                 goto look_again;
6712         }
6713         LIST_REMOVE(scb, links.le);
6714         if (col_idx != AHD_NEVER_COL_IDX
6715          && (scb->col_scb != NULL)
6716          && (scb->col_scb->flags & SCB_ACTIVE) == 0) {
6717                 LIST_REMOVE(scb->col_scb, links.le);
6718                 ahd_add_col_list(ahd, scb->col_scb, col_idx);
6719         }
6720 found:
6721         scb->flags |= SCB_ACTIVE;
6722         return (scb);
6723 }
6724
6725 /*
6726  * Return an SCB resource to the free list.
6727  */
6728 void
6729 ahd_free_scb(struct ahd_softc *ahd, struct scb *scb)
6730 {
6731         /* Clean up for the next user */
6732         scb->flags = SCB_FLAG_NONE;
6733         scb->hscb->control = 0;
6734         ahd->scb_data.scbindex[SCB_GET_TAG(scb)] = NULL;
6735
6736         if (scb->col_scb == NULL) {
6737
6738                 /*
6739                  * No collision possible.  Just free normally.
6740                  */
6741                 LIST_INSERT_HEAD(&ahd->scb_data.any_dev_free_scb_list,
6742                                  scb, links.le);
6743         } else if ((scb->col_scb->flags & SCB_ON_COL_LIST) != 0) {
6744
6745                 /*
6746                  * The SCB we might have collided with is on
6747                  * a free collision list.  Put both SCBs on
6748                  * the generic list.
6749                  */
6750                 ahd_rem_col_list(ahd, scb->col_scb);
6751                 LIST_INSERT_HEAD(&ahd->scb_data.any_dev_free_scb_list,
6752                                  scb, links.le);
6753                 LIST_INSERT_HEAD(&ahd->scb_data.any_dev_free_scb_list,
6754                                  scb->col_scb, links.le);
6755         } else if ((scb->col_scb->flags
6756                   & (SCB_PACKETIZED|SCB_ACTIVE)) == SCB_ACTIVE
6757                 && (scb->col_scb->hscb->control & TAG_ENB) != 0) {
6758
6759                 /*
6760                  * The SCB we might collide with on the next allocation
6761                  * is still active in a non-packetized, tagged, context.
6762                  * Put us on the SCB collision list.
6763                  */
6764                 ahd_add_col_list(ahd, scb,
6765                                  AHD_GET_SCB_COL_IDX(ahd, scb->col_scb));
6766         } else {
6767                 /*
6768                  * The SCB we might collide with on the next allocation
6769                  * is either active in a packetized context, or free.
6770                  * Since we can't collide, put this SCB on the generic
6771                  * free list.
6772                  */
6773                 LIST_INSERT_HEAD(&ahd->scb_data.any_dev_free_scb_list,
6774                                  scb, links.le);
6775         }
6776
6777         ahd_platform_scb_free(ahd, scb);
6778 }
6779
6780 static void
6781 ahd_alloc_scbs(struct ahd_softc *ahd)
6782 {
6783         struct scb_data *scb_data;
6784         struct scb      *next_scb;
6785         struct hardware_scb *hscb;
6786         struct map_node *hscb_map;
6787         struct map_node *sg_map;
6788         struct map_node *sense_map;
6789         uint8_t         *segs;
6790         uint8_t         *sense_data;
6791         dma_addr_t       hscb_busaddr;
6792         dma_addr_t       sg_busaddr;
6793         dma_addr_t       sense_busaddr;
6794         int              newcount;
6795         int              i;
6796
6797         scb_data = &ahd->scb_data;
6798         if (scb_data->numscbs >= AHD_SCB_MAX_ALLOC)
6799                 /* Can't allocate any more */
6800                 return;
6801
6802         if (scb_data->scbs_left != 0) {
6803                 int offset;
6804
6805                 offset = (PAGE_SIZE / sizeof(*hscb)) - scb_data->scbs_left;
6806                 hscb_map = SLIST_FIRST(&scb_data->hscb_maps);
6807                 hscb = &((struct hardware_scb *)hscb_map->vaddr)[offset];
6808                 hscb_busaddr = hscb_map->physaddr + (offset * sizeof(*hscb));
6809         } else {
6810                 hscb_map = malloc(sizeof(*hscb_map), M_DEVBUF, M_NOWAIT);
6811
6812                 if (hscb_map == NULL)
6813                         return;
6814
6815                 /* Allocate the next batch of hardware SCBs */
6816                 if (ahd_dmamem_alloc(ahd, scb_data->hscb_dmat,
6817                                      (void **)&hscb_map->vaddr,
6818                                      BUS_DMA_NOWAIT, &hscb_map->dmamap) != 0) {
6819                         free(hscb_map, M_DEVBUF);
6820                         return;
6821                 }
6822
6823                 SLIST_INSERT_HEAD(&scb_data->hscb_maps, hscb_map, links);
6824
6825                 ahd_dmamap_load(ahd, scb_data->hscb_dmat, hscb_map->dmamap,
6826                                 hscb_map->vaddr, PAGE_SIZE, ahd_dmamap_cb,
6827                                 &hscb_map->physaddr, /*flags*/0);
6828
6829                 hscb = (struct hardware_scb *)hscb_map->vaddr;
6830                 hscb_busaddr = hscb_map->physaddr;
6831                 scb_data->scbs_left = PAGE_SIZE / sizeof(*hscb);
6832         }
6833
6834         if (scb_data->sgs_left != 0) {
6835                 int offset;
6836
6837                 offset = ((ahd_sglist_allocsize(ahd) / ahd_sglist_size(ahd))
6838                        - scb_data->sgs_left) * ahd_sglist_size(ahd);
6839                 sg_map = SLIST_FIRST(&scb_data->sg_maps);
6840                 segs = sg_map->vaddr + offset;
6841                 sg_busaddr = sg_map->physaddr + offset;
6842         } else {
6843                 sg_map = malloc(sizeof(*sg_map), M_DEVBUF, M_NOWAIT);
6844
6845                 if (sg_map == NULL)
6846                         return;
6847
6848                 /* Allocate the next batch of S/G lists */
6849                 if (ahd_dmamem_alloc(ahd, scb_data->sg_dmat,
6850                                      (void **)&sg_map->vaddr,
6851                                      BUS_DMA_NOWAIT, &sg_map->dmamap) != 0) {
6852                         free(sg_map, M_DEVBUF);
6853                         return;
6854                 }
6855
6856                 SLIST_INSERT_HEAD(&scb_data->sg_maps, sg_map, links);
6857
6858                 ahd_dmamap_load(ahd, scb_data->sg_dmat, sg_map->dmamap,
6859                                 sg_map->vaddr, ahd_sglist_allocsize(ahd),
6860                                 ahd_dmamap_cb, &sg_map->physaddr, /*flags*/0);
6861
6862                 segs = sg_map->vaddr;
6863                 sg_busaddr = sg_map->physaddr;
6864                 scb_data->sgs_left =
6865                     ahd_sglist_allocsize(ahd) / ahd_sglist_size(ahd);
6866 #ifdef AHD_DEBUG
6867                 if (ahd_debug & AHD_SHOW_MEMORY)
6868                         printf("Mapped SG data\n");
6869 #endif
6870         }
6871
6872         if (scb_data->sense_left != 0) {
6873                 int offset;
6874
6875                 offset = PAGE_SIZE - (AHD_SENSE_BUFSIZE * scb_data->sense_left);
6876                 sense_map = SLIST_FIRST(&scb_data->sense_maps);
6877                 sense_data = sense_map->vaddr + offset;
6878                 sense_busaddr = sense_map->physaddr + offset;
6879         } else {
6880                 sense_map = malloc(sizeof(*sense_map), M_DEVBUF, M_NOWAIT);
6881
6882                 if (sense_map == NULL)
6883                         return;
6884
6885                 /* Allocate the next batch of sense buffers */
6886                 if (ahd_dmamem_alloc(ahd, scb_data->sense_dmat,
6887                                      (void **)&sense_map->vaddr,
6888                                      BUS_DMA_NOWAIT, &sense_map->dmamap) != 0) {
6889                         free(sense_map, M_DEVBUF);
6890                         return;
6891                 }
6892
6893                 SLIST_INSERT_HEAD(&scb_data->sense_maps, sense_map, links);
6894
6895                 ahd_dmamap_load(ahd, scb_data->sense_dmat, sense_map->dmamap,
6896                                 sense_map->vaddr, PAGE_SIZE, ahd_dmamap_cb,
6897                                 &sense_map->physaddr, /*flags*/0);
6898
6899                 sense_data = sense_map->vaddr;
6900                 sense_busaddr = sense_map->physaddr;
6901                 scb_data->sense_left = PAGE_SIZE / AHD_SENSE_BUFSIZE;
6902 #ifdef AHD_DEBUG
6903                 if (ahd_debug & AHD_SHOW_MEMORY)
6904                         printf("Mapped sense data\n");
6905 #endif
6906         }
6907
6908         newcount = min(scb_data->sense_left, scb_data->scbs_left);
6909         newcount = min(newcount, scb_data->sgs_left);
6910         newcount = min(newcount, (AHD_SCB_MAX_ALLOC - scb_data->numscbs));
6911         for (i = 0; i < newcount; i++) {
6912                 struct scb_platform_data *pdata;
6913                 u_int col_tag;
6914 #ifndef __linux__
6915                 int error;
6916 #endif
6917
6918                 next_scb = (struct scb *)malloc(sizeof(*next_scb),
6919                                                 M_DEVBUF, M_NOWAIT);
6920                 if (next_scb == NULL)
6921                         break;
6922
6923                 pdata = (struct scb_platform_data *)malloc(sizeof(*pdata),
6924                                                            M_DEVBUF, M_NOWAIT);
6925                 if (pdata == NULL) {
6926                         free(next_scb, M_DEVBUF);
6927                         break;
6928                 }
6929                 next_scb->platform_data = pdata;
6930                 next_scb->hscb_map = hscb_map;
6931                 next_scb->sg_map = sg_map;
6932                 next_scb->sense_map = sense_map;
6933                 next_scb->sg_list = segs;
6934                 next_scb->sense_data = sense_data;
6935                 next_scb->sense_busaddr = sense_busaddr;
6936                 memset(hscb, 0, sizeof(*hscb));
6937                 next_scb->hscb = hscb;
6938                 hscb->hscb_busaddr = ahd_htole32(hscb_busaddr);
6939
6940                 /*
6941                  * The sequencer always starts with the second entry.
6942                  * The first entry is embedded in the scb.
6943                  */
6944                 next_scb->sg_list_busaddr = sg_busaddr;
6945                 if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0)
6946                         next_scb->sg_list_busaddr
6947                             += sizeof(struct ahd_dma64_seg);
6948                 else
6949                         next_scb->sg_list_busaddr += sizeof(struct ahd_dma_seg);
6950                 next_scb->ahd_softc = ahd;
6951                 next_scb->flags = SCB_FLAG_NONE;
6952 #ifndef __linux__
6953                 error = ahd_dmamap_create(ahd, ahd->buffer_dmat, /*flags*/0,
6954                                           &next_scb->dmamap);
6955                 if (error != 0) {
6956                         free(next_scb, M_DEVBUF);
6957                         free(pdata, M_DEVBUF);
6958                         break;
6959                 }
6960 #endif
6961                 next_scb->hscb->tag = ahd_htole16(scb_data->numscbs);
6962                 col_tag = scb_data->numscbs ^ 0x100;
6963                 next_scb->col_scb = ahd_find_scb_by_tag(ahd, col_tag);
6964                 if (next_scb->col_scb != NULL)
6965                         next_scb->col_scb->col_scb = next_scb;
6966                 ahd_free_scb(ahd, next_scb);
6967                 hscb++;
6968                 hscb_busaddr += sizeof(*hscb);
6969                 segs += ahd_sglist_size(ahd);
6970                 sg_busaddr += ahd_sglist_size(ahd);
6971                 sense_data += AHD_SENSE_BUFSIZE;
6972                 sense_busaddr += AHD_SENSE_BUFSIZE;
6973                 scb_data->numscbs++;
6974                 scb_data->sense_left--;
6975                 scb_data->scbs_left--;
6976                 scb_data->sgs_left--;
6977         }
6978 }
6979
6980 void
6981 ahd_controller_info(struct ahd_softc *ahd, char *buf)
6982 {
6983         const char *speed;
6984         const char *type;
6985         int len;
6986
6987         len = sprintf(buf, "%s: ", ahd_chip_names[ahd->chip & AHD_CHIPID_MASK]);
6988         buf += len;
6989
6990         speed = "Ultra320 ";
6991         if ((ahd->features & AHD_WIDE) != 0) {
6992                 type = "Wide ";
6993         } else {
6994                 type = "Single ";
6995         }
6996         len = sprintf(buf, "%s%sChannel %c, SCSI Id=%d, ",
6997                       speed, type, ahd->channel, ahd->our_id);
6998         buf += len;
6999
7000         sprintf(buf, "%s, %d SCBs", ahd->bus_description,
7001                 ahd->scb_data.maxhscbs);
7002 }
7003
7004 static const char *channel_strings[] = {
7005         "Primary Low",
7006         "Primary High",
7007         "Secondary Low", 
7008         "Secondary High"
7009 };
7010
7011 static const char *termstat_strings[] = {
7012         "Terminated Correctly",
7013         "Over Terminated",
7014         "Under Terminated",
7015         "Not Configured"
7016 };
7017
7018 /***************************** Timer Facilities *******************************/
7019 #define ahd_timer_init init_timer
7020 #define ahd_timer_stop del_timer_sync
7021 typedef void ahd_linux_callback_t (u_long);
7022
7023 static void
7024 ahd_timer_reset(ahd_timer_t *timer, int usec, ahd_callback_t *func, void *arg)
7025 {
7026         struct ahd_softc *ahd;
7027
7028         ahd = (struct ahd_softc *)arg;
7029         del_timer(timer);
7030         timer->data = (u_long)arg;
7031         timer->expires = jiffies + (usec * HZ)/1000000;
7032         timer->function = (ahd_linux_callback_t*)func;
7033         add_timer(timer);
7034 }
7035
7036 /*
7037  * Start the board, ready for normal operation
7038  */
7039 int
7040 ahd_init(struct ahd_softc *ahd)
7041 {
7042         uint8_t         *next_vaddr;
7043         dma_addr_t       next_baddr;
7044         size_t           driver_data_size;
7045         int              i;
7046         int              error;
7047         u_int            warn_user;
7048         uint8_t          current_sensing;
7049         uint8_t          fstat;
7050
7051         AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
7052
7053         ahd->stack_size = ahd_probe_stack_size(ahd);
7054         ahd->saved_stack = malloc(ahd->stack_size * sizeof(uint16_t),
7055                                   M_DEVBUF, M_NOWAIT);
7056         if (ahd->saved_stack == NULL)
7057                 return (ENOMEM);
7058
7059         /*
7060          * Verify that the compiler hasn't over-agressively
7061          * padded important structures.
7062          */
7063         if (sizeof(struct hardware_scb) != 64)
7064                 panic("Hardware SCB size is incorrect");
7065
7066 #ifdef AHD_DEBUG
7067         if ((ahd_debug & AHD_DEBUG_SEQUENCER) != 0)
7068                 ahd->flags |= AHD_SEQUENCER_DEBUG;
7069 #endif
7070
7071         /*
7072          * Default to allowing initiator operations.
7073          */
7074         ahd->flags |= AHD_INITIATORROLE;
7075
7076         /*
7077          * Only allow target mode features if this unit has them enabled.
7078          */
7079         if ((AHD_TMODE_ENABLE & (0x1 << ahd->unit)) == 0)
7080                 ahd->features &= ~AHD_TARGETMODE;
7081
7082 #ifndef __linux__
7083         /* DMA tag for mapping buffers into device visible space. */
7084         if (ahd_dma_tag_create(ahd, ahd->parent_dmat, /*alignment*/1,
7085                                /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
7086                                /*lowaddr*/ahd->flags & AHD_39BIT_ADDRESSING
7087                                         ? (dma_addr_t)0x7FFFFFFFFFULL
7088                                         : BUS_SPACE_MAXADDR_32BIT,
7089                                /*highaddr*/BUS_SPACE_MAXADDR,
7090                                /*filter*/NULL, /*filterarg*/NULL,
7091                                /*maxsize*/(AHD_NSEG - 1) * PAGE_SIZE,
7092                                /*nsegments*/AHD_NSEG,
7093                                /*maxsegsz*/AHD_MAXTRANSFER_SIZE,
7094                                /*flags*/BUS_DMA_ALLOCNOW,
7095                                &ahd->buffer_dmat) != 0) {
7096                 return (ENOMEM);
7097         }
7098 #endif
7099
7100         ahd->init_level++;
7101
7102         /*
7103          * DMA tag for our command fifos and other data in system memory
7104          * the card's sequencer must be able to access.  For initiator
7105          * roles, we need to allocate space for the qoutfifo.  When providing
7106          * for the target mode role, we must additionally provide space for
7107          * the incoming target command fifo.
7108          */
7109         driver_data_size = AHD_SCB_MAX * sizeof(*ahd->qoutfifo)
7110                          + sizeof(struct hardware_scb);
7111         if ((ahd->features & AHD_TARGETMODE) != 0)
7112                 driver_data_size += AHD_TMODE_CMDS * sizeof(struct target_cmd);
7113         if ((ahd->bugs & AHD_PKT_BITBUCKET_BUG) != 0)
7114                 driver_data_size += PKT_OVERRUN_BUFSIZE;
7115         if (ahd_dma_tag_create(ahd, ahd->parent_dmat, /*alignment*/1,
7116                                /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
7117                                /*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
7118                                /*highaddr*/BUS_SPACE_MAXADDR,
7119                                /*filter*/NULL, /*filterarg*/NULL,
7120                                driver_data_size,
7121                                /*nsegments*/1,
7122                                /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
7123                                /*flags*/0, &ahd->shared_data_dmat) != 0) {
7124                 return (ENOMEM);
7125         }
7126
7127         ahd->init_level++;
7128
7129         /* Allocation of driver data */
7130         if (ahd_dmamem_alloc(ahd, ahd->shared_data_dmat,
7131                              (void **)&ahd->shared_data_map.vaddr,
7132                              BUS_DMA_NOWAIT,
7133                              &ahd->shared_data_map.dmamap) != 0) {
7134                 return (ENOMEM);
7135         }
7136
7137         ahd->init_level++;
7138
7139         /* And permanently map it in */
7140         ahd_dmamap_load(ahd, ahd->shared_data_dmat, ahd->shared_data_map.dmamap,
7141                         ahd->shared_data_map.vaddr, driver_data_size,
7142                         ahd_dmamap_cb, &ahd->shared_data_map.physaddr,
7143                         /*flags*/0);
7144         ahd->qoutfifo = (struct ahd_completion *)ahd->shared_data_map.vaddr;
7145         next_vaddr = (uint8_t *)&ahd->qoutfifo[AHD_QOUT_SIZE];
7146         next_baddr = ahd->shared_data_map.physaddr
7147                    + AHD_QOUT_SIZE*sizeof(struct ahd_completion);
7148         if ((ahd->features & AHD_TARGETMODE) != 0) {
7149                 ahd->targetcmds = (struct target_cmd *)next_vaddr;
7150                 next_vaddr += AHD_TMODE_CMDS * sizeof(struct target_cmd);
7151                 next_baddr += AHD_TMODE_CMDS * sizeof(struct target_cmd);
7152         }
7153
7154         if ((ahd->bugs & AHD_PKT_BITBUCKET_BUG) != 0) {
7155                 ahd->overrun_buf = next_vaddr;
7156                 next_vaddr += PKT_OVERRUN_BUFSIZE;
7157                 next_baddr += PKT_OVERRUN_BUFSIZE;
7158         }
7159
7160         /*
7161          * We need one SCB to serve as the "next SCB".  Since the
7162          * tag identifier in this SCB will never be used, there is
7163          * no point in using a valid HSCB tag from an SCB pulled from
7164          * the standard free pool.  So, we allocate this "sentinel"
7165          * specially from the DMA safe memory chunk used for the QOUTFIFO.
7166          */
7167         ahd->next_queued_hscb = (struct hardware_scb *)next_vaddr;
7168         ahd->next_queued_hscb_map = &ahd->shared_data_map;
7169         ahd->next_queued_hscb->hscb_busaddr = ahd_htole32(next_baddr);
7170
7171         ahd->init_level++;
7172
7173         /* Allocate SCB data now that buffer_dmat is initialized */
7174         if (ahd_init_scbdata(ahd) != 0)
7175                 return (ENOMEM);
7176
7177         if ((ahd->flags & AHD_INITIATORROLE) == 0)
7178                 ahd->flags &= ~AHD_RESET_BUS_A;
7179
7180         /*
7181          * Before committing these settings to the chip, give
7182          * the OSM one last chance to modify our configuration.
7183          */
7184         ahd_platform_init(ahd);
7185
7186         /* Bring up the chip. */
7187         ahd_chip_init(ahd);
7188
7189         AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
7190
7191         if ((ahd->flags & AHD_CURRENT_SENSING) == 0)
7192                 goto init_done;
7193
7194         /*
7195          * Verify termination based on current draw and
7196          * warn user if the bus is over/under terminated.
7197          */
7198         error = ahd_write_flexport(ahd, FLXADDR_ROMSTAT_CURSENSECTL,
7199                                    CURSENSE_ENB);
7200         if (error != 0) {
7201                 printf("%s: current sensing timeout 1\n", ahd_name(ahd));
7202                 goto init_done;
7203         }
7204         for (i = 20, fstat = FLX_FSTAT_BUSY;
7205              (fstat & FLX_FSTAT_BUSY) != 0 && i; i--) {
7206                 error = ahd_read_flexport(ahd, FLXADDR_FLEXSTAT, &fstat);
7207                 if (error != 0) {
7208                         printf("%s: current sensing timeout 2\n",
7209                                ahd_name(ahd));
7210                         goto init_done;
7211                 }
7212         }
7213         if (i == 0) {
7214                 printf("%s: Timedout during current-sensing test\n",
7215                        ahd_name(ahd));
7216                 goto init_done;
7217         }
7218
7219         /* Latch Current Sensing status. */
7220         error = ahd_read_flexport(ahd, FLXADDR_CURRENT_STAT, &current_sensing);
7221         if (error != 0) {
7222                 printf("%s: current sensing timeout 3\n", ahd_name(ahd));
7223                 goto init_done;
7224         }
7225
7226         /* Diable current sensing. */
7227         ahd_write_flexport(ahd, FLXADDR_ROMSTAT_CURSENSECTL, 0);
7228
7229 #ifdef AHD_DEBUG
7230         if ((ahd_debug & AHD_SHOW_TERMCTL) != 0) {
7231                 printf("%s: current_sensing == 0x%x\n",
7232                        ahd_name(ahd), current_sensing);
7233         }
7234 #endif
7235         warn_user = 0;
7236         for (i = 0; i < 4; i++, current_sensing >>= FLX_CSTAT_SHIFT) {
7237                 u_int term_stat;
7238
7239                 term_stat = (current_sensing & FLX_CSTAT_MASK);
7240                 switch (term_stat) {
7241                 case FLX_CSTAT_OVER:
7242                 case FLX_CSTAT_UNDER:
7243                         warn_user++;
7244                 case FLX_CSTAT_INVALID:
7245                 case FLX_CSTAT_OKAY:
7246                         if (warn_user == 0 && bootverbose == 0)
7247                                 break;
7248                         printf("%s: %s Channel %s\n", ahd_name(ahd),
7249                                channel_strings[i], termstat_strings[term_stat]);
7250                         break;
7251                 }
7252         }
7253         if (warn_user) {
7254                 printf("%s: WARNING. Termination is not configured correctly.\n"
7255                        "%s: WARNING. SCSI bus operations may FAIL.\n",
7256                        ahd_name(ahd), ahd_name(ahd));
7257         }
7258 init_done:
7259         ahd_restart(ahd);
7260         ahd_timer_reset(&ahd->stat_timer, AHD_STAT_UPDATE_US,
7261                         ahd_stat_timer, ahd);
7262         return (0);
7263 }
7264
7265 /*
7266  * (Re)initialize chip state after a chip reset.
7267  */
7268 static void
7269 ahd_chip_init(struct ahd_softc *ahd)
7270 {
7271         uint32_t busaddr;
7272         u_int    sxfrctl1;
7273         u_int    scsiseq_template;
7274         u_int    wait;
7275         u_int    i;
7276         u_int    target;
7277
7278         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
7279         /*
7280          * Take the LED out of diagnostic mode
7281          */
7282         ahd_outb(ahd, SBLKCTL, ahd_inb(ahd, SBLKCTL) & ~(DIAGLEDEN|DIAGLEDON));
7283
7284         /*
7285          * Return HS_MAILBOX to its default value.
7286          */
7287         ahd->hs_mailbox = 0;
7288         ahd_outb(ahd, HS_MAILBOX, 0);
7289
7290         /* Set the SCSI Id, SXFRCTL0, SXFRCTL1, and SIMODE1. */
7291         ahd_outb(ahd, IOWNID, ahd->our_id);
7292         ahd_outb(ahd, TOWNID, ahd->our_id);
7293         sxfrctl1 = (ahd->flags & AHD_TERM_ENB_A) != 0 ? STPWEN : 0;
7294         sxfrctl1 |= (ahd->flags & AHD_SPCHK_ENB_A) != 0 ? ENSPCHK : 0;
7295         if ((ahd->bugs & AHD_LONG_SETIMO_BUG)
7296          && (ahd->seltime != STIMESEL_MIN)) {
7297                 /*
7298                  * The selection timer duration is twice as long
7299                  * as it should be.  Halve it by adding "1" to
7300                  * the user specified setting.
7301                  */
7302                 sxfrctl1 |= ahd->seltime + STIMESEL_BUG_ADJ;
7303         } else {
7304                 sxfrctl1 |= ahd->seltime;
7305         }
7306                 
7307         ahd_outb(ahd, SXFRCTL0, DFON);
7308         ahd_outb(ahd, SXFRCTL1, sxfrctl1|ahd->seltime|ENSTIMER|ACTNEGEN);
7309         ahd_outb(ahd, SIMODE1, ENSELTIMO|ENSCSIRST|ENSCSIPERR);
7310
7311         /*
7312          * Now that termination is set, wait for up
7313          * to 500ms for our transceivers to settle.  If
7314          * the adapter does not have a cable attached,
7315          * the transceivers may never settle, so don't
7316          * complain if we fail here.
7317          */
7318         for (wait = 10000;
7319              (ahd_inb(ahd, SBLKCTL) & (ENAB40|ENAB20)) == 0 && wait;
7320              wait--)
7321                 ahd_delay(100);
7322
7323         /* Clear any false bus resets due to the transceivers settling */
7324         ahd_outb(ahd, CLRSINT1, CLRSCSIRSTI);
7325         ahd_outb(ahd, CLRINT, CLRSCSIINT);
7326
7327         /* Initialize mode specific S/G state. */
7328         for (i = 0; i < 2; i++) {
7329                 ahd_set_modes(ahd, AHD_MODE_DFF0 + i, AHD_MODE_DFF0 + i);
7330                 ahd_outb(ahd, LONGJMP_ADDR + 1, INVALID_ADDR);
7331                 ahd_outb(ahd, SG_STATE, 0);
7332                 ahd_outb(ahd, CLRSEQINTSRC, 0xFF);
7333                 ahd_outb(ahd, SEQIMODE,
7334                          ENSAVEPTRS|ENCFG4DATA|ENCFG4ISTAT
7335                         |ENCFG4TSTAT|ENCFG4ICMD|ENCFG4TCMD);
7336         }
7337
7338         ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
7339         ahd_outb(ahd, DSCOMMAND0, ahd_inb(ahd, DSCOMMAND0)|MPARCKEN|CACHETHEN);
7340         ahd_outb(ahd, DFF_THRSH, RD_DFTHRSH_75|WR_DFTHRSH_75);
7341         ahd_outb(ahd, SIMODE0, ENIOERR|ENOVERRUN);
7342         ahd_outb(ahd, SIMODE3, ENNTRAMPERR|ENOSRAMPERR);
7343         if ((ahd->bugs & AHD_BUSFREEREV_BUG) != 0) {
7344                 ahd_outb(ahd, OPTIONMODE, AUTOACKEN|AUTO_MSGOUT_DE);
7345         } else {
7346                 ahd_outb(ahd, OPTIONMODE, AUTOACKEN|BUSFREEREV|AUTO_MSGOUT_DE);
7347         }
7348         ahd_outb(ahd, SCSCHKN, CURRFIFODEF|WIDERESEN|SHVALIDSTDIS);
7349         if ((ahd->chip & AHD_BUS_MASK) == AHD_PCIX)
7350                 /*
7351                  * Do not issue a target abort when a split completion
7352                  * error occurs.  Let our PCIX interrupt handler deal
7353                  * with it instead. H2A4 Razor #625
7354                  */
7355                 ahd_outb(ahd, PCIXCTL, ahd_inb(ahd, PCIXCTL) | SPLTSTADIS);
7356
7357         if ((ahd->bugs & AHD_LQOOVERRUN_BUG) != 0)
7358                 ahd_outb(ahd, LQOSCSCTL, LQONOCHKOVER);
7359
7360         /*
7361          * Tweak IOCELL settings.
7362          */
7363         if ((ahd->flags & AHD_HP_BOARD) != 0) {
7364                 for (i = 0; i < NUMDSPS; i++) {
7365                         ahd_outb(ahd, DSPSELECT, i);
7366                         ahd_outb(ahd, WRTBIASCTL, WRTBIASCTL_HP_DEFAULT);
7367                 }
7368 #ifdef AHD_DEBUG
7369                 if ((ahd_debug & AHD_SHOW_MISC) != 0)
7370                         printf("%s: WRTBIASCTL now 0x%x\n", ahd_name(ahd),
7371                                WRTBIASCTL_HP_DEFAULT);
7372 #endif
7373         }
7374         ahd_setup_iocell_workaround(ahd);
7375
7376         /*
7377          * Enable LQI Manager interrupts.
7378          */
7379         ahd_outb(ahd, LQIMODE1, ENLQIPHASE_LQ|ENLQIPHASE_NLQ|ENLIQABORT
7380                               | ENLQICRCI_LQ|ENLQICRCI_NLQ|ENLQIBADLQI
7381                               | ENLQIOVERI_LQ|ENLQIOVERI_NLQ);
7382         ahd_outb(ahd, LQOMODE0, ENLQOATNLQ|ENLQOATNPKT|ENLQOTCRC);
7383         /*
7384          * We choose to have the sequencer catch LQOPHCHGINPKT errors
7385          * manually for the command phase at the start of a packetized
7386          * selection case.  ENLQOBUSFREE should be made redundant by
7387          * the BUSFREE interrupt, but it seems that some LQOBUSFREE
7388          * events fail to assert the BUSFREE interrupt so we must
7389          * also enable LQOBUSFREE interrupts.
7390          */
7391         ahd_outb(ahd, LQOMODE1, ENLQOBUSFREE);
7392
7393         /*
7394          * Setup sequencer interrupt handlers.
7395          */
7396         ahd_outw(ahd, INTVEC1_ADDR, ahd_resolve_seqaddr(ahd, LABEL_seq_isr));
7397         ahd_outw(ahd, INTVEC2_ADDR, ahd_resolve_seqaddr(ahd, LABEL_timer_isr));
7398
7399         /*
7400          * Setup SCB Offset registers.
7401          */
7402         if ((ahd->bugs & AHD_PKT_LUN_BUG) != 0) {
7403                 ahd_outb(ahd, LUNPTR, offsetof(struct hardware_scb,
7404                          pkt_long_lun));
7405         } else {
7406                 ahd_outb(ahd, LUNPTR, offsetof(struct hardware_scb, lun));
7407         }
7408         ahd_outb(ahd, CMDLENPTR, offsetof(struct hardware_scb, cdb_len));
7409         ahd_outb(ahd, ATTRPTR, offsetof(struct hardware_scb, task_attribute));
7410         ahd_outb(ahd, FLAGPTR, offsetof(struct hardware_scb, task_management));
7411         ahd_outb(ahd, CMDPTR, offsetof(struct hardware_scb,
7412                                        shared_data.idata.cdb));
7413         ahd_outb(ahd, QNEXTPTR,
7414                  offsetof(struct hardware_scb, next_hscb_busaddr));
7415         ahd_outb(ahd, ABRTBITPTR, MK_MESSAGE_BIT_OFFSET);
7416         ahd_outb(ahd, ABRTBYTEPTR, offsetof(struct hardware_scb, control));
7417         if ((ahd->bugs & AHD_PKT_LUN_BUG) != 0) {
7418                 ahd_outb(ahd, LUNLEN,
7419                          sizeof(ahd->next_queued_hscb->pkt_long_lun) - 1);
7420         } else {
7421                 ahd_outb(ahd, LUNLEN, LUNLEN_SINGLE_LEVEL_LUN);
7422         }
7423         ahd_outb(ahd, CDBLIMIT, SCB_CDB_LEN_PTR - 1);
7424         ahd_outb(ahd, MAXCMD, 0xFF);
7425         ahd_outb(ahd, SCBAUTOPTR,
7426                  AUSCBPTR_EN | offsetof(struct hardware_scb, tag));
7427
7428         /* We haven't been enabled for target mode yet. */
7429         ahd_outb(ahd, MULTARGID, 0);
7430         ahd_outb(ahd, MULTARGID + 1, 0);
7431
7432         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
7433         /* Initialize the negotiation table. */
7434         if ((ahd->features & AHD_NEW_IOCELL_OPTS) == 0) {
7435                 /*
7436                  * Clear the spare bytes in the neg table to avoid
7437                  * spurious parity errors.
7438                  */
7439                 for (target = 0; target < AHD_NUM_TARGETS; target++) {
7440                         ahd_outb(ahd, NEGOADDR, target);
7441                         ahd_outb(ahd, ANNEXCOL, AHD_ANNEXCOL_PER_DEV0);
7442                         for (i = 0; i < AHD_NUM_PER_DEV_ANNEXCOLS; i++)
7443                                 ahd_outb(ahd, ANNEXDAT, 0);
7444                 }
7445         }
7446         for (target = 0; target < AHD_NUM_TARGETS; target++) {
7447                 struct   ahd_devinfo devinfo;
7448                 struct   ahd_initiator_tinfo *tinfo;
7449                 struct   ahd_tmode_tstate *tstate;
7450
7451                 tinfo = ahd_fetch_transinfo(ahd, 'A', ahd->our_id,
7452                                             target, &tstate);
7453                 ahd_compile_devinfo(&devinfo, ahd->our_id,
7454                                     target, CAM_LUN_WILDCARD,
7455                                     'A', ROLE_INITIATOR);
7456                 ahd_update_neg_table(ahd, &devinfo, &tinfo->curr);
7457         }
7458
7459         ahd_outb(ahd, CLRSINT3, NTRAMPERR|OSRAMPERR);
7460         ahd_outb(ahd, CLRINT, CLRSCSIINT);
7461
7462 #ifdef NEEDS_MORE_TESTING
7463         /*
7464          * Always enable abort on incoming L_Qs if this feature is
7465          * supported.  We use this to catch invalid SCB references.
7466          */
7467         if ((ahd->bugs & AHD_ABORT_LQI_BUG) == 0)
7468                 ahd_outb(ahd, LQCTL1, ABORTPENDING);
7469         else
7470 #endif
7471                 ahd_outb(ahd, LQCTL1, 0);
7472
7473         /* All of our queues are empty */
7474         ahd->qoutfifonext = 0;
7475         ahd->qoutfifonext_valid_tag = QOUTFIFO_ENTRY_VALID;
7476         ahd_outb(ahd, QOUTFIFO_ENTRY_VALID_TAG, QOUTFIFO_ENTRY_VALID);
7477         for (i = 0; i < AHD_QOUT_SIZE; i++)
7478                 ahd->qoutfifo[i].valid_tag = 0;
7479         ahd_sync_qoutfifo(ahd, BUS_DMASYNC_PREREAD);
7480
7481         ahd->qinfifonext = 0;
7482         for (i = 0; i < AHD_QIN_SIZE; i++)
7483                 ahd->qinfifo[i] = SCB_LIST_NULL;
7484
7485         if ((ahd->features & AHD_TARGETMODE) != 0) {
7486                 /* All target command blocks start out invalid. */
7487                 for (i = 0; i < AHD_TMODE_CMDS; i++)
7488                         ahd->targetcmds[i].cmd_valid = 0;
7489                 ahd_sync_tqinfifo(ahd, BUS_DMASYNC_PREREAD);
7490                 ahd->tqinfifonext = 1;
7491                 ahd_outb(ahd, KERNEL_TQINPOS, ahd->tqinfifonext - 1);
7492                 ahd_outb(ahd, TQINPOS, ahd->tqinfifonext);
7493         }
7494
7495         /* Initialize Scratch Ram. */
7496         ahd_outb(ahd, SEQ_FLAGS, 0);
7497         ahd_outb(ahd, SEQ_FLAGS2, 0);
7498
7499         /* We don't have any waiting selections */
7500         ahd_outw(ahd, WAITING_TID_HEAD, SCB_LIST_NULL);
7501         ahd_outw(ahd, WAITING_TID_TAIL, SCB_LIST_NULL);
7502         ahd_outw(ahd, MK_MESSAGE_SCB, SCB_LIST_NULL);
7503         ahd_outw(ahd, MK_MESSAGE_SCSIID, 0xFF);
7504         for (i = 0; i < AHD_NUM_TARGETS; i++)
7505                 ahd_outw(ahd, WAITING_SCB_TAILS + (2 * i), SCB_LIST_NULL);
7506
7507         /*
7508          * Nobody is waiting to be DMAed into the QOUTFIFO.
7509          */
7510         ahd_outw(ahd, COMPLETE_SCB_HEAD, SCB_LIST_NULL);
7511         ahd_outw(ahd, COMPLETE_SCB_DMAINPROG_HEAD, SCB_LIST_NULL);
7512         ahd_outw(ahd, COMPLETE_DMA_SCB_HEAD, SCB_LIST_NULL);
7513         ahd_outw(ahd, COMPLETE_DMA_SCB_TAIL, SCB_LIST_NULL);
7514         ahd_outw(ahd, COMPLETE_ON_QFREEZE_HEAD, SCB_LIST_NULL);
7515
7516         /*
7517          * The Freeze Count is 0.
7518          */
7519         ahd->qfreeze_cnt = 0;
7520         ahd_outw(ahd, QFREEZE_COUNT, 0);
7521         ahd_outw(ahd, KERNEL_QFREEZE_COUNT, 0);
7522
7523         /*
7524          * Tell the sequencer where it can find our arrays in memory.
7525          */
7526         busaddr = ahd->shared_data_map.physaddr;
7527         ahd_outl(ahd, SHARED_DATA_ADDR, busaddr);
7528         ahd_outl(ahd, QOUTFIFO_NEXT_ADDR, busaddr);
7529
7530         /*
7531          * Setup the allowed SCSI Sequences based on operational mode.
7532          * If we are a target, we'll enable select in operations once
7533          * we've had a lun enabled.
7534          */
7535         scsiseq_template = ENAUTOATNP;
7536         if ((ahd->flags & AHD_INITIATORROLE) != 0)
7537                 scsiseq_template |= ENRSELI;
7538         ahd_outb(ahd, SCSISEQ_TEMPLATE, scsiseq_template);
7539
7540         /* There are no busy SCBs yet. */
7541         for (target = 0; target < AHD_NUM_TARGETS; target++) {
7542                 int lun;
7543
7544                 for (lun = 0; lun < AHD_NUM_LUNS_NONPKT; lun++)
7545                         ahd_unbusy_tcl(ahd, BUILD_TCL_RAW(target, 'A', lun));
7546         }
7547
7548         /*
7549          * Initialize the group code to command length table.
7550          * Vendor Unique codes are set to 0 so we only capture
7551          * the first byte of the cdb.  These can be overridden
7552          * when target mode is enabled.
7553          */
7554         ahd_outb(ahd, CMDSIZE_TABLE, 5);
7555         ahd_outb(ahd, CMDSIZE_TABLE + 1, 9);
7556         ahd_outb(ahd, CMDSIZE_TABLE + 2, 9);
7557         ahd_outb(ahd, CMDSIZE_TABLE + 3, 0);
7558         ahd_outb(ahd, CMDSIZE_TABLE + 4, 15);
7559         ahd_outb(ahd, CMDSIZE_TABLE + 5, 11);
7560         ahd_outb(ahd, CMDSIZE_TABLE + 6, 0);
7561         ahd_outb(ahd, CMDSIZE_TABLE + 7, 0);
7562                 
7563         /* Tell the sequencer of our initial queue positions */
7564         ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
7565         ahd_outb(ahd, QOFF_CTLSTA, SCB_QSIZE_512);
7566         ahd->qinfifonext = 0;
7567         ahd_set_hnscb_qoff(ahd, ahd->qinfifonext);
7568         ahd_set_hescb_qoff(ahd, 0);
7569         ahd_set_snscb_qoff(ahd, 0);
7570         ahd_set_sescb_qoff(ahd, 0);
7571         ahd_set_sdscb_qoff(ahd, 0);
7572
7573         /*
7574          * Tell the sequencer which SCB will be the next one it receives.
7575          */
7576         busaddr = ahd_le32toh(ahd->next_queued_hscb->hscb_busaddr);
7577         ahd_outl(ahd, NEXT_QUEUED_SCB_ADDR, busaddr);
7578
7579         /*
7580          * Default to coalescing disabled.
7581          */
7582         ahd_outw(ahd, INT_COALESCING_CMDCOUNT, 0);
7583         ahd_outw(ahd, CMDS_PENDING, 0);
7584         ahd_update_coalescing_values(ahd, ahd->int_coalescing_timer,
7585                                      ahd->int_coalescing_maxcmds,
7586                                      ahd->int_coalescing_mincmds);
7587         ahd_enable_coalescing(ahd, FALSE);
7588
7589         ahd_loadseq(ahd);
7590         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
7591
7592         if (ahd->features & AHD_AIC79XXB_SLOWCRC) {
7593                 u_int negodat3 = ahd_inb(ahd, NEGCONOPTS);
7594
7595                 negodat3 |= ENSLOWCRC;
7596                 ahd_outb(ahd, NEGCONOPTS, negodat3);
7597                 negodat3 = ahd_inb(ahd, NEGCONOPTS);
7598                 if (!(negodat3 & ENSLOWCRC))
7599                         printf("aic79xx: failed to set the SLOWCRC bit\n");
7600                 else
7601                         printf("aic79xx: SLOWCRC bit set\n");
7602         }
7603 }
7604
7605 /*
7606  * Setup default device and controller settings.
7607  * This should only be called if our probe has
7608  * determined that no configuration data is available.
7609  */
7610 int
7611 ahd_default_config(struct ahd_softc *ahd)
7612 {
7613         int     targ;
7614
7615         ahd->our_id = 7;
7616
7617         /*
7618          * Allocate a tstate to house information for our
7619          * initiator presence on the bus as well as the user
7620          * data for any target mode initiator.
7621          */
7622         if (ahd_alloc_tstate(ahd, ahd->our_id, 'A') == NULL) {
7623                 printf("%s: unable to allocate ahd_tmode_tstate.  "
7624                        "Failing attach\n", ahd_name(ahd));
7625                 return (ENOMEM);
7626         }
7627
7628         for (targ = 0; targ < AHD_NUM_TARGETS; targ++) {
7629                 struct   ahd_devinfo devinfo;
7630                 struct   ahd_initiator_tinfo *tinfo;
7631                 struct   ahd_tmode_tstate *tstate;
7632                 uint16_t target_mask;
7633
7634                 tinfo = ahd_fetch_transinfo(ahd, 'A', ahd->our_id,
7635                                             targ, &tstate);
7636                 /*
7637                  * We support SPC2 and SPI4.
7638                  */
7639                 tinfo->user.protocol_version = 4;
7640                 tinfo->user.transport_version = 4;
7641
7642                 target_mask = 0x01 << targ;
7643                 ahd->user_discenable |= target_mask;
7644                 tstate->discenable |= target_mask;
7645                 ahd->user_tagenable |= target_mask;
7646 #ifdef AHD_FORCE_160
7647                 tinfo->user.period = AHD_SYNCRATE_DT;
7648 #else
7649                 tinfo->user.period = AHD_SYNCRATE_160;
7650 #endif
7651                 tinfo->user.offset = MAX_OFFSET;
7652                 tinfo->user.ppr_options = MSG_EXT_PPR_RD_STRM
7653                                         | MSG_EXT_PPR_WR_FLOW
7654                                         | MSG_EXT_PPR_HOLD_MCS
7655                                         | MSG_EXT_PPR_IU_REQ
7656                                         | MSG_EXT_PPR_QAS_REQ
7657                                         | MSG_EXT_PPR_DT_REQ;
7658                 if ((ahd->features & AHD_RTI) != 0)
7659                         tinfo->user.ppr_options |= MSG_EXT_PPR_RTI;
7660
7661                 tinfo->user.width = MSG_EXT_WDTR_BUS_16_BIT;
7662
7663                 /*
7664                  * Start out Async/Narrow/Untagged and with
7665                  * conservative protocol support.
7666                  */
7667                 tinfo->goal.protocol_version = 2;
7668                 tinfo->goal.transport_version = 2;
7669                 tinfo->curr.protocol_version = 2;
7670                 tinfo->curr.transport_version = 2;
7671                 ahd_compile_devinfo(&devinfo, ahd->our_id,
7672                                     targ, CAM_LUN_WILDCARD,
7673                                     'A', ROLE_INITIATOR);
7674                 tstate->tagenable &= ~target_mask;
7675                 ahd_set_width(ahd, &devinfo, MSG_EXT_WDTR_BUS_8_BIT,
7676                               AHD_TRANS_CUR|AHD_TRANS_GOAL, /*paused*/TRUE);
7677                 ahd_set_syncrate(ahd, &devinfo, /*period*/0, /*offset*/0,
7678                                  /*ppr_options*/0, AHD_TRANS_CUR|AHD_TRANS_GOAL,
7679                                  /*paused*/TRUE);
7680         }
7681         return (0);
7682 }
7683
7684 /*
7685  * Parse device configuration information.
7686  */
7687 int
7688 ahd_parse_cfgdata(struct ahd_softc *ahd, struct seeprom_config *sc)
7689 {
7690         int targ;
7691         int max_targ;
7692
7693         max_targ = sc->max_targets & CFMAXTARG;
7694         ahd->our_id = sc->brtime_id & CFSCSIID;
7695
7696         /*
7697          * Allocate a tstate to house information for our
7698          * initiator presence on the bus as well as the user
7699          * data for any target mode initiator.
7700          */
7701         if (ahd_alloc_tstate(ahd, ahd->our_id, 'A') == NULL) {
7702                 printf("%s: unable to allocate ahd_tmode_tstate.  "
7703                        "Failing attach\n", ahd_name(ahd));
7704                 return (ENOMEM);
7705         }
7706
7707         for (targ = 0; targ < max_targ; targ++) {
7708                 struct   ahd_devinfo devinfo;
7709                 struct   ahd_initiator_tinfo *tinfo;
7710                 struct   ahd_transinfo *user_tinfo;
7711                 struct   ahd_tmode_tstate *tstate;
7712                 uint16_t target_mask;
7713
7714                 tinfo = ahd_fetch_transinfo(ahd, 'A', ahd->our_id,
7715                                             targ, &tstate);
7716                 user_tinfo = &tinfo->user;
7717
7718                 /*
7719                  * We support SPC2 and SPI4.
7720                  */
7721                 tinfo->user.protocol_version = 4;
7722                 tinfo->user.transport_version = 4;
7723
7724                 target_mask = 0x01 << targ;
7725                 ahd->user_discenable &= ~target_mask;
7726                 tstate->discenable &= ~target_mask;
7727                 ahd->user_tagenable &= ~target_mask;
7728                 if (sc->device_flags[targ] & CFDISC) {
7729                         tstate->discenable |= target_mask;
7730                         ahd->user_discenable |= target_mask;
7731                         ahd->user_tagenable |= target_mask;
7732                 } else {
7733                         /*
7734                          * Cannot be packetized without disconnection.
7735                          */
7736                         sc->device_flags[targ] &= ~CFPACKETIZED;
7737                 }
7738
7739                 user_tinfo->ppr_options = 0;
7740                 user_tinfo->period = (sc->device_flags[targ] & CFXFER);
7741                 if (user_tinfo->period < CFXFER_ASYNC) {
7742                         if (user_tinfo->period <= AHD_PERIOD_10MHz)
7743                                 user_tinfo->ppr_options |= MSG_EXT_PPR_DT_REQ;
7744                         user_tinfo->offset = MAX_OFFSET;
7745                 } else  {
7746                         user_tinfo->offset = 0;
7747                         user_tinfo->period = AHD_ASYNC_XFER_PERIOD;
7748                 }
7749 #ifdef AHD_FORCE_160
7750                 if (user_tinfo->period <= AHD_SYNCRATE_160)
7751                         user_tinfo->period = AHD_SYNCRATE_DT;
7752 #endif
7753
7754                 if ((sc->device_flags[targ] & CFPACKETIZED) != 0) {
7755                         user_tinfo->ppr_options |= MSG_EXT_PPR_RD_STRM
7756                                                 |  MSG_EXT_PPR_WR_FLOW
7757                                                 |  MSG_EXT_PPR_HOLD_MCS
7758                                                 |  MSG_EXT_PPR_IU_REQ;
7759                         if ((ahd->features & AHD_RTI) != 0)
7760                                 user_tinfo->ppr_options |= MSG_EXT_PPR_RTI;
7761                 }
7762
7763                 if ((sc->device_flags[targ] & CFQAS) != 0)
7764                         user_tinfo->ppr_options |= MSG_EXT_PPR_QAS_REQ;
7765
7766                 if ((sc->device_flags[targ] & CFWIDEB) != 0)
7767                         user_tinfo->width = MSG_EXT_WDTR_BUS_16_BIT;
7768                 else
7769                         user_tinfo->width = MSG_EXT_WDTR_BUS_8_BIT;
7770 #ifdef AHD_DEBUG
7771                 if ((ahd_debug & AHD_SHOW_MISC) != 0)
7772                         printf("(%d): %x:%x:%x:%x\n", targ, user_tinfo->width,
7773                                user_tinfo->period, user_tinfo->offset,
7774                                user_tinfo->ppr_options);
7775 #endif
7776                 /*
7777                  * Start out Async/Narrow/Untagged and with
7778                  * conservative protocol support.
7779                  */
7780                 tstate->tagenable &= ~target_mask;
7781                 tinfo->goal.protocol_version = 2;
7782                 tinfo->goal.transport_version = 2;
7783                 tinfo->curr.protocol_version = 2;
7784                 tinfo->curr.transport_version = 2;
7785                 ahd_compile_devinfo(&devinfo, ahd->our_id,
7786                                     targ, CAM_LUN_WILDCARD,
7787                                     'A', ROLE_INITIATOR);
7788                 ahd_set_width(ahd, &devinfo, MSG_EXT_WDTR_BUS_8_BIT,
7789                               AHD_TRANS_CUR|AHD_TRANS_GOAL, /*paused*/TRUE);
7790                 ahd_set_syncrate(ahd, &devinfo, /*period*/0, /*offset*/0,
7791                                  /*ppr_options*/0, AHD_TRANS_CUR|AHD_TRANS_GOAL,
7792                                  /*paused*/TRUE);
7793         }
7794
7795         ahd->flags &= ~AHD_SPCHK_ENB_A;
7796         if (sc->bios_control & CFSPARITY)
7797                 ahd->flags |= AHD_SPCHK_ENB_A;
7798
7799         ahd->flags &= ~AHD_RESET_BUS_A;
7800         if (sc->bios_control & CFRESETB)
7801                 ahd->flags |= AHD_RESET_BUS_A;
7802
7803         ahd->flags &= ~AHD_EXTENDED_TRANS_A;
7804         if (sc->bios_control & CFEXTEND)
7805                 ahd->flags |= AHD_EXTENDED_TRANS_A;
7806
7807         ahd->flags &= ~AHD_BIOS_ENABLED;
7808         if ((sc->bios_control & CFBIOSSTATE) == CFBS_ENABLED)
7809                 ahd->flags |= AHD_BIOS_ENABLED;
7810
7811         ahd->flags &= ~AHD_STPWLEVEL_A;
7812         if ((sc->adapter_control & CFSTPWLEVEL) != 0)
7813                 ahd->flags |= AHD_STPWLEVEL_A;
7814
7815         return (0);
7816 }
7817
7818 /*
7819  * Parse device configuration information.
7820  */
7821 int
7822 ahd_parse_vpddata(struct ahd_softc *ahd, struct vpd_config *vpd)
7823 {
7824         int error;
7825
7826         error = ahd_verify_vpd_cksum(vpd);
7827         if (error == 0)
7828                 return (EINVAL);
7829         if ((vpd->bios_flags & VPDBOOTHOST) != 0)
7830                 ahd->flags |= AHD_BOOT_CHANNEL;
7831         return (0);
7832 }
7833
7834 void
7835 ahd_intr_enable(struct ahd_softc *ahd, int enable)
7836 {
7837         u_int hcntrl;
7838
7839         hcntrl = ahd_inb(ahd, HCNTRL);
7840         hcntrl &= ~INTEN;
7841         ahd->pause &= ~INTEN;
7842         ahd->unpause &= ~INTEN;
7843         if (enable) {
7844                 hcntrl |= INTEN;
7845                 ahd->pause |= INTEN;
7846                 ahd->unpause |= INTEN;
7847         }
7848         ahd_outb(ahd, HCNTRL, hcntrl);
7849 }
7850
7851 static void
7852 ahd_update_coalescing_values(struct ahd_softc *ahd, u_int timer, u_int maxcmds,
7853                              u_int mincmds)
7854 {
7855         if (timer > AHD_TIMER_MAX_US)
7856                 timer = AHD_TIMER_MAX_US;
7857         ahd->int_coalescing_timer = timer;
7858
7859         if (maxcmds > AHD_INT_COALESCING_MAXCMDS_MAX)
7860                 maxcmds = AHD_INT_COALESCING_MAXCMDS_MAX;
7861         if (mincmds > AHD_INT_COALESCING_MINCMDS_MAX)
7862                 mincmds = AHD_INT_COALESCING_MINCMDS_MAX;
7863         ahd->int_coalescing_maxcmds = maxcmds;
7864         ahd_outw(ahd, INT_COALESCING_TIMER, timer / AHD_TIMER_US_PER_TICK);
7865         ahd_outb(ahd, INT_COALESCING_MAXCMDS, -maxcmds);
7866         ahd_outb(ahd, INT_COALESCING_MINCMDS, -mincmds);
7867 }
7868
7869 static void
7870 ahd_enable_coalescing(struct ahd_softc *ahd, int enable)
7871 {
7872
7873         ahd->hs_mailbox &= ~ENINT_COALESCE;
7874         if (enable)
7875                 ahd->hs_mailbox |= ENINT_COALESCE;
7876         ahd_outb(ahd, HS_MAILBOX, ahd->hs_mailbox);
7877         ahd_flush_device_writes(ahd);
7878         ahd_run_qoutfifo(ahd);
7879 }
7880
7881 /*
7882  * Ensure that the card is paused in a location
7883  * outside of all critical sections and that all
7884  * pending work is completed prior to returning.
7885  * This routine should only be called from outside
7886  * an interrupt context.
7887  */
7888 void
7889 ahd_pause_and_flushwork(struct ahd_softc *ahd)
7890 {
7891         u_int intstat;
7892         u_int maxloops;
7893
7894         maxloops = 1000;
7895         ahd->flags |= AHD_ALL_INTERRUPTS;
7896         ahd_pause(ahd);
7897         /*
7898          * Freeze the outgoing selections.  We do this only
7899          * until we are safely paused without further selections
7900          * pending.
7901          */
7902         ahd->qfreeze_cnt--;
7903         ahd_outw(ahd, KERNEL_QFREEZE_COUNT, ahd->qfreeze_cnt);
7904         ahd_outb(ahd, SEQ_FLAGS2, ahd_inb(ahd, SEQ_FLAGS2) | SELECTOUT_QFROZEN);
7905         do {
7906
7907                 ahd_unpause(ahd);
7908                 /*
7909                  * Give the sequencer some time to service
7910                  * any active selections.
7911                  */
7912                 ahd_delay(500);
7913
7914                 ahd_intr(ahd);
7915                 ahd_pause(ahd);
7916                 intstat = ahd_inb(ahd, INTSTAT);
7917                 if ((intstat & INT_PEND) == 0) {
7918                         ahd_clear_critical_section(ahd);
7919                         intstat = ahd_inb(ahd, INTSTAT);
7920                 }
7921         } while (--maxloops
7922               && (intstat != 0xFF || (ahd->features & AHD_REMOVABLE) == 0)
7923               && ((intstat & INT_PEND) != 0
7924                || (ahd_inb(ahd, SCSISEQ0) & ENSELO) != 0
7925                || (ahd_inb(ahd, SSTAT0) & (SELDO|SELINGO)) != 0));
7926
7927         if (maxloops == 0) {
7928                 printf("Infinite interrupt loop, INTSTAT = %x",
7929                       ahd_inb(ahd, INTSTAT));
7930         }
7931         ahd->qfreeze_cnt++;
7932         ahd_outw(ahd, KERNEL_QFREEZE_COUNT, ahd->qfreeze_cnt);
7933
7934         ahd_flush_qoutfifo(ahd);
7935
7936         ahd->flags &= ~AHD_ALL_INTERRUPTS;
7937 }
7938
7939 #ifdef CONFIG_PM
7940 int
7941 ahd_suspend(struct ahd_softc *ahd)
7942 {
7943
7944         ahd_pause_and_flushwork(ahd);
7945
7946         if (LIST_FIRST(&ahd->pending_scbs) != NULL) {
7947                 ahd_unpause(ahd);
7948                 return (EBUSY);
7949         }
7950         ahd_shutdown(ahd);
7951         return (0);
7952 }
7953
7954 void
7955 ahd_resume(struct ahd_softc *ahd)
7956 {
7957
7958         ahd_reset(ahd, /*reinit*/TRUE);
7959         ahd_intr_enable(ahd, TRUE); 
7960         ahd_restart(ahd);
7961 }
7962 #endif
7963
7964 /************************** Busy Target Table *********************************/
7965 /*
7966  * Set SCBPTR to the SCB that contains the busy
7967  * table entry for TCL.  Return the offset into
7968  * the SCB that contains the entry for TCL.
7969  * saved_scbid is dereferenced and set to the
7970  * scbid that should be restored once manipualtion
7971  * of the TCL entry is complete.
7972  */
7973 static __inline u_int
7974 ahd_index_busy_tcl(struct ahd_softc *ahd, u_int *saved_scbid, u_int tcl)
7975 {
7976         /*
7977          * Index to the SCB that contains the busy entry.
7978          */
7979         AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
7980         *saved_scbid = ahd_get_scbptr(ahd);
7981         ahd_set_scbptr(ahd, TCL_LUN(tcl)
7982                      | ((TCL_TARGET_OFFSET(tcl) & 0xC) << 4));
7983
7984         /*
7985          * And now calculate the SCB offset to the entry.
7986          * Each entry is 2 bytes wide, hence the
7987          * multiplication by 2.
7988          */
7989         return (((TCL_TARGET_OFFSET(tcl) & 0x3) << 1) + SCB_DISCONNECTED_LISTS);
7990 }
7991
7992 /*
7993  * Return the untagged transaction id for a given target/channel lun.
7994  */
7995 static u_int
7996 ahd_find_busy_tcl(struct ahd_softc *ahd, u_int tcl)
7997 {
7998         u_int scbid;
7999         u_int scb_offset;
8000         u_int saved_scbptr;
8001                 
8002         scb_offset = ahd_index_busy_tcl(ahd, &saved_scbptr, tcl);
8003         scbid = ahd_inw_scbram(ahd, scb_offset);
8004         ahd_set_scbptr(ahd, saved_scbptr);
8005         return (scbid);
8006 }
8007
8008 static void
8009 ahd_busy_tcl(struct ahd_softc *ahd, u_int tcl, u_int scbid)
8010 {
8011         u_int scb_offset;
8012         u_int saved_scbptr;
8013                 
8014         scb_offset = ahd_index_busy_tcl(ahd, &saved_scbptr, tcl);
8015         ahd_outw(ahd, scb_offset, scbid);
8016         ahd_set_scbptr(ahd, saved_scbptr);
8017 }
8018
8019 /************************** SCB and SCB queue management **********************/
8020 static int
8021 ahd_match_scb(struct ahd_softc *ahd, struct scb *scb, int target,
8022               char channel, int lun, u_int tag, role_t role)
8023 {
8024         int targ = SCB_GET_TARGET(ahd, scb);
8025         char chan = SCB_GET_CHANNEL(ahd, scb);
8026         int slun = SCB_GET_LUN(scb);
8027         int match;
8028
8029         match = ((chan == channel) || (channel == ALL_CHANNELS));
8030         if (match != 0)
8031                 match = ((targ == target) || (target == CAM_TARGET_WILDCARD));
8032         if (match != 0)
8033                 match = ((lun == slun) || (lun == CAM_LUN_WILDCARD));
8034         if (match != 0) {
8035 #ifdef AHD_TARGET_MODE
8036                 int group;
8037
8038                 group = XPT_FC_GROUP(scb->io_ctx->ccb_h.func_code);
8039                 if (role == ROLE_INITIATOR) {
8040                         match = (group != XPT_FC_GROUP_TMODE)
8041                               && ((tag == SCB_GET_TAG(scb))
8042                                || (tag == SCB_LIST_NULL));
8043                 } else if (role == ROLE_TARGET) {
8044                         match = (group == XPT_FC_GROUP_TMODE)
8045                               && ((tag == scb->io_ctx->csio.tag_id)
8046                                || (tag == SCB_LIST_NULL));
8047                 }
8048 #else /* !AHD_TARGET_MODE */
8049                 match = ((tag == SCB_GET_TAG(scb)) || (tag == SCB_LIST_NULL));
8050 #endif /* AHD_TARGET_MODE */
8051         }
8052
8053         return match;
8054 }
8055
8056 static void
8057 ahd_freeze_devq(struct ahd_softc *ahd, struct scb *scb)
8058 {
8059         int     target;
8060         char    channel;
8061         int     lun;
8062
8063         target = SCB_GET_TARGET(ahd, scb);
8064         lun = SCB_GET_LUN(scb);
8065         channel = SCB_GET_CHANNEL(ahd, scb);
8066         
8067         ahd_search_qinfifo(ahd, target, channel, lun,
8068                            /*tag*/SCB_LIST_NULL, ROLE_UNKNOWN,
8069                            CAM_REQUEUE_REQ, SEARCH_COMPLETE);
8070
8071         ahd_platform_freeze_devq(ahd, scb);
8072 }
8073
8074 void
8075 ahd_qinfifo_requeue_tail(struct ahd_softc *ahd, struct scb *scb)
8076 {
8077         struct scb      *prev_scb;
8078         ahd_mode_state   saved_modes;
8079
8080         saved_modes = ahd_save_modes(ahd);
8081         ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
8082         prev_scb = NULL;
8083         if (ahd_qinfifo_count(ahd) != 0) {
8084                 u_int prev_tag;
8085                 u_int prev_pos;
8086
8087                 prev_pos = AHD_QIN_WRAP(ahd->qinfifonext - 1);
8088                 prev_tag = ahd->qinfifo[prev_pos];
8089                 prev_scb = ahd_lookup_scb(ahd, prev_tag);
8090         }
8091         ahd_qinfifo_requeue(ahd, prev_scb, scb);
8092         ahd_set_hnscb_qoff(ahd, ahd->qinfifonext);
8093         ahd_restore_modes(ahd, saved_modes);
8094 }
8095
8096 static void
8097 ahd_qinfifo_requeue(struct ahd_softc *ahd, struct scb *prev_scb,
8098                     struct scb *scb)
8099 {
8100         if (prev_scb == NULL) {
8101                 uint32_t busaddr;
8102
8103                 busaddr = ahd_le32toh(scb->hscb->hscb_busaddr);
8104                 ahd_outl(ahd, NEXT_QUEUED_SCB_ADDR, busaddr);
8105         } else {
8106                 prev_scb->hscb->next_hscb_busaddr = scb->hscb->hscb_busaddr;
8107                 ahd_sync_scb(ahd, prev_scb, 
8108                              BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
8109         }
8110         ahd->qinfifo[AHD_QIN_WRAP(ahd->qinfifonext)] = SCB_GET_TAG(scb);
8111         ahd->qinfifonext++;
8112         scb->hscb->next_hscb_busaddr = ahd->next_queued_hscb->hscb_busaddr;
8113         ahd_sync_scb(ahd, scb, BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
8114 }
8115
8116 static int
8117 ahd_qinfifo_count(struct ahd_softc *ahd)
8118 {
8119         u_int qinpos;
8120         u_int wrap_qinpos;
8121         u_int wrap_qinfifonext;
8122
8123         AHD_ASSERT_MODES(ahd, AHD_MODE_CCHAN_MSK, AHD_MODE_CCHAN_MSK);
8124         qinpos = ahd_get_snscb_qoff(ahd);
8125         wrap_qinpos = AHD_QIN_WRAP(qinpos);
8126         wrap_qinfifonext = AHD_QIN_WRAP(ahd->qinfifonext);
8127         if (wrap_qinfifonext >= wrap_qinpos)
8128                 return (wrap_qinfifonext - wrap_qinpos);
8129         else
8130                 return (wrap_qinfifonext
8131                       + ARRAY_SIZE(ahd->qinfifo) - wrap_qinpos);
8132 }
8133
8134 void
8135 ahd_reset_cmds_pending(struct ahd_softc *ahd)
8136 {
8137         struct          scb *scb;
8138         ahd_mode_state  saved_modes;
8139         u_int           pending_cmds;
8140
8141         saved_modes = ahd_save_modes(ahd);
8142         ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
8143
8144         /*
8145          * Don't count any commands as outstanding that the
8146          * sequencer has already marked for completion.
8147          */
8148         ahd_flush_qoutfifo(ahd);
8149
8150         pending_cmds = 0;
8151         LIST_FOREACH(scb, &ahd->pending_scbs, pending_links) {
8152                 pending_cmds++;
8153         }
8154         ahd_outw(ahd, CMDS_PENDING, pending_cmds - ahd_qinfifo_count(ahd));
8155         ahd_restore_modes(ahd, saved_modes);
8156         ahd->flags &= ~AHD_UPDATE_PEND_CMDS;
8157 }
8158
8159 static void
8160 ahd_done_with_status(struct ahd_softc *ahd, struct scb *scb, uint32_t status)
8161 {
8162         cam_status ostat;
8163         cam_status cstat;
8164
8165         ostat = ahd_get_transaction_status(scb);
8166         if (ostat == CAM_REQ_INPROG)
8167                 ahd_set_transaction_status(scb, status);
8168         cstat = ahd_get_transaction_status(scb);
8169         if (cstat != CAM_REQ_CMP)
8170                 ahd_freeze_scb(scb);
8171         ahd_done(ahd, scb);
8172 }
8173
8174 int
8175 ahd_search_qinfifo(struct ahd_softc *ahd, int target, char channel,
8176                    int lun, u_int tag, role_t role, uint32_t status,
8177                    ahd_search_action action)
8178 {
8179         struct scb      *scb;
8180         struct scb      *mk_msg_scb;
8181         struct scb      *prev_scb;
8182         ahd_mode_state   saved_modes;
8183         u_int            qinstart;
8184         u_int            qinpos;
8185         u_int            qintail;
8186         u_int            tid_next;
8187         u_int            tid_prev;
8188         u_int            scbid;
8189         u_int            seq_flags2;
8190         u_int            savedscbptr;
8191         uint32_t         busaddr;
8192         int              found;
8193         int              targets;
8194
8195         /* Must be in CCHAN mode */
8196         saved_modes = ahd_save_modes(ahd);
8197         ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
8198
8199         /*
8200          * Halt any pending SCB DMA.  The sequencer will reinitiate
8201          * this dma if the qinfifo is not empty once we unpause.
8202          */
8203         if ((ahd_inb(ahd, CCSCBCTL) & (CCARREN|CCSCBEN|CCSCBDIR))
8204          == (CCARREN|CCSCBEN|CCSCBDIR)) {
8205                 ahd_outb(ahd, CCSCBCTL,
8206                          ahd_inb(ahd, CCSCBCTL) & ~(CCARREN|CCSCBEN));
8207                 while ((ahd_inb(ahd, CCSCBCTL) & (CCARREN|CCSCBEN)) != 0)
8208                         ;
8209         }
8210         /* Determine sequencer's position in the qinfifo. */
8211         qintail = AHD_QIN_WRAP(ahd->qinfifonext);
8212         qinstart = ahd_get_snscb_qoff(ahd);
8213         qinpos = AHD_QIN_WRAP(qinstart);
8214         found = 0;
8215         prev_scb = NULL;
8216
8217         if (action == SEARCH_PRINT) {
8218                 printf("qinstart = %d qinfifonext = %d\nQINFIFO:",
8219                        qinstart, ahd->qinfifonext);
8220         }
8221
8222         /*
8223          * Start with an empty queue.  Entries that are not chosen
8224          * for removal will be re-added to the queue as we go.
8225          */
8226         ahd->qinfifonext = qinstart;
8227         busaddr = ahd_le32toh(ahd->next_queued_hscb->hscb_busaddr);
8228         ahd_outl(ahd, NEXT_QUEUED_SCB_ADDR, busaddr);
8229
8230         while (qinpos != qintail) {
8231                 scb = ahd_lookup_scb(ahd, ahd->qinfifo[qinpos]);
8232                 if (scb == NULL) {
8233                         printf("qinpos = %d, SCB index = %d\n",
8234                                 qinpos, ahd->qinfifo[qinpos]);
8235                         panic("Loop 1\n");
8236                 }
8237
8238                 if (ahd_match_scb(ahd, scb, target, channel, lun, tag, role)) {
8239                         /*
8240                          * We found an scb that needs to be acted on.
8241                          */
8242                         found++;
8243                         switch (action) {
8244                         case SEARCH_COMPLETE:
8245                                 if ((scb->flags & SCB_ACTIVE) == 0)
8246                                         printf("Inactive SCB in qinfifo\n");
8247                                 ahd_done_with_status(ahd, scb, status);
8248                                 /* FALLTHROUGH */
8249                         case SEARCH_REMOVE:
8250                                 break;
8251                         case SEARCH_PRINT:
8252                                 printf(" 0x%x", ahd->qinfifo[qinpos]);
8253                                 /* FALLTHROUGH */
8254                         case SEARCH_COUNT:
8255                                 ahd_qinfifo_requeue(ahd, prev_scb, scb);
8256                                 prev_scb = scb;
8257                                 break;
8258                         }
8259                 } else {
8260                         ahd_qinfifo_requeue(ahd, prev_scb, scb);
8261                         prev_scb = scb;
8262                 }
8263                 qinpos = AHD_QIN_WRAP(qinpos+1);
8264         }
8265
8266         ahd_set_hnscb_qoff(ahd, ahd->qinfifonext);
8267
8268         if (action == SEARCH_PRINT)
8269                 printf("\nWAITING_TID_QUEUES:\n");
8270
8271         /*
8272          * Search waiting for selection lists.  We traverse the
8273          * list of "their ids" waiting for selection and, if
8274          * appropriate, traverse the SCBs of each "their id"
8275          * looking for matches.
8276          */
8277         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
8278         seq_flags2 = ahd_inb(ahd, SEQ_FLAGS2);
8279         if ((seq_flags2 & PENDING_MK_MESSAGE) != 0) {
8280                 scbid = ahd_inw(ahd, MK_MESSAGE_SCB);
8281                 mk_msg_scb = ahd_lookup_scb(ahd, scbid);
8282         } else
8283                 mk_msg_scb = NULL;
8284         savedscbptr = ahd_get_scbptr(ahd);
8285         tid_next = ahd_inw(ahd, WAITING_TID_HEAD);
8286         tid_prev = SCB_LIST_NULL;
8287         targets = 0;
8288         for (scbid = tid_next; !SCBID_IS_NULL(scbid); scbid = tid_next) {
8289                 u_int tid_head;
8290                 u_int tid_tail;
8291
8292                 targets++;
8293                 if (targets > AHD_NUM_TARGETS)
8294                         panic("TID LIST LOOP");
8295
8296                 if (scbid >= ahd->scb_data.numscbs) {
8297                         printf("%s: Waiting TID List inconsistency. "
8298                                "SCB index == 0x%x, yet numscbs == 0x%x.",
8299                                ahd_name(ahd), scbid, ahd->scb_data.numscbs);
8300                         ahd_dump_card_state(ahd);
8301                         panic("for safety");
8302                 }
8303                 scb = ahd_lookup_scb(ahd, scbid);
8304                 if (scb == NULL) {
8305                         printf("%s: SCB = 0x%x Not Active!\n",
8306                                ahd_name(ahd), scbid);
8307                         panic("Waiting TID List traversal\n");
8308                 }
8309                 ahd_set_scbptr(ahd, scbid);
8310                 tid_next = ahd_inw_scbram(ahd, SCB_NEXT2);
8311                 if (ahd_match_scb(ahd, scb, target, channel, CAM_LUN_WILDCARD,
8312                                   SCB_LIST_NULL, ROLE_UNKNOWN) == 0) {
8313                         tid_prev = scbid;
8314                         continue;
8315                 }
8316
8317                 /*
8318                  * We found a list of scbs that needs to be searched.
8319                  */
8320                 if (action == SEARCH_PRINT)
8321                         printf("       %d ( ", SCB_GET_TARGET(ahd, scb));
8322                 tid_head = scbid;
8323                 found += ahd_search_scb_list(ahd, target, channel,
8324                                              lun, tag, role, status,
8325                                              action, &tid_head, &tid_tail,
8326                                              SCB_GET_TARGET(ahd, scb));
8327                 /*
8328                  * Check any MK_MESSAGE SCB that is still waiting to
8329                  * enter this target's waiting for selection queue.
8330                  */
8331                 if (mk_msg_scb != NULL
8332                  && ahd_match_scb(ahd, mk_msg_scb, target, channel,
8333                                   lun, tag, role)) {
8334
8335                         /*
8336                          * We found an scb that needs to be acted on.
8337                          */
8338                         found++;
8339                         switch (action) {
8340                         case SEARCH_COMPLETE:
8341                                 if ((mk_msg_scb->flags & SCB_ACTIVE) == 0)
8342                                         printf("Inactive SCB pending MK_MSG\n");
8343                                 ahd_done_with_status(ahd, mk_msg_scb, status);
8344                                 /* FALLTHROUGH */
8345                         case SEARCH_REMOVE:
8346                         {
8347                                 u_int tail_offset;
8348
8349                                 printf("Removing MK_MSG scb\n");
8350
8351                                 /*
8352                                  * Reset our tail to the tail of the
8353                                  * main per-target list.
8354                                  */
8355                                 tail_offset = WAITING_SCB_TAILS
8356                                     + (2 * SCB_GET_TARGET(ahd, mk_msg_scb));
8357                                 ahd_outw(ahd, tail_offset, tid_tail);
8358
8359                                 seq_flags2 &= ~PENDING_MK_MESSAGE;
8360                                 ahd_outb(ahd, SEQ_FLAGS2, seq_flags2);
8361                                 ahd_outw(ahd, CMDS_PENDING,
8362                                          ahd_inw(ahd, CMDS_PENDING)-1);
8363                                 mk_msg_scb = NULL;
8364                                 break;
8365                         }
8366                         case SEARCH_PRINT:
8367                                 printf(" 0x%x", SCB_GET_TAG(scb));
8368                                 /* FALLTHROUGH */
8369                         case SEARCH_COUNT:
8370                                 break;
8371                         }
8372                 }
8373
8374                 if (mk_msg_scb != NULL
8375                  && SCBID_IS_NULL(tid_head)
8376                  && ahd_match_scb(ahd, scb, target, channel, CAM_LUN_WILDCARD,
8377                                   SCB_LIST_NULL, ROLE_UNKNOWN)) {
8378
8379                         /*
8380                          * When removing the last SCB for a target
8381                          * queue with a pending MK_MESSAGE scb, we
8382                          * must queue the MK_MESSAGE scb.
8383                          */
8384                         printf("Queueing mk_msg_scb\n");
8385                         tid_head = ahd_inw(ahd, MK_MESSAGE_SCB);
8386                         seq_flags2 &= ~PENDING_MK_MESSAGE;
8387                         ahd_outb(ahd, SEQ_FLAGS2, seq_flags2);
8388                         mk_msg_scb = NULL;
8389                 }
8390                 if (tid_head != scbid)
8391                         ahd_stitch_tid_list(ahd, tid_prev, tid_head, tid_next);
8392                 if (!SCBID_IS_NULL(tid_head))
8393                         tid_prev = tid_head;
8394                 if (action == SEARCH_PRINT)
8395                         printf(")\n");
8396         }
8397
8398         /* Restore saved state. */
8399         ahd_set_scbptr(ahd, savedscbptr);
8400         ahd_restore_modes(ahd, saved_modes);
8401         return (found);
8402 }
8403
8404 static int
8405 ahd_search_scb_list(struct ahd_softc *ahd, int target, char channel,
8406                     int lun, u_int tag, role_t role, uint32_t status,
8407                     ahd_search_action action, u_int *list_head, 
8408                     u_int *list_tail, u_int tid)
8409 {
8410         struct  scb *scb;
8411         u_int   scbid;
8412         u_int   next;
8413         u_int   prev;
8414         int     found;
8415
8416         AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
8417         found = 0;
8418         prev = SCB_LIST_NULL;
8419         next = *list_head;
8420         *list_tail = SCB_LIST_NULL;
8421         for (scbid = next; !SCBID_IS_NULL(scbid); scbid = next) {
8422                 if (scbid >= ahd->scb_data.numscbs) {
8423                         printf("%s:SCB List inconsistency. "
8424                                "SCB == 0x%x, yet numscbs == 0x%x.",
8425                                ahd_name(ahd), scbid, ahd->scb_data.numscbs);
8426                         ahd_dump_card_state(ahd);
8427                         panic("for safety");
8428                 }
8429                 scb = ahd_lookup_scb(ahd, scbid);
8430                 if (scb == NULL) {
8431                         printf("%s: SCB = %d Not Active!\n",
8432                                ahd_name(ahd), scbid);
8433                         panic("Waiting List traversal\n");
8434                 }
8435                 ahd_set_scbptr(ahd, scbid);
8436                 *list_tail = scbid;
8437                 next = ahd_inw_scbram(ahd, SCB_NEXT);
8438                 if (ahd_match_scb(ahd, scb, target, channel,
8439                                   lun, SCB_LIST_NULL, role) == 0) {
8440                         prev = scbid;
8441                         continue;
8442                 }
8443                 found++;
8444                 switch (action) {
8445                 case SEARCH_COMPLETE:
8446                         if ((scb->flags & SCB_ACTIVE) == 0)
8447                                 printf("Inactive SCB in Waiting List\n");
8448                         ahd_done_with_status(ahd, scb, status);
8449                         /* FALLTHROUGH */
8450                 case SEARCH_REMOVE:
8451                         ahd_rem_wscb(ahd, scbid, prev, next, tid);
8452                         *list_tail = prev;
8453                         if (SCBID_IS_NULL(prev))
8454                                 *list_head = next;
8455                         break;
8456                 case SEARCH_PRINT:
8457                         printf("0x%x ", scbid);
8458                 case SEARCH_COUNT:
8459                         prev = scbid;
8460                         break;
8461                 }
8462                 if (found > AHD_SCB_MAX)
8463                         panic("SCB LIST LOOP");
8464         }
8465         if (action == SEARCH_COMPLETE
8466          || action == SEARCH_REMOVE)
8467                 ahd_outw(ahd, CMDS_PENDING, ahd_inw(ahd, CMDS_PENDING) - found);
8468         return (found);
8469 }
8470
8471 static void
8472 ahd_stitch_tid_list(struct ahd_softc *ahd, u_int tid_prev,
8473                     u_int tid_cur, u_int tid_next)
8474 {
8475         AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
8476
8477         if (SCBID_IS_NULL(tid_cur)) {
8478
8479                 /* Bypass current TID list */
8480                 if (SCBID_IS_NULL(tid_prev)) {
8481                         ahd_outw(ahd, WAITING_TID_HEAD, tid_next);
8482                 } else {
8483                         ahd_set_scbptr(ahd, tid_prev);
8484                         ahd_outw(ahd, SCB_NEXT2, tid_next);
8485                 }
8486                 if (SCBID_IS_NULL(tid_next))
8487                         ahd_outw(ahd, WAITING_TID_TAIL, tid_prev);
8488         } else {
8489
8490                 /* Stitch through tid_cur */
8491                 if (SCBID_IS_NULL(tid_prev)) {
8492                         ahd_outw(ahd, WAITING_TID_HEAD, tid_cur);
8493                 } else {
8494                         ahd_set_scbptr(ahd, tid_prev);
8495                         ahd_outw(ahd, SCB_NEXT2, tid_cur);
8496                 }
8497                 ahd_set_scbptr(ahd, tid_cur);
8498                 ahd_outw(ahd, SCB_NEXT2, tid_next);
8499
8500                 if (SCBID_IS_NULL(tid_next))
8501                         ahd_outw(ahd, WAITING_TID_TAIL, tid_cur);
8502         }
8503 }
8504
8505 /*
8506  * Manipulate the waiting for selection list and return the
8507  * scb that follows the one that we remove.
8508  */
8509 static u_int
8510 ahd_rem_wscb(struct ahd_softc *ahd, u_int scbid,
8511              u_int prev, u_int next, u_int tid)
8512 {
8513         u_int tail_offset;
8514
8515         AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
8516         if (!SCBID_IS_NULL(prev)) {
8517                 ahd_set_scbptr(ahd, prev);
8518                 ahd_outw(ahd, SCB_NEXT, next);
8519         }
8520
8521         /*
8522          * SCBs that have MK_MESSAGE set in them may
8523          * cause the tail pointer to be updated without
8524          * setting the next pointer of the previous tail.
8525          * Only clear the tail if the removed SCB was
8526          * the tail.
8527          */
8528         tail_offset = WAITING_SCB_TAILS + (2 * tid);
8529         if (SCBID_IS_NULL(next)
8530          && ahd_inw(ahd, tail_offset) == scbid)
8531                 ahd_outw(ahd, tail_offset, prev);
8532
8533         ahd_add_scb_to_free_list(ahd, scbid);
8534         return (next);
8535 }
8536
8537 /*
8538  * Add the SCB as selected by SCBPTR onto the on chip list of
8539  * free hardware SCBs.  This list is empty/unused if we are not
8540  * performing SCB paging.
8541  */
8542 static void
8543 ahd_add_scb_to_free_list(struct ahd_softc *ahd, u_int scbid)
8544 {
8545 /* XXX Need some other mechanism to designate "free". */
8546         /*
8547          * Invalidate the tag so that our abort
8548          * routines don't think it's active.
8549         ahd_outb(ahd, SCB_TAG, SCB_LIST_NULL);
8550          */
8551 }
8552
8553 /******************************** Error Handling ******************************/
8554 /*
8555  * Abort all SCBs that match the given description (target/channel/lun/tag),
8556  * setting their status to the passed in status if the status has not already
8557  * been modified from CAM_REQ_INPROG.  This routine assumes that the sequencer
8558  * is paused before it is called.
8559  */
8560 static int
8561 ahd_abort_scbs(struct ahd_softc *ahd, int target, char channel,
8562                int lun, u_int tag, role_t role, uint32_t status)
8563 {
8564         struct          scb *scbp;
8565         struct          scb *scbp_next;
8566         u_int           i, j;
8567         u_int           maxtarget;
8568         u_int           minlun;
8569         u_int           maxlun;
8570         int             found;
8571         ahd_mode_state  saved_modes;
8572
8573         /* restore this when we're done */
8574         saved_modes = ahd_save_modes(ahd);
8575         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
8576
8577         found = ahd_search_qinfifo(ahd, target, channel, lun, SCB_LIST_NULL,
8578                                    role, CAM_REQUEUE_REQ, SEARCH_COMPLETE);
8579
8580         /*
8581          * Clean out the busy target table for any untagged commands.
8582          */
8583         i = 0;
8584         maxtarget = 16;
8585         if (target != CAM_TARGET_WILDCARD) {
8586                 i = target;
8587                 if (channel == 'B')
8588                         i += 8;
8589                 maxtarget = i + 1;
8590         }
8591
8592         if (lun == CAM_LUN_WILDCARD) {
8593                 minlun = 0;
8594                 maxlun = AHD_NUM_LUNS_NONPKT;
8595         } else if (lun >= AHD_NUM_LUNS_NONPKT) {
8596                 minlun = maxlun = 0;
8597         } else {
8598                 minlun = lun;
8599                 maxlun = lun + 1;
8600         }
8601
8602         if (role != ROLE_TARGET) {
8603                 for (;i < maxtarget; i++) {
8604                         for (j = minlun;j < maxlun; j++) {
8605                                 u_int scbid;
8606                                 u_int tcl;
8607
8608                                 tcl = BUILD_TCL_RAW(i, 'A', j);
8609                                 scbid = ahd_find_busy_tcl(ahd, tcl);
8610                                 scbp = ahd_lookup_scb(ahd, scbid);
8611                                 if (scbp == NULL
8612                                  || ahd_match_scb(ahd, scbp, target, channel,
8613                                                   lun, tag, role) == 0)
8614                                         continue;
8615                                 ahd_unbusy_tcl(ahd, BUILD_TCL_RAW(i, 'A', j));
8616                         }
8617                 }
8618         }
8619
8620         /*
8621          * Don't abort commands that have already completed,
8622          * but haven't quite made it up to the host yet.
8623          */
8624         ahd_flush_qoutfifo(ahd);
8625
8626         /*
8627          * Go through the pending CCB list and look for
8628          * commands for this target that are still active.
8629          * These are other tagged commands that were
8630          * disconnected when the reset occurred.
8631          */
8632         scbp_next = LIST_FIRST(&ahd->pending_scbs);
8633         while (scbp_next != NULL) {
8634                 scbp = scbp_next;
8635                 scbp_next = LIST_NEXT(scbp, pending_links);
8636                 if (ahd_match_scb(ahd, scbp, target, channel, lun, tag, role)) {
8637                         cam_status ostat;
8638
8639                         ostat = ahd_get_transaction_status(scbp);
8640                         if (ostat == CAM_REQ_INPROG)
8641                                 ahd_set_transaction_status(scbp, status);
8642                         if (ahd_get_transaction_status(scbp) != CAM_REQ_CMP)
8643                                 ahd_freeze_scb(scbp);
8644                         if ((scbp->flags & SCB_ACTIVE) == 0)
8645                                 printf("Inactive SCB on pending list\n");
8646                         ahd_done(ahd, scbp);
8647                         found++;
8648                 }
8649         }
8650         ahd_restore_modes(ahd, saved_modes);
8651         ahd_platform_abort_scbs(ahd, target, channel, lun, tag, role, status);
8652         ahd->flags |= AHD_UPDATE_PEND_CMDS;
8653         return found;
8654 }
8655
8656 static void
8657 ahd_reset_current_bus(struct ahd_softc *ahd)
8658 {
8659         uint8_t scsiseq;
8660
8661         AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
8662         ahd_outb(ahd, SIMODE1, ahd_inb(ahd, SIMODE1) & ~ENSCSIRST);
8663         scsiseq = ahd_inb(ahd, SCSISEQ0) & ~(ENSELO|ENARBO|SCSIRSTO);
8664         ahd_outb(ahd, SCSISEQ0, scsiseq | SCSIRSTO);
8665         ahd_flush_device_writes(ahd);
8666         ahd_delay(AHD_BUSRESET_DELAY);
8667         /* Turn off the bus reset */
8668         ahd_outb(ahd, SCSISEQ0, scsiseq);
8669         ahd_flush_device_writes(ahd);
8670         ahd_delay(AHD_BUSRESET_DELAY);
8671         if ((ahd->bugs & AHD_SCSIRST_BUG) != 0) {
8672                 /*
8673                  * 2A Razor #474
8674                  * Certain chip state is not cleared for
8675                  * SCSI bus resets that we initiate, so
8676                  * we must reset the chip.
8677                  */
8678                 ahd_reset(ahd, /*reinit*/TRUE);
8679                 ahd_intr_enable(ahd, /*enable*/TRUE);
8680                 AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
8681         }
8682
8683         ahd_clear_intstat(ahd);
8684 }
8685
8686 int
8687 ahd_reset_channel(struct ahd_softc *ahd, char channel, int initiate_reset)
8688 {
8689         struct  ahd_devinfo devinfo;
8690         u_int   initiator;
8691         u_int   target;
8692         u_int   max_scsiid;
8693         int     found;
8694         u_int   fifo;
8695         u_int   next_fifo;
8696         uint8_t scsiseq;
8697
8698         /*
8699          * Check if the last bus reset is cleared
8700          */
8701         if (ahd->flags & AHD_BUS_RESET_ACTIVE) {
8702                 printf("%s: bus reset still active\n",
8703                        ahd_name(ahd));
8704                 return 0;
8705         }
8706         ahd->flags |= AHD_BUS_RESET_ACTIVE;
8707
8708         ahd->pending_device = NULL;
8709
8710         ahd_compile_devinfo(&devinfo,
8711                             CAM_TARGET_WILDCARD,
8712                             CAM_TARGET_WILDCARD,
8713                             CAM_LUN_WILDCARD,
8714                             channel, ROLE_UNKNOWN);
8715         ahd_pause(ahd);
8716
8717         /* Make sure the sequencer is in a safe location. */
8718         ahd_clear_critical_section(ahd);
8719
8720         /*
8721          * Run our command complete fifos to ensure that we perform
8722          * completion processing on any commands that 'completed'
8723          * before the reset occurred.
8724          */
8725         ahd_run_qoutfifo(ahd);
8726 #ifdef AHD_TARGET_MODE
8727         if ((ahd->flags & AHD_TARGETROLE) != 0) {
8728                 ahd_run_tqinfifo(ahd, /*paused*/TRUE);
8729         }
8730 #endif
8731         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
8732
8733         /*
8734          * Disable selections so no automatic hardware
8735          * functions will modify chip state.
8736          */
8737         ahd_outb(ahd, SCSISEQ0, 0);
8738         ahd_outb(ahd, SCSISEQ1, 0);
8739
8740         /*
8741          * Safely shut down our DMA engines.  Always start with
8742          * the FIFO that is not currently active (if any are
8743          * actively connected).
8744          */
8745         next_fifo = fifo = ahd_inb(ahd, DFFSTAT) & CURRFIFO;
8746         if (next_fifo > CURRFIFO_1)
8747                 /* If disconneced, arbitrarily start with FIFO1. */
8748                 next_fifo = fifo = 0;
8749         do {
8750                 next_fifo ^= CURRFIFO_1;
8751                 ahd_set_modes(ahd, next_fifo, next_fifo);
8752                 ahd_outb(ahd, DFCNTRL,
8753                          ahd_inb(ahd, DFCNTRL) & ~(SCSIEN|HDMAEN));
8754                 while ((ahd_inb(ahd, DFCNTRL) & HDMAENACK) != 0)
8755                         ahd_delay(10);
8756                 /*
8757                  * Set CURRFIFO to the now inactive channel.
8758                  */
8759                 ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
8760                 ahd_outb(ahd, DFFSTAT, next_fifo);
8761         } while (next_fifo != fifo);
8762
8763         /*
8764          * Reset the bus if we are initiating this reset
8765          */
8766         ahd_clear_msg_state(ahd);
8767         ahd_outb(ahd, SIMODE1,
8768                  ahd_inb(ahd, SIMODE1) & ~(ENBUSFREE|ENSCSIRST));
8769
8770         if (initiate_reset)
8771                 ahd_reset_current_bus(ahd);
8772
8773         ahd_clear_intstat(ahd);
8774
8775         /*
8776          * Clean up all the state information for the
8777          * pending transactions on this bus.
8778          */
8779         found = ahd_abort_scbs(ahd, CAM_TARGET_WILDCARD, channel,
8780                                CAM_LUN_WILDCARD, SCB_LIST_NULL,
8781                                ROLE_UNKNOWN, CAM_SCSI_BUS_RESET);
8782
8783         /*
8784          * Cleanup anything left in the FIFOs.
8785          */
8786         ahd_clear_fifo(ahd, 0);
8787         ahd_clear_fifo(ahd, 1);
8788
8789         /*
8790          * Clear SCSI interrupt status
8791          */
8792         ahd_outb(ahd, CLRSINT1, CLRSCSIRSTI);
8793
8794         /*
8795          * Reenable selections
8796          */
8797         ahd_outb(ahd, SIMODE1, ahd_inb(ahd, SIMODE1) | ENSCSIRST);
8798         scsiseq = ahd_inb(ahd, SCSISEQ_TEMPLATE);
8799         ahd_outb(ahd, SCSISEQ1, scsiseq & (ENSELI|ENRSELI|ENAUTOATNP));
8800
8801         max_scsiid = (ahd->features & AHD_WIDE) ? 15 : 7;
8802 #ifdef AHD_TARGET_MODE
8803         /*
8804          * Send an immediate notify ccb to all target more peripheral
8805          * drivers affected by this action.
8806          */
8807         for (target = 0; target <= max_scsiid; target++) {
8808                 struct ahd_tmode_tstate* tstate;
8809                 u_int lun;
8810
8811                 tstate = ahd->enabled_targets[target];
8812                 if (tstate == NULL)
8813                         continue;
8814                 for (lun = 0; lun < AHD_NUM_LUNS; lun++) {
8815                         struct ahd_tmode_lstate* lstate;
8816
8817                         lstate = tstate->enabled_luns[lun];
8818                         if (lstate == NULL)
8819                                 continue;
8820
8821                         ahd_queue_lstate_event(ahd, lstate, CAM_TARGET_WILDCARD,
8822                                                EVENT_TYPE_BUS_RESET, /*arg*/0);
8823                         ahd_send_lstate_events(ahd, lstate);
8824                 }
8825         }
8826 #endif
8827         /*
8828          * Revert to async/narrow transfers until we renegotiate.
8829          */
8830         for (target = 0; target <= max_scsiid; target++) {
8831
8832                 if (ahd->enabled_targets[target] == NULL)
8833                         continue;
8834                 for (initiator = 0; initiator <= max_scsiid; initiator++) {
8835                         struct ahd_devinfo devinfo;
8836
8837                         ahd_compile_devinfo(&devinfo, target, initiator,
8838                                             CAM_LUN_WILDCARD,
8839                                             'A', ROLE_UNKNOWN);
8840                         ahd_set_width(ahd, &devinfo, MSG_EXT_WDTR_BUS_8_BIT,
8841                                       AHD_TRANS_CUR, /*paused*/TRUE);
8842                         ahd_set_syncrate(ahd, &devinfo, /*period*/0,
8843                                          /*offset*/0, /*ppr_options*/0,
8844                                          AHD_TRANS_CUR, /*paused*/TRUE);
8845                 }
8846         }
8847
8848         /* Notify the XPT that a bus reset occurred */
8849         ahd_send_async(ahd, devinfo.channel, CAM_TARGET_WILDCARD,
8850                        CAM_LUN_WILDCARD, AC_BUS_RESET);
8851
8852         ahd_restart(ahd);
8853
8854         return (found);
8855 }
8856
8857 /**************************** Statistics Processing ***************************/
8858 static void
8859 ahd_stat_timer(void *arg)
8860 {
8861         struct  ahd_softc *ahd = arg;
8862         u_long  s;
8863         int     enint_coal;
8864         
8865         ahd_lock(ahd, &s);
8866
8867         enint_coal = ahd->hs_mailbox & ENINT_COALESCE;
8868         if (ahd->cmdcmplt_total > ahd->int_coalescing_threshold)
8869                 enint_coal |= ENINT_COALESCE;
8870         else if (ahd->cmdcmplt_total < ahd->int_coalescing_stop_threshold)
8871                 enint_coal &= ~ENINT_COALESCE;
8872
8873         if (enint_coal != (ahd->hs_mailbox & ENINT_COALESCE)) {
8874                 ahd_enable_coalescing(ahd, enint_coal);
8875 #ifdef AHD_DEBUG
8876                 if ((ahd_debug & AHD_SHOW_INT_COALESCING) != 0)
8877                         printf("%s: Interrupt coalescing "
8878                                "now %sabled. Cmds %d\n",
8879                                ahd_name(ahd),
8880                                (enint_coal & ENINT_COALESCE) ? "en" : "dis",
8881                                ahd->cmdcmplt_total);
8882 #endif
8883         }
8884
8885         ahd->cmdcmplt_bucket = (ahd->cmdcmplt_bucket+1) & (AHD_STAT_BUCKETS-1);
8886         ahd->cmdcmplt_total -= ahd->cmdcmplt_counts[ahd->cmdcmplt_bucket];
8887         ahd->cmdcmplt_counts[ahd->cmdcmplt_bucket] = 0;
8888         ahd_timer_reset(&ahd->stat_timer, AHD_STAT_UPDATE_US,
8889                         ahd_stat_timer, ahd);
8890         ahd_unlock(ahd, &s);
8891 }
8892
8893 /****************************** Status Processing *****************************/
8894
8895 static void
8896 ahd_handle_scsi_status(struct ahd_softc *ahd, struct scb *scb)
8897 {
8898         struct  hardware_scb *hscb;
8899         int     paused;
8900
8901         /*
8902          * The sequencer freezes its select-out queue
8903          * anytime a SCSI status error occurs.  We must
8904          * handle the error and increment our qfreeze count
8905          * to allow the sequencer to continue.  We don't
8906          * bother clearing critical sections here since all
8907          * operations are on data structures that the sequencer
8908          * is not touching once the queue is frozen.
8909          */
8910         hscb = scb->hscb; 
8911
8912         if (ahd_is_paused(ahd)) {
8913                 paused = 1;
8914         } else {
8915                 paused = 0;
8916                 ahd_pause(ahd);
8917         }
8918
8919         /* Freeze the queue until the client sees the error. */
8920         ahd_freeze_devq(ahd, scb);
8921         ahd_freeze_scb(scb);
8922         ahd->qfreeze_cnt++;
8923         ahd_outw(ahd, KERNEL_QFREEZE_COUNT, ahd->qfreeze_cnt);
8924
8925         if (paused == 0)
8926                 ahd_unpause(ahd);
8927
8928         /* Don't want to clobber the original sense code */
8929         if ((scb->flags & SCB_SENSE) != 0) {
8930                 /*
8931                  * Clear the SCB_SENSE Flag and perform
8932                  * a normal command completion.
8933                  */
8934                 scb->flags &= ~SCB_SENSE;
8935                 ahd_set_transaction_status(scb, CAM_AUTOSENSE_FAIL);
8936                 ahd_done(ahd, scb);
8937                 return;
8938         }
8939         ahd_set_transaction_status(scb, CAM_SCSI_STATUS_ERROR);
8940         ahd_set_scsi_status(scb, hscb->shared_data.istatus.scsi_status);
8941         switch (hscb->shared_data.istatus.scsi_status) {
8942         case STATUS_PKT_SENSE:
8943         {
8944                 struct scsi_status_iu_header *siu;
8945
8946                 ahd_sync_sense(ahd, scb, BUS_DMASYNC_POSTREAD);
8947                 siu = (struct scsi_status_iu_header *)scb->sense_data;
8948                 ahd_set_scsi_status(scb, siu->status);
8949 #ifdef AHD_DEBUG
8950                 if ((ahd_debug & AHD_SHOW_SENSE) != 0) {
8951                         ahd_print_path(ahd, scb);
8952                         printf("SCB 0x%x Received PKT Status of 0x%x\n",
8953                                SCB_GET_TAG(scb), siu->status);
8954                         printf("\tflags = 0x%x, sense len = 0x%x, "
8955                                "pktfail = 0x%x\n",
8956                                siu->flags, scsi_4btoul(siu->sense_length),
8957                                scsi_4btoul(siu->pkt_failures_length));
8958                 }
8959 #endif
8960                 if ((siu->flags & SIU_RSPVALID) != 0) {
8961                         ahd_print_path(ahd, scb);
8962                         if (scsi_4btoul(siu->pkt_failures_length) < 4) {
8963                                 printf("Unable to parse pkt_failures\n");
8964                         } else {
8965
8966                                 switch (SIU_PKTFAIL_CODE(siu)) {
8967                                 case SIU_PFC_NONE:
8968                                         printf("No packet failure found\n");
8969                                         break;
8970                                 case SIU_PFC_CIU_FIELDS_INVALID:
8971                                         printf("Invalid Command IU Field\n");
8972                                         break;
8973                                 case SIU_PFC_TMF_NOT_SUPPORTED:
8974                                         printf("TMF not supportd\n");
8975                                         break;
8976                                 case SIU_PFC_TMF_FAILED:
8977                                         printf("TMF failed\n");
8978                                         break;
8979                                 case SIU_PFC_INVALID_TYPE_CODE:
8980                                         printf("Invalid L_Q Type code\n");
8981                                         break;
8982                                 case SIU_PFC_ILLEGAL_REQUEST:
8983                                         printf("Illegal request\n");
8984                                 default:
8985                                         break;
8986                                 }
8987                         }
8988                         if (siu->status == SCSI_STATUS_OK)
8989                                 ahd_set_transaction_status(scb,
8990                                                            CAM_REQ_CMP_ERR);
8991                 }
8992                 if ((siu->flags & SIU_SNSVALID) != 0) {
8993                         scb->flags |= SCB_PKT_SENSE;
8994 #ifdef AHD_DEBUG
8995                         if ((ahd_debug & AHD_SHOW_SENSE) != 0)
8996                                 printf("Sense data available\n");
8997 #endif
8998                 }
8999                 ahd_done(ahd, scb);
9000                 break;
9001         }
9002         case SCSI_STATUS_CMD_TERMINATED:
9003         case SCSI_STATUS_CHECK_COND:
9004         {
9005                 struct ahd_devinfo devinfo;
9006                 struct ahd_dma_seg *sg;
9007                 struct scsi_sense *sc;
9008                 struct ahd_initiator_tinfo *targ_info;
9009                 struct ahd_tmode_tstate *tstate;
9010                 struct ahd_transinfo *tinfo;
9011 #ifdef AHD_DEBUG
9012                 if (ahd_debug & AHD_SHOW_SENSE) {
9013                         ahd_print_path(ahd, scb);
9014                         printf("SCB %d: requests Check Status\n",
9015                                SCB_GET_TAG(scb));
9016                 }
9017 #endif
9018
9019                 if (ahd_perform_autosense(scb) == 0)
9020                         break;
9021
9022                 ahd_compile_devinfo(&devinfo, SCB_GET_OUR_ID(scb),
9023                                     SCB_GET_TARGET(ahd, scb),
9024                                     SCB_GET_LUN(scb),
9025                                     SCB_GET_CHANNEL(ahd, scb),
9026                                     ROLE_INITIATOR);
9027                 targ_info = ahd_fetch_transinfo(ahd,
9028                                                 devinfo.channel,
9029                                                 devinfo.our_scsiid,
9030                                                 devinfo.target,
9031                                                 &tstate);
9032                 tinfo = &targ_info->curr;
9033                 sg = scb->sg_list;
9034                 sc = (struct scsi_sense *)hscb->shared_data.idata.cdb;
9035                 /*
9036                  * Save off the residual if there is one.
9037                  */
9038                 ahd_update_residual(ahd, scb);
9039 #ifdef AHD_DEBUG
9040                 if (ahd_debug & AHD_SHOW_SENSE) {
9041                         ahd_print_path(ahd, scb);
9042                         printf("Sending Sense\n");
9043                 }
9044 #endif
9045                 scb->sg_count = 0;
9046                 sg = ahd_sg_setup(ahd, scb, sg, ahd_get_sense_bufaddr(ahd, scb),
9047                                   ahd_get_sense_bufsize(ahd, scb),
9048                                   /*last*/TRUE);
9049                 sc->opcode = REQUEST_SENSE;
9050                 sc->byte2 = 0;
9051                 if (tinfo->protocol_version <= SCSI_REV_2
9052                  && SCB_GET_LUN(scb) < 8)
9053                         sc->byte2 = SCB_GET_LUN(scb) << 5;
9054                 sc->unused[0] = 0;
9055                 sc->unused[1] = 0;
9056                 sc->length = ahd_get_sense_bufsize(ahd, scb);
9057                 sc->control = 0;
9058
9059                 /*
9060                  * We can't allow the target to disconnect.
9061                  * This will be an untagged transaction and
9062                  * having the target disconnect will make this
9063                  * transaction indestinguishable from outstanding
9064                  * tagged transactions.
9065                  */
9066                 hscb->control = 0;
9067
9068                 /*
9069                  * This request sense could be because the
9070                  * the device lost power or in some other
9071                  * way has lost our transfer negotiations.
9072                  * Renegotiate if appropriate.  Unit attention
9073                  * errors will be reported before any data
9074                  * phases occur.
9075                  */
9076                 if (ahd_get_residual(scb) == ahd_get_transfer_length(scb)) {
9077                         ahd_update_neg_request(ahd, &devinfo,
9078                                                tstate, targ_info,
9079                                                AHD_NEG_IF_NON_ASYNC);
9080                 }
9081                 if (tstate->auto_negotiate & devinfo.target_mask) {
9082                         hscb->control |= MK_MESSAGE;
9083                         scb->flags &=
9084                             ~(SCB_NEGOTIATE|SCB_ABORT|SCB_DEVICE_RESET);
9085                         scb->flags |= SCB_AUTO_NEGOTIATE;
9086                 }
9087                 hscb->cdb_len = sizeof(*sc);
9088                 ahd_setup_data_scb(ahd, scb);
9089                 scb->flags |= SCB_SENSE;
9090                 ahd_queue_scb(ahd, scb);
9091                 break;
9092         }
9093         case SCSI_STATUS_OK:
9094                 printf("%s: Interrupted for staus of 0???\n",
9095                        ahd_name(ahd));
9096                 /* FALLTHROUGH */
9097         default:
9098                 ahd_done(ahd, scb);
9099                 break;
9100         }
9101 }
9102
9103 static void
9104 ahd_handle_scb_status(struct ahd_softc *ahd, struct scb *scb)
9105 {
9106         if (scb->hscb->shared_data.istatus.scsi_status != 0) {
9107                 ahd_handle_scsi_status(ahd, scb);
9108         } else {
9109                 ahd_calc_residual(ahd, scb);
9110                 ahd_done(ahd, scb);
9111         }
9112 }
9113
9114 /*
9115  * Calculate the residual for a just completed SCB.
9116  */
9117 static void
9118 ahd_calc_residual(struct ahd_softc *ahd, struct scb *scb)
9119 {
9120         struct hardware_scb *hscb;
9121         struct initiator_status *spkt;
9122         uint32_t sgptr;
9123         uint32_t resid_sgptr;
9124         uint32_t resid;
9125
9126         /*
9127          * 5 cases.
9128          * 1) No residual.
9129          *    SG_STATUS_VALID clear in sgptr.
9130          * 2) Transferless command
9131          * 3) Never performed any transfers.
9132          *    sgptr has SG_FULL_RESID set.
9133          * 4) No residual but target did not
9134          *    save data pointers after the
9135          *    last transfer, so sgptr was
9136          *    never updated.
9137          * 5) We have a partial residual.
9138          *    Use residual_sgptr to determine
9139          *    where we are.
9140          */
9141
9142         hscb = scb->hscb;
9143         sgptr = ahd_le32toh(hscb->sgptr);
9144         if ((sgptr & SG_STATUS_VALID) == 0)
9145                 /* Case 1 */
9146                 return;
9147         sgptr &= ~SG_STATUS_VALID;
9148
9149         if ((sgptr & SG_LIST_NULL) != 0)
9150                 /* Case 2 */
9151                 return;
9152
9153         /*
9154          * Residual fields are the same in both
9155          * target and initiator status packets,
9156          * so we can always use the initiator fields
9157          * regardless of the role for this SCB.
9158          */
9159         spkt = &hscb->shared_data.istatus;
9160         resid_sgptr = ahd_le32toh(spkt->residual_sgptr);
9161         if ((sgptr & SG_FULL_RESID) != 0) {
9162                 /* Case 3 */
9163                 resid = ahd_get_transfer_length(scb);
9164         } else if ((resid_sgptr & SG_LIST_NULL) != 0) {
9165                 /* Case 4 */
9166                 return;
9167         } else if ((resid_sgptr & SG_OVERRUN_RESID) != 0) {
9168                 ahd_print_path(ahd, scb);
9169                 printf("data overrun detected Tag == 0x%x.\n",
9170                        SCB_GET_TAG(scb));
9171                 ahd_freeze_devq(ahd, scb);
9172                 ahd_set_transaction_status(scb, CAM_DATA_RUN_ERR);
9173                 ahd_freeze_scb(scb);
9174                 return;
9175         } else if ((resid_sgptr & ~SG_PTR_MASK) != 0) {
9176                 panic("Bogus resid sgptr value 0x%x\n", resid_sgptr);
9177                 /* NOTREACHED */
9178         } else {
9179                 struct ahd_dma_seg *sg;
9180
9181                 /*
9182                  * Remainder of the SG where the transfer
9183                  * stopped.  
9184                  */
9185                 resid = ahd_le32toh(spkt->residual_datacnt) & AHD_SG_LEN_MASK;
9186                 sg = ahd_sg_bus_to_virt(ahd, scb, resid_sgptr & SG_PTR_MASK);
9187
9188                 /* The residual sg_ptr always points to the next sg */
9189                 sg--;
9190
9191                 /*
9192                  * Add up the contents of all residual
9193                  * SG segments that are after the SG where
9194                  * the transfer stopped.
9195                  */
9196                 while ((ahd_le32toh(sg->len) & AHD_DMA_LAST_SEG) == 0) {
9197                         sg++;
9198                         resid += ahd_le32toh(sg->len) & AHD_SG_LEN_MASK;
9199                 }
9200         }
9201         if ((scb->flags & SCB_SENSE) == 0)
9202                 ahd_set_residual(scb, resid);
9203         else
9204                 ahd_set_sense_residual(scb, resid);
9205
9206 #ifdef AHD_DEBUG
9207         if ((ahd_debug & AHD_SHOW_MISC) != 0) {
9208                 ahd_print_path(ahd, scb);
9209                 printf("Handled %sResidual of %d bytes\n",
9210                        (scb->flags & SCB_SENSE) ? "Sense " : "", resid);
9211         }
9212 #endif
9213 }
9214
9215 /******************************* Target Mode **********************************/
9216 #ifdef AHD_TARGET_MODE
9217 /*
9218  * Add a target mode event to this lun's queue
9219  */
9220 static void
9221 ahd_queue_lstate_event(struct ahd_softc *ahd, struct ahd_tmode_lstate *lstate,
9222                        u_int initiator_id, u_int event_type, u_int event_arg)
9223 {
9224         struct ahd_tmode_event *event;
9225         int pending;
9226
9227         xpt_freeze_devq(lstate->path, /*count*/1);
9228         if (lstate->event_w_idx >= lstate->event_r_idx)
9229                 pending = lstate->event_w_idx - lstate->event_r_idx;
9230         else
9231                 pending = AHD_TMODE_EVENT_BUFFER_SIZE + 1
9232                         - (lstate->event_r_idx - lstate->event_w_idx);
9233
9234         if (event_type == EVENT_TYPE_BUS_RESET
9235          || event_type == MSG_BUS_DEV_RESET) {
9236                 /*
9237                  * Any earlier events are irrelevant, so reset our buffer.
9238                  * This has the effect of allowing us to deal with reset
9239                  * floods (an external device holding down the reset line)
9240                  * without losing the event that is really interesting.
9241                  */
9242                 lstate->event_r_idx = 0;
9243                 lstate->event_w_idx = 0;
9244                 xpt_release_devq(lstate->path, pending, /*runqueue*/FALSE);
9245         }
9246
9247         if (pending == AHD_TMODE_EVENT_BUFFER_SIZE) {
9248                 xpt_print_path(lstate->path);
9249                 printf("immediate event %x:%x lost\n",
9250                        lstate->event_buffer[lstate->event_r_idx].event_type,
9251                        lstate->event_buffer[lstate->event_r_idx].event_arg);
9252                 lstate->event_r_idx++;
9253                 if (lstate->event_r_idx == AHD_TMODE_EVENT_BUFFER_SIZE)
9254                         lstate->event_r_idx = 0;
9255                 xpt_release_devq(lstate->path, /*count*/1, /*runqueue*/FALSE);
9256         }
9257
9258         event = &lstate->event_buffer[lstate->event_w_idx];
9259         event->initiator_id = initiator_id;
9260         event->event_type = event_type;
9261         event->event_arg = event_arg;
9262         lstate->event_w_idx++;
9263         if (lstate->event_w_idx == AHD_TMODE_EVENT_BUFFER_SIZE)
9264                 lstate->event_w_idx = 0;
9265 }
9266
9267 /*
9268  * Send any target mode events queued up waiting
9269  * for immediate notify resources.
9270  */
9271 void
9272 ahd_send_lstate_events(struct ahd_softc *ahd, struct ahd_tmode_lstate *lstate)
9273 {
9274         struct ccb_hdr *ccbh;
9275         struct ccb_immed_notify *inot;
9276
9277         while (lstate->event_r_idx != lstate->event_w_idx
9278             && (ccbh = SLIST_FIRST(&lstate->immed_notifies)) != NULL) {
9279                 struct ahd_tmode_event *event;
9280
9281                 event = &lstate->event_buffer[lstate->event_r_idx];
9282                 SLIST_REMOVE_HEAD(&lstate->immed_notifies, sim_links.sle);
9283                 inot = (struct ccb_immed_notify *)ccbh;
9284                 switch (event->event_type) {
9285                 case EVENT_TYPE_BUS_RESET:
9286                         ccbh->status = CAM_SCSI_BUS_RESET|CAM_DEV_QFRZN;
9287                         break;
9288                 default:
9289                         ccbh->status = CAM_MESSAGE_RECV|CAM_DEV_QFRZN;
9290                         inot->message_args[0] = event->event_type;
9291                         inot->message_args[1] = event->event_arg;
9292                         break;
9293                 }
9294                 inot->initiator_id = event->initiator_id;
9295                 inot->sense_len = 0;
9296                 xpt_done((union ccb *)inot);
9297                 lstate->event_r_idx++;
9298                 if (lstate->event_r_idx == AHD_TMODE_EVENT_BUFFER_SIZE)
9299                         lstate->event_r_idx = 0;
9300         }
9301 }
9302 #endif
9303
9304 /******************** Sequencer Program Patching/Download *********************/
9305
9306 #ifdef AHD_DUMP_SEQ
9307 void
9308 ahd_dumpseq(struct ahd_softc* ahd)
9309 {
9310         int i;
9311         int max_prog;
9312
9313         max_prog = 2048;
9314
9315         ahd_outb(ahd, SEQCTL0, PERRORDIS|FAILDIS|FASTMODE|LOADRAM);
9316         ahd_outw(ahd, PRGMCNT, 0);
9317         for (i = 0; i < max_prog; i++) {
9318                 uint8_t ins_bytes[4];
9319
9320                 ahd_insb(ahd, SEQRAM, ins_bytes, 4);
9321                 printf("0x%08x\n", ins_bytes[0] << 24
9322                                  | ins_bytes[1] << 16
9323                                  | ins_bytes[2] << 8
9324                                  | ins_bytes[3]);
9325         }
9326 }
9327 #endif
9328
9329 static void
9330 ahd_loadseq(struct ahd_softc *ahd)
9331 {
9332         struct  cs cs_table[num_critical_sections];
9333         u_int   begin_set[num_critical_sections];
9334         u_int   end_set[num_critical_sections];
9335         struct  patch *cur_patch;
9336         u_int   cs_count;
9337         u_int   cur_cs;
9338         u_int   i;
9339         int     downloaded;
9340         u_int   skip_addr;
9341         u_int   sg_prefetch_cnt;
9342         u_int   sg_prefetch_cnt_limit;
9343         u_int   sg_prefetch_align;
9344         u_int   sg_size;
9345         u_int   cacheline_mask;
9346         uint8_t download_consts[DOWNLOAD_CONST_COUNT];
9347
9348         if (bootverbose)
9349                 printf("%s: Downloading Sequencer Program...",
9350                        ahd_name(ahd));
9351
9352 #if DOWNLOAD_CONST_COUNT != 8
9353 #error "Download Const Mismatch"
9354 #endif
9355         /*
9356          * Start out with 0 critical sections
9357          * that apply to this firmware load.
9358          */
9359         cs_count = 0;
9360         cur_cs = 0;
9361         memset(begin_set, 0, sizeof(begin_set));
9362         memset(end_set, 0, sizeof(end_set));
9363
9364         /*
9365          * Setup downloadable constant table.
9366          * 
9367          * The computation for the S/G prefetch variables is
9368          * a bit complicated.  We would like to always fetch
9369          * in terms of cachelined sized increments.  However,
9370          * if the cacheline is not an even multiple of the
9371          * SG element size or is larger than our SG RAM, using
9372          * just the cache size might leave us with only a portion
9373          * of an SG element at the tail of a prefetch.  If the
9374          * cacheline is larger than our S/G prefetch buffer less
9375          * the size of an SG element, we may round down to a cacheline
9376          * that doesn't contain any or all of the S/G of interest
9377          * within the bounds of our S/G ram.  Provide variables to
9378          * the sequencer that will allow it to handle these edge
9379          * cases.
9380          */
9381         /* Start by aligning to the nearest cacheline. */
9382         sg_prefetch_align = ahd->pci_cachesize;
9383         if (sg_prefetch_align == 0)
9384                 sg_prefetch_align = 8;
9385         /* Round down to the nearest power of 2. */
9386         while (powerof2(sg_prefetch_align) == 0)
9387                 sg_prefetch_align--;
9388
9389         cacheline_mask = sg_prefetch_align - 1;
9390
9391         /*
9392          * If the cacheline boundary is greater than half our prefetch RAM
9393          * we risk not being able to fetch even a single complete S/G
9394          * segment if we align to that boundary.
9395          */
9396         if (sg_prefetch_align > CCSGADDR_MAX/2)
9397                 sg_prefetch_align = CCSGADDR_MAX/2;
9398         /* Start by fetching a single cacheline. */
9399         sg_prefetch_cnt = sg_prefetch_align;
9400         /*
9401          * Increment the prefetch count by cachelines until
9402          * at least one S/G element will fit.
9403          */
9404         sg_size = sizeof(struct ahd_dma_seg);
9405         if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0)
9406                 sg_size = sizeof(struct ahd_dma64_seg);
9407         while (sg_prefetch_cnt < sg_size)
9408                 sg_prefetch_cnt += sg_prefetch_align;
9409         /*
9410          * If the cacheline is not an even multiple of
9411          * the S/G size, we may only get a partial S/G when
9412          * we align. Add a cacheline if this is the case.
9413          */
9414         if ((sg_prefetch_align % sg_size) != 0
9415          && (sg_prefetch_cnt < CCSGADDR_MAX))
9416                 sg_prefetch_cnt += sg_prefetch_align;
9417         /*
9418          * Lastly, compute a value that the sequencer can use
9419          * to determine if the remainder of the CCSGRAM buffer
9420          * has a full S/G element in it.
9421          */
9422         sg_prefetch_cnt_limit = -(sg_prefetch_cnt - sg_size + 1);
9423         download_consts[SG_PREFETCH_CNT] = sg_prefetch_cnt;
9424         download_consts[SG_PREFETCH_CNT_LIMIT] = sg_prefetch_cnt_limit;
9425         download_consts[SG_PREFETCH_ALIGN_MASK] = ~(sg_prefetch_align - 1);
9426         download_consts[SG_PREFETCH_ADDR_MASK] = (sg_prefetch_align - 1);
9427         download_consts[SG_SIZEOF] = sg_size;
9428         download_consts[PKT_OVERRUN_BUFOFFSET] =
9429                 (ahd->overrun_buf - (uint8_t *)ahd->qoutfifo) / 256;
9430         download_consts[SCB_TRANSFER_SIZE] = SCB_TRANSFER_SIZE_1BYTE_LUN;
9431         download_consts[CACHELINE_MASK] = cacheline_mask;
9432         cur_patch = patches;
9433         downloaded = 0;
9434         skip_addr = 0;
9435         ahd_outb(ahd, SEQCTL0, PERRORDIS|FAILDIS|FASTMODE|LOADRAM);
9436         ahd_outw(ahd, PRGMCNT, 0);
9437
9438         for (i = 0; i < sizeof(seqprog)/4; i++) {
9439                 if (ahd_check_patch(ahd, &cur_patch, i, &skip_addr) == 0) {
9440                         /*
9441                          * Don't download this instruction as it
9442                          * is in a patch that was removed.
9443                          */
9444                         continue;
9445                 }
9446                 /*
9447                  * Move through the CS table until we find a CS
9448                  * that might apply to this instruction.
9449                  */
9450                 for (; cur_cs < num_critical_sections; cur_cs++) {
9451                         if (critical_sections[cur_cs].end <= i) {
9452                                 if (begin_set[cs_count] == TRUE
9453                                  && end_set[cs_count] == FALSE) {
9454                                         cs_table[cs_count].end = downloaded;
9455                                         end_set[cs_count] = TRUE;
9456                                         cs_count++;
9457                                 }
9458                                 continue;
9459                         }
9460                         if (critical_sections[cur_cs].begin <= i
9461                          && begin_set[cs_count] == FALSE) {
9462                                 cs_table[cs_count].begin = downloaded;
9463                                 begin_set[cs_count] = TRUE;
9464                         }
9465                         break;
9466                 }
9467                 ahd_download_instr(ahd, i, download_consts);
9468                 downloaded++;
9469         }
9470
9471         ahd->num_critical_sections = cs_count;
9472         if (cs_count != 0) {
9473
9474                 cs_count *= sizeof(struct cs);
9475                 ahd->critical_sections = malloc(cs_count, M_DEVBUF, M_NOWAIT);
9476                 if (ahd->critical_sections == NULL)
9477                         panic("ahd_loadseq: Could not malloc");
9478                 memcpy(ahd->critical_sections, cs_table, cs_count);
9479         }
9480         ahd_outb(ahd, SEQCTL0, PERRORDIS|FAILDIS|FASTMODE);
9481
9482         if (bootverbose) {
9483                 printf(" %d instructions downloaded\n", downloaded);
9484                 printf("%s: Features 0x%x, Bugs 0x%x, Flags 0x%x\n",
9485                        ahd_name(ahd), ahd->features, ahd->bugs, ahd->flags);
9486         }
9487 }
9488
9489 static int
9490 ahd_check_patch(struct ahd_softc *ahd, struct patch **start_patch,
9491                 u_int start_instr, u_int *skip_addr)
9492 {
9493         struct  patch *cur_patch;
9494         struct  patch *last_patch;
9495         u_int   num_patches;
9496
9497         num_patches = ARRAY_SIZE(patches);
9498         last_patch = &patches[num_patches];
9499         cur_patch = *start_patch;
9500
9501         while (cur_patch < last_patch && start_instr == cur_patch->begin) {
9502
9503                 if (cur_patch->patch_func(ahd) == 0) {
9504
9505                         /* Start rejecting code */
9506                         *skip_addr = start_instr + cur_patch->skip_instr;
9507                         cur_patch += cur_patch->skip_patch;
9508                 } else {
9509                         /* Accepted this patch.  Advance to the next
9510                          * one and wait for our intruction pointer to
9511                          * hit this point.
9512                          */
9513                         cur_patch++;
9514                 }
9515         }
9516
9517         *start_patch = cur_patch;
9518         if (start_instr < *skip_addr)
9519                 /* Still skipping */
9520                 return (0);
9521
9522         return (1);
9523 }
9524
9525 static u_int
9526 ahd_resolve_seqaddr(struct ahd_softc *ahd, u_int address)
9527 {
9528         struct patch *cur_patch;
9529         int address_offset;
9530         u_int skip_addr;
9531         u_int i;
9532
9533         address_offset = 0;
9534         cur_patch = patches;
9535         skip_addr = 0;
9536
9537         for (i = 0; i < address;) {
9538
9539                 ahd_check_patch(ahd, &cur_patch, i, &skip_addr);
9540
9541                 if (skip_addr > i) {
9542                         int end_addr;
9543
9544                         end_addr = min(address, skip_addr);
9545                         address_offset += end_addr - i;
9546                         i = skip_addr;
9547                 } else {
9548                         i++;
9549                 }
9550         }
9551         return (address - address_offset);
9552 }
9553
9554 static void
9555 ahd_download_instr(struct ahd_softc *ahd, u_int instrptr, uint8_t *dconsts)
9556 {
9557         union   ins_formats instr;
9558         struct  ins_format1 *fmt1_ins;
9559         struct  ins_format3 *fmt3_ins;
9560         u_int   opcode;
9561
9562         /*
9563          * The firmware is always compiled into a little endian format.
9564          */
9565         instr.integer = ahd_le32toh(*(uint32_t*)&seqprog[instrptr * 4]);
9566
9567         fmt1_ins = &instr.format1;
9568         fmt3_ins = NULL;
9569
9570         /* Pull the opcode */
9571         opcode = instr.format1.opcode;
9572         switch (opcode) {
9573         case AIC_OP_JMP:
9574         case AIC_OP_JC:
9575         case AIC_OP_JNC:
9576         case AIC_OP_CALL:
9577         case AIC_OP_JNE:
9578         case AIC_OP_JNZ:
9579         case AIC_OP_JE:
9580         case AIC_OP_JZ:
9581         {
9582                 fmt3_ins = &instr.format3;
9583                 fmt3_ins->address = ahd_resolve_seqaddr(ahd, fmt3_ins->address);
9584                 /* FALLTHROUGH */
9585         }
9586         case AIC_OP_OR:
9587         case AIC_OP_AND:
9588         case AIC_OP_XOR:
9589         case AIC_OP_ADD:
9590         case AIC_OP_ADC:
9591         case AIC_OP_BMOV:
9592                 if (fmt1_ins->parity != 0) {
9593                         fmt1_ins->immediate = dconsts[fmt1_ins->immediate];
9594                 }
9595                 fmt1_ins->parity = 0;
9596                 /* FALLTHROUGH */
9597         case AIC_OP_ROL:
9598         {
9599                 int i, count;
9600
9601                 /* Calculate odd parity for the instruction */
9602                 for (i = 0, count = 0; i < 31; i++) {
9603                         uint32_t mask;
9604
9605                         mask = 0x01 << i;
9606                         if ((instr.integer & mask) != 0)
9607                                 count++;
9608                 }
9609                 if ((count & 0x01) == 0)
9610                         instr.format1.parity = 1;
9611
9612                 /* The sequencer is a little endian cpu */
9613                 instr.integer = ahd_htole32(instr.integer);
9614                 ahd_outsb(ahd, SEQRAM, instr.bytes, 4);
9615                 break;
9616         }
9617         default:
9618                 panic("Unknown opcode encountered in seq program");
9619                 break;
9620         }
9621 }
9622
9623 static int
9624 ahd_probe_stack_size(struct ahd_softc *ahd)
9625 {
9626         int last_probe;
9627
9628         last_probe = 0;
9629         while (1) {
9630                 int i;
9631
9632                 /*
9633                  * We avoid using 0 as a pattern to avoid
9634                  * confusion if the stack implementation
9635                  * "back-fills" with zeros when "poping'
9636                  * entries.
9637                  */
9638                 for (i = 1; i <= last_probe+1; i++) {
9639                        ahd_outb(ahd, STACK, i & 0xFF);
9640                        ahd_outb(ahd, STACK, (i >> 8) & 0xFF);
9641                 }
9642
9643                 /* Verify */
9644                 for (i = last_probe+1; i > 0; i--) {
9645                         u_int stack_entry;
9646
9647                         stack_entry = ahd_inb(ahd, STACK)
9648                                     |(ahd_inb(ahd, STACK) << 8);
9649                         if (stack_entry != i)
9650                                 goto sized;
9651                 }
9652                 last_probe++;
9653         }
9654 sized:
9655         return (last_probe);
9656 }
9657
9658 int
9659 ahd_print_register(ahd_reg_parse_entry_t *table, u_int num_entries,
9660                    const char *name, u_int address, u_int value,
9661                    u_int *cur_column, u_int wrap_point)
9662 {
9663         int     printed;
9664         u_int   printed_mask;
9665
9666         if (cur_column != NULL && *cur_column >= wrap_point) {
9667                 printf("\n");
9668                 *cur_column = 0;
9669         }
9670         printed = printf("%s[0x%x]", name, value);
9671         if (table == NULL) {
9672                 printed += printf(" ");
9673                 *cur_column += printed;
9674                 return (printed);
9675         }
9676         printed_mask = 0;
9677         while (printed_mask != 0xFF) {
9678                 int entry;
9679
9680                 for (entry = 0; entry < num_entries; entry++) {
9681                         if (((value & table[entry].mask)
9682                           != table[entry].value)
9683                          || ((printed_mask & table[entry].mask)
9684                           == table[entry].mask))
9685                                 continue;
9686
9687                         printed += printf("%s%s",
9688                                           printed_mask == 0 ? ":(" : "|",
9689                                           table[entry].name);
9690                         printed_mask |= table[entry].mask;
9691                         
9692                         break;
9693                 }
9694                 if (entry >= num_entries)
9695                         break;
9696         }
9697         if (printed_mask != 0)
9698                 printed += printf(") ");
9699         else
9700                 printed += printf(" ");
9701         if (cur_column != NULL)
9702                 *cur_column += printed;
9703         return (printed);
9704 }
9705
9706 void
9707 ahd_dump_card_state(struct ahd_softc *ahd)
9708 {
9709         struct scb      *scb;
9710         ahd_mode_state   saved_modes;
9711         u_int            dffstat;
9712         int              paused;
9713         u_int            scb_index;
9714         u_int            saved_scb_index;
9715         u_int            cur_col;
9716         int              i;
9717
9718         if (ahd_is_paused(ahd)) {
9719                 paused = 1;
9720         } else {
9721                 paused = 0;
9722                 ahd_pause(ahd);
9723         }
9724         saved_modes = ahd_save_modes(ahd);
9725         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
9726         printf(">>>>>>>>>>>>>>>>>> Dump Card State Begins <<<<<<<<<<<<<<<<<\n"
9727                "%s: Dumping Card State at program address 0x%x Mode 0x%x\n",
9728                ahd_name(ahd), 
9729                ahd_inw(ahd, CURADDR),
9730                ahd_build_mode_state(ahd, ahd->saved_src_mode,
9731                                     ahd->saved_dst_mode));
9732         if (paused)
9733                 printf("Card was paused\n");
9734
9735         if (ahd_check_cmdcmpltqueues(ahd))
9736                 printf("Completions are pending\n");
9737
9738         /*
9739          * Mode independent registers.
9740          */
9741         cur_col = 0;
9742         ahd_intstat_print(ahd_inb(ahd, INTSTAT), &cur_col, 50);
9743         ahd_seloid_print(ahd_inb(ahd, SELOID), &cur_col, 50);
9744         ahd_selid_print(ahd_inb(ahd, SELID), &cur_col, 50);
9745         ahd_hs_mailbox_print(ahd_inb(ahd, LOCAL_HS_MAILBOX), &cur_col, 50);
9746         ahd_intctl_print(ahd_inb(ahd, INTCTL), &cur_col, 50);
9747         ahd_seqintstat_print(ahd_inb(ahd, SEQINTSTAT), &cur_col, 50);
9748         ahd_saved_mode_print(ahd_inb(ahd, SAVED_MODE), &cur_col, 50);
9749         ahd_dffstat_print(ahd_inb(ahd, DFFSTAT), &cur_col, 50);
9750         ahd_scsisigi_print(ahd_inb(ahd, SCSISIGI), &cur_col, 50);
9751         ahd_scsiphase_print(ahd_inb(ahd, SCSIPHASE), &cur_col, 50);
9752         ahd_scsibus_print(ahd_inb(ahd, SCSIBUS), &cur_col, 50);
9753         ahd_lastphase_print(ahd_inb(ahd, LASTPHASE), &cur_col, 50);
9754         ahd_scsiseq0_print(ahd_inb(ahd, SCSISEQ0), &cur_col, 50);
9755         ahd_scsiseq1_print(ahd_inb(ahd, SCSISEQ1), &cur_col, 50);
9756         ahd_seqctl0_print(ahd_inb(ahd, SEQCTL0), &cur_col, 50);
9757         ahd_seqintctl_print(ahd_inb(ahd, SEQINTCTL), &cur_col, 50);
9758         ahd_seq_flags_print(ahd_inb(ahd, SEQ_FLAGS), &cur_col, 50);
9759         ahd_seq_flags2_print(ahd_inb(ahd, SEQ_FLAGS2), &cur_col, 50);
9760         ahd_qfreeze_count_print(ahd_inw(ahd, QFREEZE_COUNT), &cur_col, 50);
9761         ahd_kernel_qfreeze_count_print(ahd_inw(ahd, KERNEL_QFREEZE_COUNT),
9762                                        &cur_col, 50);
9763         ahd_mk_message_scb_print(ahd_inw(ahd, MK_MESSAGE_SCB), &cur_col, 50);
9764         ahd_mk_message_scsiid_print(ahd_inb(ahd, MK_MESSAGE_SCSIID),
9765                                     &cur_col, 50);
9766         ahd_sstat0_print(ahd_inb(ahd, SSTAT0), &cur_col, 50);
9767         ahd_sstat1_print(ahd_inb(ahd, SSTAT1), &cur_col, 50);
9768         ahd_sstat2_print(ahd_inb(ahd, SSTAT2), &cur_col, 50);
9769         ahd_sstat3_print(ahd_inb(ahd, SSTAT3), &cur_col, 50);
9770         ahd_perrdiag_print(ahd_inb(ahd, PERRDIAG), &cur_col, 50);
9771         ahd_simode1_print(ahd_inb(ahd, SIMODE1), &cur_col, 50);
9772         ahd_lqistat0_print(ahd_inb(ahd, LQISTAT0), &cur_col, 50);
9773         ahd_lqistat1_print(ahd_inb(ahd, LQISTAT1), &cur_col, 50);
9774         ahd_lqistat2_print(ahd_inb(ahd, LQISTAT2), &cur_col, 50);
9775         ahd_lqostat0_print(ahd_inb(ahd, LQOSTAT0), &cur_col, 50);
9776         ahd_lqostat1_print(ahd_inb(ahd, LQOSTAT1), &cur_col, 50);
9777         ahd_lqostat2_print(ahd_inb(ahd, LQOSTAT2), &cur_col, 50);
9778         printf("\n");
9779         printf("\nSCB Count = %d CMDS_PENDING = %d LASTSCB 0x%x "
9780                "CURRSCB 0x%x NEXTSCB 0x%x\n",
9781                ahd->scb_data.numscbs, ahd_inw(ahd, CMDS_PENDING),
9782                ahd_inw(ahd, LASTSCB), ahd_inw(ahd, CURRSCB),
9783                ahd_inw(ahd, NEXTSCB));
9784         cur_col = 0;
9785         /* QINFIFO */
9786         ahd_search_qinfifo(ahd, CAM_TARGET_WILDCARD, ALL_CHANNELS,
9787                            CAM_LUN_WILDCARD, SCB_LIST_NULL,
9788                            ROLE_UNKNOWN, /*status*/0, SEARCH_PRINT);
9789         saved_scb_index = ahd_get_scbptr(ahd);
9790         printf("Pending list:");
9791         i = 0;
9792         LIST_FOREACH(scb, &ahd->pending_scbs, pending_links) {
9793                 if (i++ > AHD_SCB_MAX)
9794                         break;
9795                 cur_col = printf("\n%3d FIFO_USE[0x%x] ", SCB_GET_TAG(scb),
9796                                  ahd_inb_scbram(ahd, SCB_FIFO_USE_COUNT));
9797                 ahd_set_scbptr(ahd, SCB_GET_TAG(scb));
9798                 ahd_scb_control_print(ahd_inb_scbram(ahd, SCB_CONTROL),
9799                                       &cur_col, 60);
9800                 ahd_scb_scsiid_print(ahd_inb_scbram(ahd, SCB_SCSIID),
9801                                      &cur_col, 60);
9802         }
9803         printf("\nTotal %d\n", i);
9804
9805         printf("Kernel Free SCB list: ");
9806         i = 0;
9807         TAILQ_FOREACH(scb, &ahd->scb_data.free_scbs, links.tqe) {
9808                 struct scb *list_scb;
9809
9810                 list_scb = scb;
9811                 do {
9812                         printf("%d ", SCB_GET_TAG(list_scb));
9813                         list_scb = LIST_NEXT(list_scb, collision_links);
9814                 } while (list_scb && i++ < AHD_SCB_MAX);
9815         }
9816
9817         LIST_FOREACH(scb, &ahd->scb_data.any_dev_free_scb_list, links.le) {
9818                 if (i++ > AHD_SCB_MAX)
9819                         break;
9820                 printf("%d ", SCB_GET_TAG(scb));
9821         }
9822         printf("\n");
9823
9824         printf("Sequencer Complete DMA-inprog list: ");
9825         scb_index = ahd_inw(ahd, COMPLETE_SCB_DMAINPROG_HEAD);
9826         i = 0;
9827         while (!SCBID_IS_NULL(scb_index) && i++ < AHD_SCB_MAX) {
9828                 ahd_set_scbptr(ahd, scb_index);
9829                 printf("%d ", scb_index);
9830                 scb_index = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
9831         }
9832         printf("\n");
9833
9834         printf("Sequencer Complete list: ");
9835         scb_index = ahd_inw(ahd, COMPLETE_SCB_HEAD);
9836         i = 0;
9837         while (!SCBID_IS_NULL(scb_index) && i++ < AHD_SCB_MAX) {
9838                 ahd_set_scbptr(ahd, scb_index);
9839                 printf("%d ", scb_index);
9840                 scb_index = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
9841         }
9842         printf("\n");
9843
9844         
9845         printf("Sequencer DMA-Up and Complete list: ");
9846         scb_index = ahd_inw(ahd, COMPLETE_DMA_SCB_HEAD);
9847         i = 0;
9848         while (!SCBID_IS_NULL(scb_index) && i++ < AHD_SCB_MAX) {
9849                 ahd_set_scbptr(ahd, scb_index);
9850                 printf("%d ", scb_index);
9851                 scb_index = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
9852         }
9853         printf("\n");
9854         printf("Sequencer On QFreeze and Complete list: ");
9855         scb_index = ahd_inw(ahd, COMPLETE_ON_QFREEZE_HEAD);
9856         i = 0;
9857         while (!SCBID_IS_NULL(scb_index) && i++ < AHD_SCB_MAX) {
9858                 ahd_set_scbptr(ahd, scb_index);
9859                 printf("%d ", scb_index);
9860                 scb_index = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
9861         }
9862         printf("\n");
9863         ahd_set_scbptr(ahd, saved_scb_index);
9864         dffstat = ahd_inb(ahd, DFFSTAT);
9865         for (i = 0; i < 2; i++) {
9866 #ifdef AHD_DEBUG
9867                 struct scb *fifo_scb;
9868 #endif
9869                 u_int       fifo_scbptr;
9870
9871                 ahd_set_modes(ahd, AHD_MODE_DFF0 + i, AHD_MODE_DFF0 + i);
9872                 fifo_scbptr = ahd_get_scbptr(ahd);
9873                 printf("\n\n%s: FIFO%d %s, LONGJMP == 0x%x, SCB 0x%x\n",
9874                        ahd_name(ahd), i,
9875                        (dffstat & (FIFO0FREE << i)) ? "Free" : "Active",
9876                        ahd_inw(ahd, LONGJMP_ADDR), fifo_scbptr);
9877                 cur_col = 0;
9878                 ahd_seqimode_print(ahd_inb(ahd, SEQIMODE), &cur_col, 50);
9879                 ahd_seqintsrc_print(ahd_inb(ahd, SEQINTSRC), &cur_col, 50);
9880                 ahd_dfcntrl_print(ahd_inb(ahd, DFCNTRL), &cur_col, 50);
9881                 ahd_dfstatus_print(ahd_inb(ahd, DFSTATUS), &cur_col, 50);
9882                 ahd_sg_cache_shadow_print(ahd_inb(ahd, SG_CACHE_SHADOW),
9883                                           &cur_col, 50);
9884                 ahd_sg_state_print(ahd_inb(ahd, SG_STATE), &cur_col, 50);
9885                 ahd_dffsxfrctl_print(ahd_inb(ahd, DFFSXFRCTL), &cur_col, 50);
9886                 ahd_soffcnt_print(ahd_inb(ahd, SOFFCNT), &cur_col, 50);
9887                 ahd_mdffstat_print(ahd_inb(ahd, MDFFSTAT), &cur_col, 50);
9888                 if (cur_col > 50) {
9889                         printf("\n");
9890                         cur_col = 0;
9891                 }
9892                 cur_col += printf("SHADDR = 0x%x%x, SHCNT = 0x%x ",
9893                                   ahd_inl(ahd, SHADDR+4),
9894                                   ahd_inl(ahd, SHADDR),
9895                                   (ahd_inb(ahd, SHCNT)
9896                                 | (ahd_inb(ahd, SHCNT + 1) << 8)
9897                                 | (ahd_inb(ahd, SHCNT + 2) << 16)));
9898                 if (cur_col > 50) {
9899                         printf("\n");
9900                         cur_col = 0;
9901                 }
9902                 cur_col += printf("HADDR = 0x%x%x, HCNT = 0x%x ",
9903                                   ahd_inl(ahd, HADDR+4),
9904                                   ahd_inl(ahd, HADDR),
9905                                   (ahd_inb(ahd, HCNT)
9906                                 | (ahd_inb(ahd, HCNT + 1) << 8)
9907                                 | (ahd_inb(ahd, HCNT + 2) << 16)));
9908                 ahd_ccsgctl_print(ahd_inb(ahd, CCSGCTL), &cur_col, 50);
9909 #ifdef AHD_DEBUG
9910                 if ((ahd_debug & AHD_SHOW_SG) != 0) {
9911                         fifo_scb = ahd_lookup_scb(ahd, fifo_scbptr);
9912                         if (fifo_scb != NULL)
9913                                 ahd_dump_sglist(fifo_scb);
9914                 }
9915 #endif
9916         }
9917         printf("\nLQIN: ");
9918         for (i = 0; i < 20; i++)
9919                 printf("0x%x ", ahd_inb(ahd, LQIN + i));
9920         printf("\n");
9921         ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
9922         printf("%s: LQISTATE = 0x%x, LQOSTATE = 0x%x, OPTIONMODE = 0x%x\n",
9923                ahd_name(ahd), ahd_inb(ahd, LQISTATE), ahd_inb(ahd, LQOSTATE),
9924                ahd_inb(ahd, OPTIONMODE));
9925         printf("%s: OS_SPACE_CNT = 0x%x MAXCMDCNT = 0x%x\n",
9926                ahd_name(ahd), ahd_inb(ahd, OS_SPACE_CNT),
9927                ahd_inb(ahd, MAXCMDCNT));
9928         printf("%s: SAVED_SCSIID = 0x%x SAVED_LUN = 0x%x\n",
9929                ahd_name(ahd), ahd_inb(ahd, SAVED_SCSIID),
9930                ahd_inb(ahd, SAVED_LUN));
9931         ahd_simode0_print(ahd_inb(ahd, SIMODE0), &cur_col, 50);
9932         printf("\n");
9933         ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
9934         cur_col = 0;
9935         ahd_ccscbctl_print(ahd_inb(ahd, CCSCBCTL), &cur_col, 50);
9936         printf("\n");
9937         ahd_set_modes(ahd, ahd->saved_src_mode, ahd->saved_dst_mode);
9938         printf("%s: REG0 == 0x%x, SINDEX = 0x%x, DINDEX = 0x%x\n",
9939                ahd_name(ahd), ahd_inw(ahd, REG0), ahd_inw(ahd, SINDEX),
9940                ahd_inw(ahd, DINDEX));
9941         printf("%s: SCBPTR == 0x%x, SCB_NEXT == 0x%x, SCB_NEXT2 == 0x%x\n",
9942                ahd_name(ahd), ahd_get_scbptr(ahd),
9943                ahd_inw_scbram(ahd, SCB_NEXT),
9944                ahd_inw_scbram(ahd, SCB_NEXT2));
9945         printf("CDB %x %x %x %x %x %x\n",
9946                ahd_inb_scbram(ahd, SCB_CDB_STORE),
9947                ahd_inb_scbram(ahd, SCB_CDB_STORE+1),
9948                ahd_inb_scbram(ahd, SCB_CDB_STORE+2),
9949                ahd_inb_scbram(ahd, SCB_CDB_STORE+3),
9950                ahd_inb_scbram(ahd, SCB_CDB_STORE+4),
9951                ahd_inb_scbram(ahd, SCB_CDB_STORE+5));
9952         printf("STACK:");
9953         for (i = 0; i < ahd->stack_size; i++) {
9954                 ahd->saved_stack[i] =
9955                     ahd_inb(ahd, STACK)|(ahd_inb(ahd, STACK) << 8);
9956                 printf(" 0x%x", ahd->saved_stack[i]);
9957         }
9958         for (i = ahd->stack_size-1; i >= 0; i--) {
9959                 ahd_outb(ahd, STACK, ahd->saved_stack[i] & 0xFF);
9960                 ahd_outb(ahd, STACK, (ahd->saved_stack[i] >> 8) & 0xFF);
9961         }
9962         printf("\n<<<<<<<<<<<<<<<<< Dump Card State Ends >>>>>>>>>>>>>>>>>>\n");
9963         ahd_restore_modes(ahd, saved_modes);
9964         if (paused == 0)
9965                 ahd_unpause(ahd);
9966 }
9967
9968 #if 0
9969 void
9970 ahd_dump_scbs(struct ahd_softc *ahd)
9971 {
9972         ahd_mode_state saved_modes;
9973         u_int          saved_scb_index;
9974         int            i;
9975
9976         saved_modes = ahd_save_modes(ahd);
9977         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
9978         saved_scb_index = ahd_get_scbptr(ahd);
9979         for (i = 0; i < AHD_SCB_MAX; i++) {
9980                 ahd_set_scbptr(ahd, i);
9981                 printf("%3d", i);
9982                 printf("(CTRL 0x%x ID 0x%x N 0x%x N2 0x%x SG 0x%x, RSG 0x%x)\n",
9983                        ahd_inb_scbram(ahd, SCB_CONTROL),
9984                        ahd_inb_scbram(ahd, SCB_SCSIID),
9985                        ahd_inw_scbram(ahd, SCB_NEXT),
9986                        ahd_inw_scbram(ahd, SCB_NEXT2),
9987                        ahd_inl_scbram(ahd, SCB_SGPTR),
9988                        ahd_inl_scbram(ahd, SCB_RESIDUAL_SGPTR));
9989         }
9990         printf("\n");
9991         ahd_set_scbptr(ahd, saved_scb_index);
9992         ahd_restore_modes(ahd, saved_modes);
9993 }
9994 #endif  /*  0  */
9995
9996 /**************************** Flexport Logic **********************************/
9997 /*
9998  * Read count 16bit words from 16bit word address start_addr from the
9999  * SEEPROM attached to the controller, into buf, using the controller's
10000  * SEEPROM reading state machine.  Optionally treat the data as a byte
10001  * stream in terms of byte order.
10002  */
10003 int
10004 ahd_read_seeprom(struct ahd_softc *ahd, uint16_t *buf,
10005                  u_int start_addr, u_int count, int bytestream)
10006 {
10007         u_int cur_addr;
10008         u_int end_addr;
10009         int   error;
10010
10011         /*
10012          * If we never make it through the loop even once,
10013          * we were passed invalid arguments.
10014          */
10015         error = EINVAL;
10016         AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
10017         end_addr = start_addr + count;
10018         for (cur_addr = start_addr; cur_addr < end_addr; cur_addr++) {
10019
10020                 ahd_outb(ahd, SEEADR, cur_addr);
10021                 ahd_outb(ahd, SEECTL, SEEOP_READ | SEESTART);
10022                 
10023                 error = ahd_wait_seeprom(ahd);
10024                 if (error)
10025                         break;
10026                 if (bytestream != 0) {
10027                         uint8_t *bytestream_ptr;
10028
10029                         bytestream_ptr = (uint8_t *)buf;
10030                         *bytestream_ptr++ = ahd_inb(ahd, SEEDAT);
10031                         *bytestream_ptr = ahd_inb(ahd, SEEDAT+1);
10032                 } else {
10033                         /*
10034                          * ahd_inw() already handles machine byte order.
10035                          */
10036                         *buf = ahd_inw(ahd, SEEDAT);
10037                 }
10038                 buf++;
10039         }
10040         return (error);
10041 }
10042
10043 /*
10044  * Write count 16bit words from buf, into SEEPROM attache to the
10045  * controller starting at 16bit word address start_addr, using the
10046  * controller's SEEPROM writing state machine.
10047  */
10048 int
10049 ahd_write_seeprom(struct ahd_softc *ahd, uint16_t *buf,
10050                   u_int start_addr, u_int count)
10051 {
10052         u_int cur_addr;
10053         u_int end_addr;
10054         int   error;
10055         int   retval;
10056
10057         AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
10058         error = ENOENT;
10059
10060         /* Place the chip into write-enable mode */
10061         ahd_outb(ahd, SEEADR, SEEOP_EWEN_ADDR);
10062         ahd_outb(ahd, SEECTL, SEEOP_EWEN | SEESTART);
10063         error = ahd_wait_seeprom(ahd);
10064         if (error)
10065                 return (error);
10066
10067         /*
10068          * Write the data.  If we don't get throught the loop at
10069          * least once, the arguments were invalid.
10070          */
10071         retval = EINVAL;
10072         end_addr = start_addr + count;
10073         for (cur_addr = start_addr; cur_addr < end_addr; cur_addr++) {
10074                 ahd_outw(ahd, SEEDAT, *buf++);
10075                 ahd_outb(ahd, SEEADR, cur_addr);
10076                 ahd_outb(ahd, SEECTL, SEEOP_WRITE | SEESTART);
10077                 
10078                 retval = ahd_wait_seeprom(ahd);
10079                 if (retval)
10080                         break;
10081         }
10082
10083         /*
10084          * Disable writes.
10085          */
10086         ahd_outb(ahd, SEEADR, SEEOP_EWDS_ADDR);
10087         ahd_outb(ahd, SEECTL, SEEOP_EWDS | SEESTART);
10088         error = ahd_wait_seeprom(ahd);
10089         if (error)
10090                 return (error);
10091         return (retval);
10092 }
10093
10094 /*
10095  * Wait ~100us for the serial eeprom to satisfy our request.
10096  */
10097 static int
10098 ahd_wait_seeprom(struct ahd_softc *ahd)
10099 {
10100         int cnt;
10101
10102         cnt = 5000;
10103         while ((ahd_inb(ahd, SEESTAT) & (SEEARBACK|SEEBUSY)) != 0 && --cnt)
10104                 ahd_delay(5);
10105
10106         if (cnt == 0)
10107                 return (ETIMEDOUT);
10108         return (0);
10109 }
10110
10111 /*
10112  * Validate the two checksums in the per_channel
10113  * vital product data struct.
10114  */
10115 static int
10116 ahd_verify_vpd_cksum(struct vpd_config *vpd)
10117 {
10118         int i;
10119         int maxaddr;
10120         uint32_t checksum;
10121         uint8_t *vpdarray;
10122
10123         vpdarray = (uint8_t *)vpd;
10124         maxaddr = offsetof(struct vpd_config, vpd_checksum);
10125         checksum = 0;
10126         for (i = offsetof(struct vpd_config, resource_type); i < maxaddr; i++)
10127                 checksum = checksum + vpdarray[i];
10128         if (checksum == 0
10129          || (-checksum & 0xFF) != vpd->vpd_checksum)
10130                 return (0);
10131
10132         checksum = 0;
10133         maxaddr = offsetof(struct vpd_config, checksum);
10134         for (i = offsetof(struct vpd_config, default_target_flags);
10135              i < maxaddr; i++)
10136                 checksum = checksum + vpdarray[i];
10137         if (checksum == 0
10138          || (-checksum & 0xFF) != vpd->checksum)
10139                 return (0);
10140         return (1);
10141 }
10142
10143 int
10144 ahd_verify_cksum(struct seeprom_config *sc)
10145 {
10146         int i;
10147         int maxaddr;
10148         uint32_t checksum;
10149         uint16_t *scarray;
10150
10151         maxaddr = (sizeof(*sc)/2) - 1;
10152         checksum = 0;
10153         scarray = (uint16_t *)sc;
10154
10155         for (i = 0; i < maxaddr; i++)
10156                 checksum = checksum + scarray[i];
10157         if (checksum == 0
10158          || (checksum & 0xFFFF) != sc->checksum) {
10159                 return (0);
10160         } else {
10161                 return (1);
10162         }
10163 }
10164
10165 int
10166 ahd_acquire_seeprom(struct ahd_softc *ahd)
10167 {
10168         /*
10169          * We should be able to determine the SEEPROM type
10170          * from the flexport logic, but unfortunately not
10171          * all implementations have this logic and there is
10172          * no programatic method for determining if the logic
10173          * is present.
10174          */
10175         return (1);
10176 #if 0
10177         uint8_t seetype;
10178         int     error;
10179
10180         error = ahd_read_flexport(ahd, FLXADDR_ROMSTAT_CURSENSECTL, &seetype);
10181         if (error != 0
10182          || ((seetype & FLX_ROMSTAT_SEECFG) == FLX_ROMSTAT_SEE_NONE))
10183                 return (0);
10184         return (1);
10185 #endif
10186 }
10187
10188 void
10189 ahd_release_seeprom(struct ahd_softc *ahd)
10190 {
10191         /* Currently a no-op */
10192 }
10193
10194 /*
10195  * Wait at most 2 seconds for flexport arbitration to succeed.
10196  */
10197 static int
10198 ahd_wait_flexport(struct ahd_softc *ahd)
10199 {
10200         int cnt;
10201
10202         AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
10203         cnt = 1000000 * 2 / 5;
10204         while ((ahd_inb(ahd, BRDCTL) & FLXARBACK) == 0 && --cnt)
10205                 ahd_delay(5);
10206
10207         if (cnt == 0)
10208                 return (ETIMEDOUT);
10209         return (0);
10210 }
10211
10212 int
10213 ahd_write_flexport(struct ahd_softc *ahd, u_int addr, u_int value)
10214 {
10215         int error;
10216
10217         AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
10218         if (addr > 7)
10219                 panic("ahd_write_flexport: address out of range");
10220         ahd_outb(ahd, BRDCTL, BRDEN|(addr << 3));
10221         error = ahd_wait_flexport(ahd);
10222         if (error != 0)
10223                 return (error);
10224         ahd_outb(ahd, BRDDAT, value);
10225         ahd_flush_device_writes(ahd);
10226         ahd_outb(ahd, BRDCTL, BRDSTB|BRDEN|(addr << 3));
10227         ahd_flush_device_writes(ahd);
10228         ahd_outb(ahd, BRDCTL, BRDEN|(addr << 3));
10229         ahd_flush_device_writes(ahd);
10230         ahd_outb(ahd, BRDCTL, 0);
10231         ahd_flush_device_writes(ahd);
10232         return (0);
10233 }
10234
10235 int
10236 ahd_read_flexport(struct ahd_softc *ahd, u_int addr, uint8_t *value)
10237 {
10238         int     error;
10239
10240         AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
10241         if (addr > 7)
10242                 panic("ahd_read_flexport: address out of range");
10243         ahd_outb(ahd, BRDCTL, BRDRW|BRDEN|(addr << 3));
10244         error = ahd_wait_flexport(ahd);
10245         if (error != 0)
10246                 return (error);
10247         *value = ahd_inb(ahd, BRDDAT);
10248         ahd_outb(ahd, BRDCTL, 0);
10249         ahd_flush_device_writes(ahd);
10250         return (0);
10251 }
10252
10253 /************************* Target Mode ****************************************/
10254 #ifdef AHD_TARGET_MODE
10255 cam_status
10256 ahd_find_tmode_devs(struct ahd_softc *ahd, struct cam_sim *sim, union ccb *ccb,
10257                     struct ahd_tmode_tstate **tstate,
10258                     struct ahd_tmode_lstate **lstate,
10259                     int notfound_failure)
10260 {
10261
10262         if ((ahd->features & AHD_TARGETMODE) == 0)
10263                 return (CAM_REQ_INVALID);
10264
10265         /*
10266          * Handle the 'black hole' device that sucks up
10267          * requests to unattached luns on enabled targets.
10268          */
10269         if (ccb->ccb_h.target_id == CAM_TARGET_WILDCARD
10270          && ccb->ccb_h.target_lun == CAM_LUN_WILDCARD) {
10271                 *tstate = NULL;
10272                 *lstate = ahd->black_hole;
10273         } else {
10274                 u_int max_id;
10275
10276                 max_id = (ahd->features & AHD_WIDE) ? 16 : 8;
10277                 if (ccb->ccb_h.target_id >= max_id)
10278                         return (CAM_TID_INVALID);
10279
10280                 if (ccb->ccb_h.target_lun >= AHD_NUM_LUNS)
10281                         return (CAM_LUN_INVALID);
10282
10283                 *tstate = ahd->enabled_targets[ccb->ccb_h.target_id];
10284                 *lstate = NULL;
10285                 if (*tstate != NULL)
10286                         *lstate =
10287                             (*tstate)->enabled_luns[ccb->ccb_h.target_lun];
10288         }
10289
10290         if (notfound_failure != 0 && *lstate == NULL)
10291                 return (CAM_PATH_INVALID);
10292
10293         return (CAM_REQ_CMP);
10294 }
10295
10296 void
10297 ahd_handle_en_lun(struct ahd_softc *ahd, struct cam_sim *sim, union ccb *ccb)
10298 {
10299 #if NOT_YET
10300         struct     ahd_tmode_tstate *tstate;
10301         struct     ahd_tmode_lstate *lstate;
10302         struct     ccb_en_lun *cel;
10303         cam_status status;
10304         u_int      target;
10305         u_int      lun;
10306         u_int      target_mask;
10307         u_long     s;
10308         char       channel;
10309
10310         status = ahd_find_tmode_devs(ahd, sim, ccb, &tstate, &lstate,
10311                                      /*notfound_failure*/FALSE);
10312
10313         if (status != CAM_REQ_CMP) {
10314                 ccb->ccb_h.status = status;
10315                 return;
10316         }
10317
10318         if ((ahd->features & AHD_MULTIROLE) != 0) {
10319                 u_int      our_id;
10320
10321                 our_id = ahd->our_id;
10322                 if (ccb->ccb_h.target_id != our_id) {
10323                         if ((ahd->features & AHD_MULTI_TID) != 0
10324                          && (ahd->flags & AHD_INITIATORROLE) != 0) {
10325                                 /*
10326                                  * Only allow additional targets if
10327                                  * the initiator role is disabled.
10328                                  * The hardware cannot handle a re-select-in
10329                                  * on the initiator id during a re-select-out
10330                                  * on a different target id.
10331                                  */
10332                                 status = CAM_TID_INVALID;
10333                         } else if ((ahd->flags & AHD_INITIATORROLE) != 0
10334                                 || ahd->enabled_luns > 0) {
10335                                 /*
10336                                  * Only allow our target id to change
10337                                  * if the initiator role is not configured
10338                                  * and there are no enabled luns which
10339                                  * are attached to the currently registered
10340                                  * scsi id.
10341                                  */
10342                                 status = CAM_TID_INVALID;
10343                         }
10344                 }
10345         }
10346
10347         if (status != CAM_REQ_CMP) {
10348                 ccb->ccb_h.status = status;
10349                 return;
10350         }
10351
10352         /*
10353          * We now have an id that is valid.
10354          * If we aren't in target mode, switch modes.
10355          */
10356         if ((ahd->flags & AHD_TARGETROLE) == 0
10357          && ccb->ccb_h.target_id != CAM_TARGET_WILDCARD) {
10358                 u_long  s;
10359
10360                 printf("Configuring Target Mode\n");
10361                 ahd_lock(ahd, &s);
10362                 if (LIST_FIRST(&ahd->pending_scbs) != NULL) {
10363                         ccb->ccb_h.status = CAM_BUSY;
10364                         ahd_unlock(ahd, &s);
10365                         return;
10366                 }
10367                 ahd->flags |= AHD_TARGETROLE;
10368                 if ((ahd->features & AHD_MULTIROLE) == 0)
10369                         ahd->flags &= ~AHD_INITIATORROLE;
10370                 ahd_pause(ahd);
10371                 ahd_loadseq(ahd);
10372                 ahd_restart(ahd);
10373                 ahd_unlock(ahd, &s);
10374         }
10375         cel = &ccb->cel;
10376         target = ccb->ccb_h.target_id;
10377         lun = ccb->ccb_h.target_lun;
10378         channel = SIM_CHANNEL(ahd, sim);
10379         target_mask = 0x01 << target;
10380         if (channel == 'B')
10381                 target_mask <<= 8;
10382
10383         if (cel->enable != 0) {
10384                 u_int scsiseq1;
10385
10386                 /* Are we already enabled?? */
10387                 if (lstate != NULL) {
10388                         xpt_print_path(ccb->ccb_h.path);
10389                         printf("Lun already enabled\n");
10390                         ccb->ccb_h.status = CAM_LUN_ALRDY_ENA;
10391                         return;
10392                 }
10393
10394                 if (cel->grp6_len != 0
10395                  || cel->grp7_len != 0) {
10396                         /*
10397                          * Don't (yet?) support vendor
10398                          * specific commands.
10399                          */
10400                         ccb->ccb_h.status = CAM_REQ_INVALID;
10401                         printf("Non-zero Group Codes\n");
10402                         return;
10403                 }
10404
10405                 /*
10406                  * Seems to be okay.
10407                  * Setup our data structures.
10408                  */
10409                 if (target != CAM_TARGET_WILDCARD && tstate == NULL) {
10410                         tstate = ahd_alloc_tstate(ahd, target, channel);
10411                         if (tstate == NULL) {
10412                                 xpt_print_path(ccb->ccb_h.path);
10413                                 printf("Couldn't allocate tstate\n");
10414                                 ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
10415                                 return;
10416                         }
10417                 }
10418                 lstate = malloc(sizeof(*lstate), M_DEVBUF, M_NOWAIT);
10419                 if (lstate == NULL) {
10420                         xpt_print_path(ccb->ccb_h.path);
10421                         printf("Couldn't allocate lstate\n");
10422                         ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
10423                         return;
10424                 }
10425                 memset(lstate, 0, sizeof(*lstate));
10426                 status = xpt_create_path(&lstate->path, /*periph*/NULL,
10427                                          xpt_path_path_id(ccb->ccb_h.path),
10428                                          xpt_path_target_id(ccb->ccb_h.path),
10429                                          xpt_path_lun_id(ccb->ccb_h.path));
10430                 if (status != CAM_REQ_CMP) {
10431                         free(lstate, M_DEVBUF);
10432                         xpt_print_path(ccb->ccb_h.path);
10433                         printf("Couldn't allocate path\n");
10434                         ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
10435                         return;
10436                 }
10437                 SLIST_INIT(&lstate->accept_tios);
10438                 SLIST_INIT(&lstate->immed_notifies);
10439                 ahd_lock(ahd, &s);
10440                 ahd_pause(ahd);
10441                 if (target != CAM_TARGET_WILDCARD) {
10442                         tstate->enabled_luns[lun] = lstate;
10443                         ahd->enabled_luns++;
10444
10445                         if ((ahd->features & AHD_MULTI_TID) != 0) {
10446                                 u_int targid_mask;
10447
10448                                 targid_mask = ahd_inw(ahd, TARGID);
10449                                 targid_mask |= target_mask;
10450                                 ahd_outw(ahd, TARGID, targid_mask);
10451                                 ahd_update_scsiid(ahd, targid_mask);
10452                         } else {
10453                                 u_int our_id;
10454                                 char  channel;
10455
10456                                 channel = SIM_CHANNEL(ahd, sim);
10457                                 our_id = SIM_SCSI_ID(ahd, sim);
10458
10459                                 /*
10460                                  * This can only happen if selections
10461                                  * are not enabled
10462                                  */
10463                                 if (target != our_id) {
10464                                         u_int sblkctl;
10465                                         char  cur_channel;
10466                                         int   swap;
10467
10468                                         sblkctl = ahd_inb(ahd, SBLKCTL);
10469                                         cur_channel = (sblkctl & SELBUSB)
10470                                                     ? 'B' : 'A';
10471                                         if ((ahd->features & AHD_TWIN) == 0)
10472                                                 cur_channel = 'A';
10473                                         swap = cur_channel != channel;
10474                                         ahd->our_id = target;
10475
10476                                         if (swap)
10477                                                 ahd_outb(ahd, SBLKCTL,
10478                                                          sblkctl ^ SELBUSB);
10479
10480                                         ahd_outb(ahd, SCSIID, target);
10481
10482                                         if (swap)
10483                                                 ahd_outb(ahd, SBLKCTL, sblkctl);
10484                                 }
10485                         }
10486                 } else
10487                         ahd->black_hole = lstate;
10488                 /* Allow select-in operations */
10489                 if (ahd->black_hole != NULL && ahd->enabled_luns > 0) {
10490                         scsiseq1 = ahd_inb(ahd, SCSISEQ_TEMPLATE);
10491                         scsiseq1 |= ENSELI;
10492                         ahd_outb(ahd, SCSISEQ_TEMPLATE, scsiseq1);
10493                         scsiseq1 = ahd_inb(ahd, SCSISEQ1);
10494                         scsiseq1 |= ENSELI;
10495                         ahd_outb(ahd, SCSISEQ1, scsiseq1);
10496                 }
10497                 ahd_unpause(ahd);
10498                 ahd_unlock(ahd, &s);
10499                 ccb->ccb_h.status = CAM_REQ_CMP;
10500                 xpt_print_path(ccb->ccb_h.path);
10501                 printf("Lun now enabled for target mode\n");
10502         } else {
10503                 struct scb *scb;
10504                 int i, empty;
10505
10506                 if (lstate == NULL) {
10507                         ccb->ccb_h.status = CAM_LUN_INVALID;
10508                         return;
10509                 }
10510
10511                 ahd_lock(ahd, &s);
10512                 
10513                 ccb->ccb_h.status = CAM_REQ_CMP;
10514                 LIST_FOREACH(scb, &ahd->pending_scbs, pending_links) {
10515                         struct ccb_hdr *ccbh;
10516
10517                         ccbh = &scb->io_ctx->ccb_h;
10518                         if (ccbh->func_code == XPT_CONT_TARGET_IO
10519                          && !xpt_path_comp(ccbh->path, ccb->ccb_h.path)){
10520                                 printf("CTIO pending\n");
10521                                 ccb->ccb_h.status = CAM_REQ_INVALID;
10522                                 ahd_unlock(ahd, &s);
10523                                 return;
10524                         }
10525                 }
10526
10527                 if (SLIST_FIRST(&lstate->accept_tios) != NULL) {
10528                         printf("ATIOs pending\n");
10529                         ccb->ccb_h.status = CAM_REQ_INVALID;
10530                 }
10531
10532                 if (SLIST_FIRST(&lstate->immed_notifies) != NULL) {
10533                         printf("INOTs pending\n");
10534                         ccb->ccb_h.status = CAM_REQ_INVALID;
10535                 }
10536
10537                 if (ccb->ccb_h.status != CAM_REQ_CMP) {
10538                         ahd_unlock(ahd, &s);
10539                         return;
10540                 }
10541
10542                 xpt_print_path(ccb->ccb_h.path);
10543                 printf("Target mode disabled\n");
10544                 xpt_free_path(lstate->path);
10545                 free(lstate, M_DEVBUF);
10546
10547                 ahd_pause(ahd);
10548                 /* Can we clean up the target too? */
10549                 if (target != CAM_TARGET_WILDCARD) {
10550                         tstate->enabled_luns[lun] = NULL;
10551                         ahd->enabled_luns--;
10552                         for (empty = 1, i = 0; i < 8; i++)
10553                                 if (tstate->enabled_luns[i] != NULL) {
10554                                         empty = 0;
10555                                         break;
10556                                 }
10557
10558                         if (empty) {
10559                                 ahd_free_tstate(ahd, target, channel,
10560                                                 /*force*/FALSE);
10561                                 if (ahd->features & AHD_MULTI_TID) {
10562                                         u_int targid_mask;
10563
10564                                         targid_mask = ahd_inw(ahd, TARGID);
10565                                         targid_mask &= ~target_mask;
10566                                         ahd_outw(ahd, TARGID, targid_mask);
10567                                         ahd_update_scsiid(ahd, targid_mask);
10568                                 }
10569                         }
10570                 } else {
10571
10572                         ahd->black_hole = NULL;
10573
10574                         /*
10575                          * We can't allow selections without
10576                          * our black hole device.
10577                          */
10578                         empty = TRUE;
10579                 }
10580                 if (ahd->enabled_luns == 0) {
10581                         /* Disallow select-in */
10582                         u_int scsiseq1;
10583
10584                         scsiseq1 = ahd_inb(ahd, SCSISEQ_TEMPLATE);
10585                         scsiseq1 &= ~ENSELI;
10586                         ahd_outb(ahd, SCSISEQ_TEMPLATE, scsiseq1);
10587                         scsiseq1 = ahd_inb(ahd, SCSISEQ1);
10588                         scsiseq1 &= ~ENSELI;
10589                         ahd_outb(ahd, SCSISEQ1, scsiseq1);
10590
10591                         if ((ahd->features & AHD_MULTIROLE) == 0) {
10592                                 printf("Configuring Initiator Mode\n");
10593                                 ahd->flags &= ~AHD_TARGETROLE;
10594                                 ahd->flags |= AHD_INITIATORROLE;
10595                                 ahd_pause(ahd);
10596                                 ahd_loadseq(ahd);
10597                                 ahd_restart(ahd);
10598                                 /*
10599                                  * Unpaused.  The extra unpause
10600                                  * that follows is harmless.
10601                                  */
10602                         }
10603                 }
10604                 ahd_unpause(ahd);
10605                 ahd_unlock(ahd, &s);
10606         }
10607 #endif
10608 }
10609
10610 static void
10611 ahd_update_scsiid(struct ahd_softc *ahd, u_int targid_mask)
10612 {
10613 #if NOT_YET
10614         u_int scsiid_mask;
10615         u_int scsiid;
10616
10617         if ((ahd->features & AHD_MULTI_TID) == 0)
10618                 panic("ahd_update_scsiid called on non-multitid unit\n");
10619
10620         /*
10621          * Since we will rely on the TARGID mask
10622          * for selection enables, ensure that OID
10623          * in SCSIID is not set to some other ID
10624          * that we don't want to allow selections on.
10625          */
10626         if ((ahd->features & AHD_ULTRA2) != 0)
10627                 scsiid = ahd_inb(ahd, SCSIID_ULTRA2);
10628         else
10629                 scsiid = ahd_inb(ahd, SCSIID);
10630         scsiid_mask = 0x1 << (scsiid & OID);
10631         if ((targid_mask & scsiid_mask) == 0) {
10632                 u_int our_id;
10633
10634                 /* ffs counts from 1 */
10635                 our_id = ffs(targid_mask);
10636                 if (our_id == 0)
10637                         our_id = ahd->our_id;
10638                 else
10639                         our_id--;
10640                 scsiid &= TID;
10641                 scsiid |= our_id;
10642         }
10643         if ((ahd->features & AHD_ULTRA2) != 0)
10644                 ahd_outb(ahd, SCSIID_ULTRA2, scsiid);
10645         else
10646                 ahd_outb(ahd, SCSIID, scsiid);
10647 #endif
10648 }
10649
10650 void
10651 ahd_run_tqinfifo(struct ahd_softc *ahd, int paused)
10652 {
10653         struct target_cmd *cmd;
10654
10655         ahd_sync_tqinfifo(ahd, BUS_DMASYNC_POSTREAD);
10656         while ((cmd = &ahd->targetcmds[ahd->tqinfifonext])->cmd_valid != 0) {
10657
10658                 /*
10659                  * Only advance through the queue if we
10660                  * have the resources to process the command.
10661                  */
10662                 if (ahd_handle_target_cmd(ahd, cmd) != 0)
10663                         break;
10664
10665                 cmd->cmd_valid = 0;
10666                 ahd_dmamap_sync(ahd, ahd->shared_data_dmat,
10667                                 ahd->shared_data_map.dmamap,
10668                                 ahd_targetcmd_offset(ahd, ahd->tqinfifonext),
10669                                 sizeof(struct target_cmd),
10670                                 BUS_DMASYNC_PREREAD);
10671                 ahd->tqinfifonext++;
10672
10673                 /*
10674                  * Lazily update our position in the target mode incoming
10675                  * command queue as seen by the sequencer.
10676                  */
10677                 if ((ahd->tqinfifonext & (HOST_TQINPOS - 1)) == 1) {
10678                         u_int hs_mailbox;
10679
10680                         hs_mailbox = ahd_inb(ahd, HS_MAILBOX);
10681                         hs_mailbox &= ~HOST_TQINPOS;
10682                         hs_mailbox |= ahd->tqinfifonext & HOST_TQINPOS;
10683                         ahd_outb(ahd, HS_MAILBOX, hs_mailbox);
10684                 }
10685         }
10686 }
10687
10688 static int
10689 ahd_handle_target_cmd(struct ahd_softc *ahd, struct target_cmd *cmd)
10690 {
10691         struct    ahd_tmode_tstate *tstate;
10692         struct    ahd_tmode_lstate *lstate;
10693         struct    ccb_accept_tio *atio;
10694         uint8_t *byte;
10695         int       initiator;
10696         int       target;
10697         int       lun;
10698
10699         initiator = SCSIID_TARGET(ahd, cmd->scsiid);
10700         target = SCSIID_OUR_ID(cmd->scsiid);
10701         lun    = (cmd->identify & MSG_IDENTIFY_LUNMASK);
10702
10703         byte = cmd->bytes;
10704         tstate = ahd->enabled_targets[target];
10705         lstate = NULL;
10706         if (tstate != NULL)
10707                 lstate = tstate->enabled_luns[lun];
10708
10709         /*
10710          * Commands for disabled luns go to the black hole driver.
10711          */
10712         if (lstate == NULL)
10713                 lstate = ahd->black_hole;
10714
10715         atio = (struct ccb_accept_tio*)SLIST_FIRST(&lstate->accept_tios);
10716         if (atio == NULL) {
10717                 ahd->flags |= AHD_TQINFIFO_BLOCKED;
10718                 /*
10719                  * Wait for more ATIOs from the peripheral driver for this lun.
10720                  */
10721                 return (1);
10722         } else
10723                 ahd->flags &= ~AHD_TQINFIFO_BLOCKED;
10724 #ifdef AHD_DEBUG
10725         if ((ahd_debug & AHD_SHOW_TQIN) != 0)
10726                 printf("Incoming command from %d for %d:%d%s\n",
10727                        initiator, target, lun,
10728                        lstate == ahd->black_hole ? "(Black Holed)" : "");
10729 #endif
10730         SLIST_REMOVE_HEAD(&lstate->accept_tios, sim_links.sle);
10731
10732         if (lstate == ahd->black_hole) {
10733                 /* Fill in the wildcards */
10734                 atio->ccb_h.target_id = target;
10735                 atio->ccb_h.target_lun = lun;
10736         }
10737
10738         /*
10739          * Package it up and send it off to
10740          * whomever has this lun enabled.
10741          */
10742         atio->sense_len = 0;
10743         atio->init_id = initiator;
10744         if (byte[0] != 0xFF) {
10745                 /* Tag was included */
10746                 atio->tag_action = *byte++;
10747                 atio->tag_id = *byte++;
10748                 atio->ccb_h.flags = CAM_TAG_ACTION_VALID;
10749         } else {
10750                 atio->ccb_h.flags = 0;
10751         }
10752         byte++;
10753
10754         /* Okay.  Now determine the cdb size based on the command code */
10755         switch (*byte >> CMD_GROUP_CODE_SHIFT) {
10756         case 0:
10757                 atio->cdb_len = 6;
10758                 break;
10759         case 1:
10760         case 2:
10761                 atio->cdb_len = 10;
10762                 break;
10763         case 4:
10764                 atio->cdb_len = 16;
10765                 break;
10766         case 5:
10767                 atio->cdb_len = 12;
10768                 break;
10769         case 3:
10770         default:
10771                 /* Only copy the opcode. */
10772                 atio->cdb_len = 1;
10773                 printf("Reserved or VU command code type encountered\n");
10774                 break;
10775         }
10776         
10777         memcpy(atio->cdb_io.cdb_bytes, byte, atio->cdb_len);
10778
10779         atio->ccb_h.status |= CAM_CDB_RECVD;
10780
10781         if ((cmd->identify & MSG_IDENTIFY_DISCFLAG) == 0) {
10782                 /*
10783                  * We weren't allowed to disconnect.
10784                  * We're hanging on the bus until a
10785                  * continue target I/O comes in response
10786                  * to this accept tio.
10787                  */
10788 #ifdef AHD_DEBUG
10789                 if ((ahd_debug & AHD_SHOW_TQIN) != 0)
10790                         printf("Received Immediate Command %d:%d:%d - %p\n",
10791                                initiator, target, lun, ahd->pending_device);
10792 #endif
10793                 ahd->pending_device = lstate;
10794                 ahd_freeze_ccb((union ccb *)atio);
10795                 atio->ccb_h.flags |= CAM_DIS_DISCONNECT;
10796         }
10797         xpt_done((union ccb*)atio);
10798         return (0);
10799 }
10800
10801 #endif