Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most
[dragonfly.git] / sys / dev / disk / aha / aha.c
1 /*
2  * Generic register and struct definitions for the Adaptech 154x/164x
3  * SCSI host adapters. Product specific probe and attach routines can
4  * be found in:
5  *      aha 1540/1542B/1542C/1542CF/1542CP      aha_isa.c
6  *
7  * Copyright (c) 1998 M. Warner Losh.
8  * All Rights Reserved.
9  *
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions, and the following disclaimer,
16  *    without modification, immediately at the beginning of the file.
17  * 2. The name of the author may not be used to endorse or promote products
18  *    derived from this software without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
24  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * Derived from bt.c written by:
33  *
34  * Copyright (c) 1998 Justin T. Gibbs.
35  * All rights reserved.
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  * 1. Redistributions of source code must retain the above copyright
41  *    notice, this list of conditions, and the following disclaimer,
42  *    without modification, immediately at the beginning of the file.
43  * 2. The name of the author may not be used to endorse or promote products
44  *    derived from this software without specific prior written permission.
45  *
46  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
47  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
48  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
49  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
50  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
51  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
52  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
53  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
54  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
55  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
56  * SUCH DAMAGE.
57  *
58  * $FreeBSD: src/sys/dev/aha/aha.c,v 1.34.2.1 2000/08/02 22:24:39 peter Exp $
59  * $DragonFly: src/sys/dev/disk/aha/aha.c,v 1.2 2003/06/17 04:28:21 dillon Exp $
60  */
61
62 #include <sys/param.h>
63 #include <sys/systm.h> 
64 #include <sys/malloc.h>
65 #include <sys/buf.h>
66 #include <sys/kernel.h>
67  
68 #include <machine/bus_pio.h>
69 #include <machine/bus.h>
70 #include <machine/clock.h>
71
72 #include <cam/cam.h>
73 #include <cam/cam_ccb.h>
74 #include <cam/cam_sim.h>
75 #include <cam/cam_xpt_sim.h>
76 #include <cam/cam_debug.h>
77
78 #include <cam/scsi/scsi_message.h>
79
80 #include <vm/vm.h>
81 #include <vm/pmap.h>
82
83 #include <dev/aha/ahareg.h>
84
85 struct aha_softc *aha_softcs[NAHATOT];
86
87 #define PRVERB(x) if (bootverbose) printf x
88
89 /* Macro to determine that a rev is potentially a new valid one
90  * so that the driver doesn't keep breaking on new revs as it
91  * did for the CF and CP.
92  */
93 #define PROBABLY_NEW_BOARD(REV) (REV > 0x43 && REV < 0x56)
94
95 #ifndef MAX
96 #define MAX(a, b) ((a) > (b) ? (a) : (b))
97 #endif
98
99 /* MailBox Management functions */
100 static __inline void    ahanextinbox(struct aha_softc *aha);
101 static __inline void    ahanextoutbox(struct aha_softc *aha);
102
103 static __inline void
104 ahanextinbox(struct aha_softc *aha)
105 {
106         if (aha->cur_inbox == aha->last_inbox)
107                 aha->cur_inbox = aha->in_boxes;
108         else
109                 aha->cur_inbox++;
110 }
111
112 static __inline void
113 ahanextoutbox(struct aha_softc *aha)
114 {
115         if (aha->cur_outbox == aha->last_outbox)
116                 aha->cur_outbox = aha->out_boxes;
117         else
118                 aha->cur_outbox++;
119 }
120
121 #define ahautoa24(u,s3)                 \
122         (s3)[0] = ((u) >> 16) & 0xff;   \
123         (s3)[1] = ((u) >> 8) & 0xff;    \
124         (s3)[2] = (u) & 0xff;
125
126 #define aha_a24tou(s3) \
127         (((s3)[0] << 16) | ((s3)[1] << 8) | (s3)[2])
128
129 /* CCB Mangement functions */
130 static __inline u_int32_t               ahaccbvtop(struct aha_softc *aha,
131                                                   struct aha_ccb *accb);
132 static __inline struct aha_ccb*         ahaccbptov(struct aha_softc *aha,
133                                                   u_int32_t ccb_addr);
134
135 static __inline u_int32_t
136 ahaccbvtop(struct aha_softc *aha, struct aha_ccb *accb)
137 {
138         return (aha->aha_ccb_physbase
139               + (u_int32_t)((caddr_t)accb - (caddr_t)aha->aha_ccb_array));
140 }
141 static __inline struct aha_ccb *
142 ahaccbptov(struct aha_softc *aha, u_int32_t ccb_addr)
143 {
144         return (aha->aha_ccb_array +
145               + ((struct aha_ccb*)ccb_addr-(struct aha_ccb*)aha->aha_ccb_physbase));
146 }
147
148 static struct aha_ccb*  ahagetccb(struct aha_softc *aha);
149 static __inline void    ahafreeccb(struct aha_softc *aha, struct aha_ccb *accb);
150 static void             ahaallocccbs(struct aha_softc *aha);
151 static bus_dmamap_callback_t ahaexecuteccb;
152 static void             ahadone(struct aha_softc *aha, struct aha_ccb *accb,
153                                aha_mbi_comp_code_t comp_code);
154
155 /* Host adapter command functions */
156 static int      ahareset(struct aha_softc* aha, int hard_reset);
157
158 /* Initialization functions */
159 static int                      ahainitmboxes(struct aha_softc *aha);
160 static bus_dmamap_callback_t    ahamapmboxes;
161 static bus_dmamap_callback_t    ahamapccbs;
162 static bus_dmamap_callback_t    ahamapsgs;
163
164 /* Transfer Negotiation Functions */
165 static void ahafetchtransinfo(struct aha_softc *aha,
166                              struct ccb_trans_settings *cts);
167
168 /* CAM SIM entry points */
169 #define ccb_accb_ptr spriv_ptr0
170 #define ccb_aha_ptr spriv_ptr1
171 static void     ahaaction(struct cam_sim *sim, union ccb *ccb);
172 static void     ahapoll(struct cam_sim *sim);
173
174 /* Our timeout handler */
175 static timeout_t ahatimeout;
176
177 u_long aha_unit = 0;
178
179 /*
180  * Do our own re-probe protection until a configuration
181  * manager can do it for us.  This ensures that we don't
182  * reprobe a card already found by the EISA or PCI probes.
183  */
184 static struct aha_isa_port aha_isa_ports[] =
185 {
186         { 0x130, 4 },
187         { 0x134, 5 },
188         { 0x230, 2 },
189         { 0x234, 3 },
190         { 0x330, 0 },
191         { 0x334, 1 }
192 };
193
194 /*
195  * I/O ports listed in the order enumerated by the
196  * card for certain op codes.
197  */
198 static u_int16_t aha_board_ports[] =
199 {
200         0x330,
201         0x334,
202         0x230,
203         0x234,
204         0x130,
205         0x134
206 };
207
208 /* Exported functions */
209 struct aha_softc *
210 aha_alloc(int unit, bus_space_tag_t tag, bus_space_handle_t bsh)
211 {
212         struct  aha_softc *aha;  
213
214         if (unit != AHA_TEMP_UNIT) {
215                 if (unit >= NAHATOT) {
216                         printf("aha: unit number (%d) too high\n", unit);
217                         return NULL;
218                 }
219
220                 /*
221                  * Allocate a storage area for us
222                  */
223                 if (aha_softcs[unit]) {    
224                         printf("aha%d: memory already allocated\n", unit);
225                         return NULL;    
226                 }
227         }
228
229         aha = malloc(sizeof(struct aha_softc), M_DEVBUF, M_NOWAIT);
230         if (!aha) {
231                 printf("aha%d: cannot malloc!\n", unit);
232                 return NULL;    
233         }
234         bzero(aha, sizeof(struct aha_softc));
235         SLIST_INIT(&aha->free_aha_ccbs);
236         LIST_INIT(&aha->pending_ccbs);
237         SLIST_INIT(&aha->sg_maps);
238         aha->unit = unit;
239         aha->tag = tag;
240         aha->bsh = bsh;
241         aha->ccb_sg_opcode = INITIATOR_SG_CCB_WRESID;
242         aha->ccb_ccb_opcode = INITIATOR_CCB_WRESID;
243
244         if (aha->unit != AHA_TEMP_UNIT) {
245                 aha_softcs[unit] = aha;
246         }
247         return (aha);
248 }
249
250 void
251 aha_free(struct aha_softc *aha)
252 {
253         switch (aha->init_level) {
254         default:
255         case 8:
256         {
257                 struct sg_map_node *sg_map;
258
259                 while ((sg_map = SLIST_FIRST(&aha->sg_maps))!= NULL) {
260                         SLIST_REMOVE_HEAD(&aha->sg_maps, links);
261                         bus_dmamap_unload(aha->sg_dmat,
262                                           sg_map->sg_dmamap);
263                         bus_dmamem_free(aha->sg_dmat, sg_map->sg_vaddr,
264                                         sg_map->sg_dmamap);
265                         free(sg_map, M_DEVBUF);
266                 }
267                 bus_dma_tag_destroy(aha->sg_dmat);
268         }
269         case 7:
270                 bus_dmamap_unload(aha->ccb_dmat, aha->ccb_dmamap);
271         case 6:
272                 bus_dmamap_destroy(aha->ccb_dmat, aha->ccb_dmamap);
273                 bus_dmamem_free(aha->ccb_dmat, aha->aha_ccb_array,
274                                 aha->ccb_dmamap);
275         case 5:
276                 bus_dma_tag_destroy(aha->ccb_dmat);
277         case 4:
278                 bus_dmamap_unload(aha->mailbox_dmat, aha->mailbox_dmamap);
279         case 3:
280                 bus_dmamem_free(aha->mailbox_dmat, aha->in_boxes,
281                                 aha->mailbox_dmamap);
282                 bus_dmamap_destroy(aha->mailbox_dmat, aha->mailbox_dmamap);
283         case 2:
284                 bus_dma_tag_destroy(aha->buffer_dmat);
285         case 1:
286                 bus_dma_tag_destroy(aha->mailbox_dmat);
287         case 0:
288         }
289         if (aha->unit != AHA_TEMP_UNIT) {
290                 aha_softcs[aha->unit] = NULL;
291         }
292         free(aha, M_DEVBUF);
293 }
294
295 /*
296  * Probe the adapter and verify that the card is an Adaptec.
297  */
298 int
299 aha_probe(struct aha_softc* aha)
300 {
301         u_int    status;
302         u_int    intstat;
303         int      error;
304         board_id_data_t board_id;
305
306         /*
307          * See if the three I/O ports look reasonable.
308          * Touch the minimal number of registers in the
309          * failure case.
310          */
311         status = aha_inb(aha, STATUS_REG);
312         if ((status == 0)
313          || (status & (DIAG_ACTIVE|CMD_REG_BUSY|
314                        STATUS_REG_RSVD)) != 0) {
315                 PRVERB(("%s: status reg test failed %x\n", aha_name(aha),
316                         status));
317                 return (ENXIO);
318         }
319
320         intstat = aha_inb(aha, INTSTAT_REG);
321         if ((intstat & INTSTAT_REG_RSVD) != 0) {
322                 PRVERB(("%s: Failed Intstat Reg Test\n", aha_name(aha)));
323                 return (ENXIO);
324         }
325
326         /*
327          * Looking good so far.  Final test is to reset the
328          * adapter and fetch the board ID and ensure we aren't
329          * looking at a BusLogic.
330          */
331         if ((error = ahareset(aha, /*hard_reset*/TRUE)) != 0) {
332                 PRVERB(("%s: Failed Reset\n", aha_name(aha)));
333                 return (ENXIO);
334         }
335
336         /*
337          * Get the board ID.  We use this to see if we're dealing with
338          * a buslogic card or a aha card (or clone).
339          */
340         error = aha_cmd(aha, AOP_INQUIRE_BOARD_ID, NULL, /*parmlen*/0,
341                        (u_int8_t*)&board_id, sizeof(board_id),
342                        DEFAULT_CMD_TIMEOUT);
343         if (error != 0) {
344                 PRVERB(("%s: INQUIRE failed %x\n", aha_name(aha), error));
345                 return (ENXIO);
346         }
347         aha->fw_major = board_id.firmware_rev_major;
348         aha->fw_minor = board_id.firmware_rev_minor;
349         aha->boardid = board_id.board_type;
350
351         /*
352          * The Buslogic cards have an id of either 0x41 or 0x42.  So
353          * if those come up in the probe, we test the geometry register
354          * of the board.  Adaptec boards that are this old will not have
355          * this register, and return 0xff, while buslogic cards will return
356          * something different.
357          *
358          * It appears that for reasons unknow, for the for the
359          * aha-1542B cards, we need to wait a little bit before trying
360          * to read the geometry register.  I picked 10ms since we have
361          * reports that a for loop to 1000 did the trick, and this
362          * errs on the side of conservatism.  Besides, no one will
363          * notice a 10mS delay here, even the 1542B card users :-)
364          *
365          * Some compatible cards return 0 here.  Some cards also
366          * seem to return 0x7f.
367          *
368          * XXX I'm not sure how this will impact other cloned cards 
369          *
370          * This really should be replaced with the esetup command, since
371          * that appears to be more reliable.  This becomes more and more
372          * true over time as we discover more cards that don't read the
373          * geometry register consistantly.
374          */
375         if (aha->boardid <= 0x42) {
376                 /* Wait 10ms before reading */
377                 DELAY(10000);
378                 status = aha_inb(aha, GEOMETRY_REG);
379                 if (status != 0xff && status != 0x00 && status != 0x7f) {
380                         PRVERB(("%s: Geometry Register test failed 0x%x\n",
381                                 aha_name(aha), status));
382                         return (ENXIO);
383                 }
384         }
385         
386         return (0);
387 }
388
389 /*
390  * Pull the boards setup information and record it in our softc.
391  */
392 int
393 aha_fetch_adapter_info(struct aha_softc *aha)
394 {
395         setup_data_t    setup_info;
396         config_data_t config_data;
397         u_int8_t length_param;
398         int      error;
399         struct  aha_extbios extbios;
400         
401         switch (aha->boardid) {
402         case BOARD_1540_16HEAD_BIOS:
403                 snprintf(aha->model, sizeof(aha->model), "1540 16 head BIOS");
404                 break;
405         case BOARD_1540_64HEAD_BIOS:
406                 snprintf(aha->model, sizeof(aha->model), "1540 64 head BIOS");
407                 break;
408         case BOARD_1542:
409                 snprintf(aha->model, sizeof(aha->model), "1540/1542 64 head BIOS");
410                 break;
411         case BOARD_1640:
412                 snprintf(aha->model, sizeof(aha->model), "1640");
413                 break;
414         case BOARD_1740:
415                 snprintf(aha->model, sizeof(aha->model), "1740A/1742A/1744");
416                 break;
417         case BOARD_1542C:
418                 snprintf(aha->model, sizeof(aha->model), "1542C");
419                 break;
420         case BOARD_1542CF:
421                 snprintf(aha->model, sizeof(aha->model), "1542CF");
422                 break;
423         case BOARD_1542CP:
424                 snprintf(aha->model, sizeof(aha->model), "1542CP");
425                 break;
426         default:
427                 snprintf(aha->model, sizeof(aha->model), "Unknown");
428                 break;
429         }
430         /*
431          * If we are a new type of 1542 board (anything newer than a 1542C)
432          * then disable the extended bios so that the
433          * mailbox interface is unlocked.
434          * This is also true for the 1542B Version 3.20. First Adaptec
435          * board that supports >1Gb drives.
436          * No need to check the extended bios flags as some of the
437          * extensions that cause us problems are not flagged in that byte.
438          */
439         if (PROBABLY_NEW_BOARD(aha->boardid) ||
440                 (aha->boardid == 0x41
441                 && aha->fw_major == 0x31 && 
442                 aha->fw_minor >= 0x34)) {
443                 error = aha_cmd(aha, AOP_RETURN_EXT_BIOS_INFO, NULL,
444                         /*paramlen*/0, (u_char *)&extbios, sizeof(extbios),
445                         DEFAULT_CMD_TIMEOUT);
446                 error = aha_cmd(aha, AOP_MBOX_IF_ENABLE, (u_int8_t *)&extbios,
447                         /*paramlen*/2, NULL, 0, DEFAULT_CMD_TIMEOUT);
448         }
449         if (aha->boardid < 0x41)
450                 printf("%s: Warning: aha-1542A won't likely work.\n",
451                         aha_name(aha));
452
453         aha->max_sg = 17;               /* Need >= 17 to do 64k I/O */
454         aha->diff_bus = 0;
455         aha->extended_lun = 0;
456         aha->extended_trans = 0;
457         aha->max_ccbs = 16;
458         /* Determine Sync/Wide/Disc settings */
459         length_param = sizeof(setup_info);
460         error = aha_cmd(aha, AOP_INQUIRE_SETUP_INFO, &length_param,
461                        /*paramlen*/1, (u_int8_t*)&setup_info,
462                        sizeof(setup_info), DEFAULT_CMD_TIMEOUT);
463         if (error != 0) {
464                 printf("%s: aha_fetch_adapter_info - Failed "
465                        "Get Setup Info\n", aha_name(aha));
466                 return (error);
467         }
468         if (setup_info.initiate_sync != 0) {
469                 aha->sync_permitted = ALL_TARGETS;
470         }
471         aha->disc_permitted = ALL_TARGETS;
472
473         /* We need as many mailboxes as we can have ccbs */
474         aha->num_boxes = aha->max_ccbs;
475
476         /* Determine our SCSI ID */
477         
478         error = aha_cmd(aha, AOP_INQUIRE_CONFIG, NULL, /*parmlen*/0,
479                        (u_int8_t*)&config_data, sizeof(config_data),
480                        DEFAULT_CMD_TIMEOUT);
481         if (error != 0) {
482                 printf("%s: aha_fetch_adapter_info - Failed Get Config\n",
483                        aha_name(aha));
484                 return (error);
485         }
486         aha->scsi_id = config_data.scsi_id;
487         return (0);
488 }
489
490 /*
491  * Start the board, ready for normal operation
492  */
493 int
494 aha_init(struct aha_softc* aha)
495 {
496         /* Announce the Adapter */
497         printf("%s: AHA-%s FW Rev. %c.%c (ID=%x) ", aha_name(aha),
498                aha->model, aha->fw_major, aha->fw_minor, aha->boardid);
499
500         if (aha->diff_bus != 0)
501                 printf("Diff ");
502
503         printf("SCSI Host Adapter, SCSI ID %d, %d CCBs\n", aha->scsi_id,
504                aha->max_ccbs);
505
506         /*
507          * Create our DMA tags.  These tags define the kinds of device
508          * accessible memory allocations and memory mappings we will 
509          * need to perform during normal operation.
510          *
511          * Unless we need to further restrict the allocation, we rely
512          * on the restrictions of the parent dmat, hence the common
513          * use of MAXADDR and MAXSIZE.
514          */
515
516         /* DMA tag for mapping buffers into device visible space. */
517         if (bus_dma_tag_create(aha->parent_dmat, /*alignment*/1, /*boundary*/0,
518                                /*lowaddr*/BUS_SPACE_MAXADDR,
519                                /*highaddr*/BUS_SPACE_MAXADDR,
520                                /*filter*/NULL, /*filterarg*/NULL,
521                                /*maxsize*/MAXBSIZE, /*nsegments*/AHA_NSEG,
522                                /*maxsegsz*/BUS_SPACE_MAXSIZE_24BIT,
523                                /*flags*/BUS_DMA_ALLOCNOW,
524                                &aha->buffer_dmat) != 0) {
525                 goto error_exit;
526         }
527
528         aha->init_level++;
529         /* DMA tag for our mailboxes */
530         if (bus_dma_tag_create(aha->parent_dmat, /*alignment*/1, /*boundary*/0,
531                                /*lowaddr*/BUS_SPACE_MAXADDR,
532                                /*highaddr*/BUS_SPACE_MAXADDR,
533                                /*filter*/NULL, /*filterarg*/NULL,
534                                aha->num_boxes * (sizeof(aha_mbox_in_t)
535                                                + sizeof(aha_mbox_out_t)),
536                                /*nsegments*/1,
537                                /*maxsegsz*/BUS_SPACE_MAXSIZE_24BIT,
538                                /*flags*/0, &aha->mailbox_dmat) != 0) {
539                 goto error_exit;
540         }
541
542         aha->init_level++;
543
544         /* Allocation for our mailboxes */
545         if (bus_dmamem_alloc(aha->mailbox_dmat, (void **)&aha->out_boxes,
546                              BUS_DMA_NOWAIT, &aha->mailbox_dmamap) != 0) {
547                 goto error_exit;
548         }
549
550         aha->init_level++;
551
552         /* And permanently map them */
553         bus_dmamap_load(aha->mailbox_dmat, aha->mailbox_dmamap,
554                         aha->out_boxes,
555                         aha->num_boxes * (sizeof(aha_mbox_in_t)
556                                        + sizeof(aha_mbox_out_t)),
557                         ahamapmboxes, aha, /*flags*/0);
558
559         aha->init_level++;
560
561         aha->in_boxes = (aha_mbox_in_t *)&aha->out_boxes[aha->num_boxes];
562
563         ahainitmboxes(aha);
564
565         /* DMA tag for our ccb structures */
566         if (bus_dma_tag_create(aha->parent_dmat, /*alignment*/1, /*boundary*/0,
567                                /*lowaddr*/BUS_SPACE_MAXADDR,
568                                /*highaddr*/BUS_SPACE_MAXADDR,
569                                /*filter*/NULL, /*filterarg*/NULL,
570                                aha->max_ccbs * sizeof(struct aha_ccb),
571                                /*nsegments*/1,
572                                /*maxsegsz*/BUS_SPACE_MAXSIZE_24BIT,
573                                /*flags*/0, &aha->ccb_dmat) != 0) {
574                 goto error_exit;
575         }
576
577         aha->init_level++;
578
579         /* Allocation for our ccbs */
580         if (bus_dmamem_alloc(aha->ccb_dmat, (void **)&aha->aha_ccb_array,
581                              BUS_DMA_NOWAIT, &aha->ccb_dmamap) != 0) {
582                 goto error_exit;
583         }
584
585         aha->init_level++;
586
587         /* And permanently map them */
588         bus_dmamap_load(aha->ccb_dmat, aha->ccb_dmamap,
589                         aha->aha_ccb_array,
590                         aha->max_ccbs * sizeof(struct aha_ccb),
591                         ahamapccbs, aha, /*flags*/0);
592
593         aha->init_level++;
594
595         /* DMA tag for our S/G structures.  We allocate in page sized chunks */
596         if (bus_dma_tag_create(aha->parent_dmat, /*alignment*/1, /*boundary*/0,
597                                /*lowaddr*/BUS_SPACE_MAXADDR,
598                                /*highaddr*/BUS_SPACE_MAXADDR,
599                                /*filter*/NULL, /*filterarg*/NULL,
600                                PAGE_SIZE, /*nsegments*/1,
601                                /*maxsegsz*/BUS_SPACE_MAXSIZE_24BIT,
602                                /*flags*/0, &aha->sg_dmat) != 0) {
603                 goto error_exit;
604         }
605
606         aha->init_level++;
607
608         /* Perform initial CCB allocation */
609         bzero(aha->aha_ccb_array, aha->max_ccbs * sizeof(struct aha_ccb));
610         ahaallocccbs(aha);
611
612         if (aha->num_ccbs == 0) {
613                 printf("%s: aha_init - Unable to allocate initial ccbs\n",
614                        aha_name(aha));
615                 goto error_exit;
616         }
617
618         /*
619          * Note that we are going and return (to probe)
620          */
621         return 0;
622
623 error_exit:
624
625         return (ENXIO);
626 }
627
628 int
629 aha_attach(struct aha_softc *aha)
630 {
631         int tagged_dev_openings;
632         struct cam_devq *devq;
633
634         /*
635          * We don't do tagged queueing, since the aha cards don't
636          * support it.
637          */
638         tagged_dev_openings = 0;
639
640         /*
641          * Create the device queue for our SIM.
642          */
643         devq = cam_simq_alloc(aha->max_ccbs - 1);
644         if (devq == NULL)
645                 return (ENOMEM);
646
647         /*
648          * Construct our SIM entry
649          */
650         aha->sim = cam_sim_alloc(ahaaction, ahapoll, "aha", aha, aha->unit,
651                                 2, tagged_dev_openings, devq);
652         if (aha->sim == NULL) {
653                 cam_simq_free(devq);
654                 return (ENOMEM);
655         }
656         
657         if (xpt_bus_register(aha->sim, 0) != CAM_SUCCESS) {
658                 cam_sim_free(aha->sim, /*free_devq*/TRUE);
659                 return (ENXIO);
660         }
661         
662         if (xpt_create_path(&aha->path, /*periph*/NULL,
663                             cam_sim_path(aha->sim), CAM_TARGET_WILDCARD,
664                             CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
665                 xpt_bus_deregister(cam_sim_path(aha->sim));
666                 cam_sim_free(aha->sim, /*free_devq*/TRUE);
667                 return (ENXIO);
668         }
669                 
670         return (0);
671 }
672
673 char *
674 aha_name(struct aha_softc *aha)
675 {
676         static char name[10];
677
678         snprintf(name, sizeof(name), "aha%d", aha->unit);
679         return (name);
680 }
681
682 void
683 aha_find_probe_range(int ioport, int *port_index, int *max_port_index)
684 {
685         if (ioport > 0) {
686                 int i;
687
688                 for (i = 0;i < AHA_NUM_ISAPORTS; i++)
689                         if (ioport <= aha_isa_ports[i].addr)
690                                 break;
691                 if ((i >= AHA_NUM_ISAPORTS)
692                  || (ioport != aha_isa_ports[i].addr)) {
693                         printf("\n"
694 "aha_isa_probe: Invalid baseport of 0x%x specified.\n"
695 "aha_isa_probe: Nearest valid baseport is 0x%x.\n"
696 "aha_isa_probe: Failing probe.\n",
697                                ioport,
698                                (i < AHA_NUM_ISAPORTS)
699                                     ? aha_isa_ports[i].addr
700                                     : aha_isa_ports[AHA_NUM_ISAPORTS - 1].addr);
701                         *port_index = *max_port_index = -1;
702                         return;
703                 }
704                 *port_index = *max_port_index = aha_isa_ports[i].bio;
705         } else {
706                 *port_index = 0;
707                 *max_port_index = AHA_NUM_ISAPORTS - 1;
708         }
709 }
710
711 int
712 aha_iop_from_bio(isa_compat_io_t bio_index)
713 {
714         if (bio_index >= 0 && bio_index < AHA_NUM_ISAPORTS)
715                 return (aha_board_ports[bio_index]);
716         return (-1);
717 }
718
719 static void
720 ahaallocccbs(struct aha_softc *aha)
721 {
722         struct aha_ccb *next_ccb;
723         struct sg_map_node *sg_map;
724         bus_addr_t physaddr;
725         aha_sg_t *segs;
726         int newcount;
727         int i;
728
729         next_ccb = &aha->aha_ccb_array[aha->num_ccbs];
730
731         sg_map = malloc(sizeof(*sg_map), M_DEVBUF, M_NOWAIT);
732
733         if (sg_map == NULL)
734                 return;
735
736         /* Allocate S/G space for the next batch of CCBS */
737         if (bus_dmamem_alloc(aha->sg_dmat, (void **)&sg_map->sg_vaddr,
738                              BUS_DMA_NOWAIT, &sg_map->sg_dmamap) != 0) {
739                 free(sg_map, M_DEVBUF);
740                 return;
741         }
742
743         SLIST_INSERT_HEAD(&aha->sg_maps, sg_map, links);
744
745         bus_dmamap_load(aha->sg_dmat, sg_map->sg_dmamap, sg_map->sg_vaddr,
746                         PAGE_SIZE, ahamapsgs, aha, /*flags*/0);
747         
748         segs = sg_map->sg_vaddr;
749         physaddr = sg_map->sg_physaddr;
750
751         newcount = (PAGE_SIZE / (AHA_NSEG * sizeof(aha_sg_t)));
752         for (i = 0; aha->num_ccbs < aha->max_ccbs && i < newcount; i++) {
753                 int error;
754
755                 next_ccb->sg_list = segs;
756                 next_ccb->sg_list_phys = physaddr;
757                 next_ccb->flags = ACCB_FREE;
758                 error = bus_dmamap_create(aha->buffer_dmat, /*flags*/0,
759                                           &next_ccb->dmamap);
760                 if (error != 0)
761                         break;
762                 SLIST_INSERT_HEAD(&aha->free_aha_ccbs, next_ccb, links);
763                 segs += AHA_NSEG;
764                 physaddr += (AHA_NSEG * sizeof(aha_sg_t));
765                 next_ccb++;
766                 aha->num_ccbs++;
767         }
768
769         /* Reserve a CCB for error recovery */
770         if (aha->recovery_accb == NULL) {
771                 aha->recovery_accb = SLIST_FIRST(&aha->free_aha_ccbs);
772                 SLIST_REMOVE_HEAD(&aha->free_aha_ccbs, links);
773         }
774 }
775
776 static __inline void
777 ahafreeccb(struct aha_softc *aha, struct aha_ccb *accb)
778 {
779         int s;
780
781         s = splcam();
782         if ((accb->flags & ACCB_ACTIVE) != 0)
783                 LIST_REMOVE(&accb->ccb->ccb_h, sim_links.le);
784         if (aha->resource_shortage != 0
785          && (accb->ccb->ccb_h.status & CAM_RELEASE_SIMQ) == 0) {
786                 accb->ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
787                 aha->resource_shortage = FALSE;
788         }
789         accb->flags = ACCB_FREE;
790         SLIST_INSERT_HEAD(&aha->free_aha_ccbs, accb, links);
791         aha->active_ccbs--;
792         splx(s);
793 }
794
795 static struct aha_ccb*
796 ahagetccb(struct aha_softc *aha)
797 {
798         struct  aha_ccb* accb;
799         int     s;
800
801         s = splcam();
802         if ((accb = SLIST_FIRST(&aha->free_aha_ccbs)) != NULL) {
803                 SLIST_REMOVE_HEAD(&aha->free_aha_ccbs, links);
804                 aha->active_ccbs++;
805         } else if (aha->num_ccbs < aha->max_ccbs) {
806                 ahaallocccbs(aha);
807                 accb = SLIST_FIRST(&aha->free_aha_ccbs);
808                 if (accb == NULL)
809                         printf("%s: Can't malloc ACCB\n", aha_name(aha));
810                 else {
811                         SLIST_REMOVE_HEAD(&aha->free_aha_ccbs, links);
812                         aha->active_ccbs++;
813                 }
814         }
815         splx(s);
816
817         return (accb);
818 }
819
820 static void
821 ahaaction(struct cam_sim *sim, union ccb *ccb)
822 {
823         struct  aha_softc *aha;
824
825         CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("ahaaction\n"));
826         
827         aha = (struct aha_softc *)cam_sim_softc(sim);
828         
829         switch (ccb->ccb_h.func_code) {
830         /* Common cases first */
831         case XPT_SCSI_IO:       /* Execute the requested I/O operation */
832         case XPT_RESET_DEV:     /* Bus Device Reset the specified SCSI device */
833         {
834                 struct  aha_ccb *accb;
835                 struct  aha_hccb *hccb;
836
837                 /*
838                  * get a accb to use.
839                  */
840                 if ((accb = ahagetccb(aha)) == NULL) {
841                         int s;
842
843                         s = splcam();
844                         aha->resource_shortage = TRUE;
845                         splx(s);
846                         xpt_freeze_simq(aha->sim, /*count*/1);
847                         ccb->ccb_h.status = CAM_REQUEUE_REQ;
848                         xpt_done(ccb);
849                         return;
850                 }
851                 
852                 hccb = &accb->hccb;
853
854                 /*
855                  * So we can find the ACCB when an abort is requested
856                  */
857                 accb->ccb = ccb;
858                 ccb->ccb_h.ccb_accb_ptr = accb;
859                 ccb->ccb_h.ccb_aha_ptr = aha;
860
861                 /*
862                  * Put all the arguments for the xfer in the accb
863                  */
864                 hccb->target = ccb->ccb_h.target_id;
865                 hccb->lun = ccb->ccb_h.target_lun;
866                 hccb->ahastat = 0;
867                 hccb->sdstat = 0;
868
869                 if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
870                         struct ccb_scsiio *csio;
871                         struct ccb_hdr *ccbh;
872
873                         csio = &ccb->csio;
874                         ccbh = &csio->ccb_h;
875                         hccb->opcode = aha->ccb_ccb_opcode;
876                         hccb->datain = (ccb->ccb_h.flags & CAM_DIR_IN) != 0;
877                         hccb->dataout = (ccb->ccb_h.flags & CAM_DIR_OUT) != 0;
878                         hccb->cmd_len = csio->cdb_len;
879                         if (hccb->cmd_len > sizeof(hccb->scsi_cdb)) {
880                                 ccb->ccb_h.status = CAM_REQ_INVALID;
881                                 ahafreeccb(aha, accb);
882                                 xpt_done(ccb);
883                                 return;
884                         }
885                         hccb->sense_len = csio->sense_len;
886                         if ((ccbh->flags & CAM_CDB_POINTER) != 0) {
887                                 if ((ccbh->flags & CAM_CDB_PHYS) == 0) {
888                                         bcopy(csio->cdb_io.cdb_ptr,
889                                               hccb->scsi_cdb, hccb->cmd_len);
890                                 } else {
891                                         /* I guess I could map it in... */
892                                         ccbh->status = CAM_REQ_INVALID;
893                                         ahafreeccb(aha, accb);
894                                         xpt_done(ccb);
895                                         return;
896                                 }
897                         } else {
898                                 bcopy(csio->cdb_io.cdb_bytes,
899                                       hccb->scsi_cdb, hccb->cmd_len);
900                         }
901                         /*
902                          * If we have any data to send with this command,
903                          * map it into bus space.
904                          */
905                         /* Only use S/G if there is a transfer */
906                         if ((ccbh->flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
907                                 if ((ccbh->flags & CAM_SCATTER_VALID) == 0) {
908                                         /*
909                                          * We've been given a pointer
910                                          * to a single buffer.
911                                          */
912                                         if ((ccbh->flags & CAM_DATA_PHYS)==0) {
913                                                 int s;
914                                                 int error;
915
916                                                 s = splsoftvm();
917                                                 error = bus_dmamap_load(
918                                                     aha->buffer_dmat,
919                                                     accb->dmamap,
920                                                     csio->data_ptr,
921                                                     csio->dxfer_len,
922                                                     ahaexecuteccb,
923                                                     accb,
924                                                     /*flags*/0);
925                                                 if (error == EINPROGRESS) {
926                                                         /*
927                                                          * So as to maintain
928                                                          * ordering, freeze the
929                                                          * controller queue
930                                                          * until our mapping is
931                                                          * returned.
932                                                          */
933                                                         xpt_freeze_simq(aha->sim,
934                                                                         1);
935                                                         csio->ccb_h.status |=
936                                                             CAM_RELEASE_SIMQ;
937                                                 }
938                                                 splx(s);
939                                         } else {
940                                                 struct bus_dma_segment seg; 
941
942                                                 /* Pointer to physical buffer */
943                                                 seg.ds_addr =
944                                                     (bus_addr_t)csio->data_ptr;
945                                                 seg.ds_len = csio->dxfer_len;
946                                                 ahaexecuteccb(accb, &seg, 1, 0);
947                                         }
948                                 } else {
949                                         struct bus_dma_segment *segs;
950
951                                         if ((ccbh->flags & CAM_DATA_PHYS) != 0)
952                                                 panic("ahaaction - Physical "
953                                                       "segment pointers "
954                                                       "unsupported");
955
956                                         if ((ccbh->flags&CAM_SG_LIST_PHYS)==0)
957                                                 panic("ahaaction - Virtual "
958                                                       "segment addresses "
959                                                       "unsupported");
960
961                                         /* Just use the segments provided */
962                                         segs = (struct bus_dma_segment *)
963                                             csio->data_ptr;
964                                         ahaexecuteccb(accb, segs,
965                                                      csio->sglist_cnt, 0);
966                                 }
967                         } else {
968                                 ahaexecuteccb(accb, NULL, 0, 0);
969                         }
970                 } else {
971                         hccb->opcode = INITIATOR_BUS_DEV_RESET;
972                         /* No data transfer */
973                         hccb->datain = TRUE;
974                         hccb->dataout = TRUE;
975                         hccb->cmd_len = 0;
976                         hccb->sense_len = 0;
977                         ahaexecuteccb(accb, NULL, 0, 0);
978                 }
979                 break;
980         }
981         case XPT_EN_LUN:                /* Enable LUN as a target */
982         case XPT_TARGET_IO:             /* Execute target I/O request */
983         case XPT_ACCEPT_TARGET_IO:      /* Accept Host Target Mode CDB */
984         case XPT_CONT_TARGET_IO:        /* Continue Host Target I/O Connection*/
985         case XPT_ABORT:                 /* Abort the specified CCB */
986                 /* XXX Implement */
987                 ccb->ccb_h.status = CAM_REQ_INVALID;
988                 xpt_done(ccb);
989                 break;
990         case XPT_SET_TRAN_SETTINGS:
991         {
992                 /* XXX Implement */
993                 ccb->ccb_h.status = CAM_PROVIDE_FAIL;
994                 xpt_done(ccb);
995                 break;
996         }
997         case XPT_GET_TRAN_SETTINGS:
998         /* Get default/user set transfer settings for the target */
999         {
1000                 struct  ccb_trans_settings *cts;
1001                 u_int   target_mask;
1002
1003                 cts = &ccb->cts;
1004                 target_mask = 0x01 << ccb->ccb_h.target_id;
1005                 if ((cts->flags & CCB_TRANS_USER_SETTINGS) != 0) {
1006                         cts->flags = 0;
1007                         if ((aha->disc_permitted & target_mask) != 0)
1008                                 cts->flags |= CCB_TRANS_DISC_ENB;
1009                         cts->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
1010                         if ((aha->sync_permitted & target_mask) != 0) {
1011                                 if (aha->boardid >= BOARD_1542CF)
1012                                         cts->sync_period = 25;
1013                                 else
1014                                         cts->sync_period = 50;
1015                         } else
1016                                 cts->sync_period = 0;
1017
1018                         if (cts->sync_period != 0)
1019                                 cts->sync_offset = 15;
1020
1021                         cts->valid = CCB_TRANS_SYNC_RATE_VALID
1022                                    | CCB_TRANS_SYNC_OFFSET_VALID
1023                                    | CCB_TRANS_BUS_WIDTH_VALID
1024                                    | CCB_TRANS_DISC_VALID
1025                                    | CCB_TRANS_TQ_VALID;
1026                 } else {
1027                         ahafetchtransinfo(aha, cts);
1028                 }
1029
1030                 ccb->ccb_h.status = CAM_REQ_CMP;
1031                 xpt_done(ccb);
1032                 break;
1033         }
1034         case XPT_CALC_GEOMETRY:
1035         {
1036                 struct    ccb_calc_geometry *ccg;
1037                 u_int32_t size_mb;
1038                 u_int32_t secs_per_cylinder;
1039
1040                 ccg = &ccb->ccg;
1041                 size_mb = ccg->volume_size
1042                         / ((1024L * 1024L) / ccg->block_size);
1043                 
1044                 if (size_mb >= 1024 && (aha->extended_trans != 0)) {
1045                         if (size_mb >= 2048) {
1046                                 ccg->heads = 255;
1047                                 ccg->secs_per_track = 63;
1048                         } else {
1049                                 ccg->heads = 128;
1050                                 ccg->secs_per_track = 32;
1051                         }
1052                 } else {
1053                         ccg->heads = 64;
1054                         ccg->secs_per_track = 32;
1055                 }
1056                 secs_per_cylinder = ccg->heads * ccg->secs_per_track;
1057                 ccg->cylinders = ccg->volume_size / secs_per_cylinder;
1058                 ccb->ccb_h.status = CAM_REQ_CMP;
1059                 xpt_done(ccb);
1060                 break;
1061         }
1062         case XPT_RESET_BUS:             /* Reset the specified SCSI bus */
1063         {
1064                 ahareset(aha, /*hardreset*/TRUE);
1065                 ccb->ccb_h.status = CAM_REQ_CMP;
1066                 xpt_done(ccb);
1067                 break;
1068         }
1069         case XPT_TERM_IO:               /* Terminate the I/O process */
1070                 /* XXX Implement */
1071                 ccb->ccb_h.status = CAM_REQ_INVALID;
1072                 xpt_done(ccb);
1073                 break;
1074         case XPT_PATH_INQ:              /* Path routing inquiry */
1075         {
1076                 struct ccb_pathinq *cpi = &ccb->cpi;
1077                 
1078                 cpi->version_num = 1; /* XXX??? */
1079                 cpi->hba_inquiry = PI_SDTR_ABLE;
1080                 cpi->target_sprt = 0;
1081                 cpi->hba_misc = 0;
1082                 cpi->hba_eng_cnt = 0;
1083                 cpi->max_target = 7;
1084                 cpi->max_lun = 7;
1085                 cpi->initiator_id = aha->scsi_id;
1086                 cpi->bus_id = cam_sim_bus(sim);
1087                 cpi->base_transfer_speed = 3300;
1088                 strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
1089                 strncpy(cpi->hba_vid, "Adaptec", HBA_IDLEN);
1090                 strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
1091                 cpi->unit_number = cam_sim_unit(sim);
1092                 cpi->ccb_h.status = CAM_REQ_CMP;
1093                 xpt_done(ccb);
1094                 break;
1095         }
1096         default:
1097                 ccb->ccb_h.status = CAM_REQ_INVALID;
1098                 xpt_done(ccb);
1099                 break;
1100         }
1101 }
1102
1103 static void
1104 ahaexecuteccb(void *arg, bus_dma_segment_t *dm_segs, int nseg, int error)
1105 {
1106         struct   aha_ccb *accb;
1107         union    ccb *ccb;
1108         struct   aha_softc *aha;
1109         int      s;
1110         u_int32_t paddr;
1111
1112         accb = (struct aha_ccb *)arg;
1113         ccb = accb->ccb;
1114         aha = (struct aha_softc *)ccb->ccb_h.ccb_aha_ptr;
1115
1116         if (error != 0) {
1117                 if (error != EFBIG)
1118                         printf("%s: Unexepected error 0x%x returned from "
1119                                "bus_dmamap_load\n", aha_name(aha), error);
1120                 if (ccb->ccb_h.status == CAM_REQ_INPROG) {
1121                         xpt_freeze_devq(ccb->ccb_h.path, /*count*/1);
1122                         ccb->ccb_h.status = CAM_REQ_TOO_BIG|CAM_DEV_QFRZN;
1123                 }
1124                 ahafreeccb(aha, accb);
1125                 xpt_done(ccb);
1126                 return;
1127         }
1128                 
1129         if (nseg != 0) {
1130                 aha_sg_t *sg;
1131                 bus_dma_segment_t *end_seg;
1132                 bus_dmasync_op_t op;
1133
1134                 end_seg = dm_segs + nseg;
1135
1136                 /* Copy the segments into our SG list */
1137                 sg = accb->sg_list;
1138                 while (dm_segs < end_seg) {
1139                         ahautoa24(dm_segs->ds_len, sg->len);
1140                         ahautoa24(dm_segs->ds_addr, sg->addr);
1141                         sg++;
1142                         dm_segs++;
1143                 }
1144
1145                 if (nseg > 1) {
1146                         accb->hccb.opcode = aha->ccb_sg_opcode;
1147                         ahautoa24((sizeof(aha_sg_t) * nseg),
1148                                   accb->hccb.data_len);
1149                         ahautoa24(accb->sg_list_phys, accb->hccb.data_addr);
1150                 } else {
1151                         bcopy(accb->sg_list->len, accb->hccb.data_len, 3);
1152                         bcopy(accb->sg_list->addr, accb->hccb.data_addr, 3);
1153                 }
1154
1155                 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN)
1156                         op = BUS_DMASYNC_PREREAD;
1157                 else
1158                         op = BUS_DMASYNC_PREWRITE;
1159
1160                 bus_dmamap_sync(aha->buffer_dmat, accb->dmamap, op);
1161
1162         } else {
1163                 accb->hccb.opcode = INITIATOR_CCB;
1164                 ahautoa24(0, accb->hccb.data_len);
1165                 ahautoa24(0, accb->hccb.data_addr);
1166         }
1167
1168         s = splcam();
1169
1170         /*
1171          * Last time we need to check if this CCB needs to
1172          * be aborted.
1173          */
1174         if (ccb->ccb_h.status != CAM_REQ_INPROG) {
1175                 if (nseg != 0)
1176                         bus_dmamap_unload(aha->buffer_dmat, accb->dmamap);
1177                 ahafreeccb(aha, accb);
1178                 xpt_done(ccb);
1179                 splx(s);
1180                 return;
1181         }
1182                 
1183         accb->flags = ACCB_ACTIVE;
1184         ccb->ccb_h.status |= CAM_SIM_QUEUED;
1185         LIST_INSERT_HEAD(&aha->pending_ccbs, &ccb->ccb_h, sim_links.le);
1186
1187         ccb->ccb_h.timeout_ch =
1188             timeout(ahatimeout, (caddr_t)accb,
1189                     (ccb->ccb_h.timeout * hz) / 1000);
1190
1191         /* Tell the adapter about this command */
1192         if (aha->cur_outbox->action_code != AMBO_FREE) {
1193                 /*
1194                  * We should never encounter a busy mailbox.
1195                  * If we do, warn the user, and treat it as
1196                  * a resource shortage.  If the controller is
1197                  * hung, one of the pending transactions will
1198                  * timeout causing us to start recovery operations.
1199                  */
1200                 printf("%s: Encountered busy mailbox with %d out of %d "
1201                        "commands active!!!", aha_name(aha), aha->active_ccbs,
1202                        aha->max_ccbs);
1203                 untimeout(ahatimeout, accb, ccb->ccb_h.timeout_ch);
1204                 if (nseg != 0)
1205                         bus_dmamap_unload(aha->buffer_dmat, accb->dmamap);
1206                 ahafreeccb(aha, accb);
1207                 aha->resource_shortage = TRUE;
1208                 xpt_freeze_simq(aha->sim, /*count*/1);
1209                 ccb->ccb_h.status = CAM_REQUEUE_REQ;
1210                 xpt_done(ccb);
1211                 return;
1212         }
1213         paddr = ahaccbvtop(aha, accb);
1214         ahautoa24(paddr, aha->cur_outbox->ccb_addr);
1215         aha->cur_outbox->action_code = AMBO_START;      
1216         aha_outb(aha, COMMAND_REG, AOP_START_MBOX);
1217
1218         ahanextoutbox(aha);
1219         splx(s);
1220 }
1221
1222 void
1223 aha_intr(void *arg)
1224 {
1225         struct  aha_softc *aha;
1226         u_int   intstat;
1227
1228         aha = (struct aha_softc *)arg;
1229         while (((intstat = aha_inb(aha, INTSTAT_REG)) & INTR_PENDING) != 0) {
1230                 if ((intstat & CMD_COMPLETE) != 0) {
1231                         aha->latched_status = aha_inb(aha, STATUS_REG);
1232                         aha->command_cmp = TRUE;
1233                 }
1234
1235                 aha_outb(aha, CONTROL_REG, RESET_INTR);
1236
1237                 if ((intstat & IMB_LOADED) != 0) {
1238                         while (aha->cur_inbox->comp_code != AMBI_FREE) {
1239                                 u_int32_t       paddr;
1240                                 paddr = aha_a24tou(aha->cur_inbox->ccb_addr);
1241                                 ahadone(aha,
1242                                        ahaccbptov(aha, paddr),
1243                                        aha->cur_inbox->comp_code);
1244                                 aha->cur_inbox->comp_code = AMBI_FREE;
1245                                 ahanextinbox(aha);
1246                         }
1247                 }
1248
1249                 if ((intstat & SCSI_BUS_RESET) != 0) {
1250                         ahareset(aha, /*hardreset*/FALSE);
1251                 }
1252         }
1253 }
1254
1255 static void
1256 ahadone(struct aha_softc *aha, struct aha_ccb *accb, aha_mbi_comp_code_t comp_code)
1257 {
1258         union  ccb        *ccb;
1259         struct ccb_scsiio *csio;
1260
1261         ccb = accb->ccb;
1262         csio = &accb->ccb->csio;
1263
1264         if ((accb->flags & ACCB_ACTIVE) == 0) {
1265                 printf("%s: ahadone - Attempt to free non-active ACCB %p\n",
1266                        aha_name(aha), (void *)accb);
1267                 return;
1268         }
1269
1270         if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1271                 bus_dmasync_op_t op;
1272
1273                 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN)
1274                         op = BUS_DMASYNC_POSTREAD;
1275                 else
1276                         op = BUS_DMASYNC_POSTWRITE;
1277                 bus_dmamap_sync(aha->buffer_dmat, accb->dmamap, op);
1278                 bus_dmamap_unload(aha->buffer_dmat, accb->dmamap);
1279         }
1280
1281         if (accb == aha->recovery_accb) {
1282                 /*
1283                  * The recovery ACCB does not have a CCB associated
1284                  * with it, so short circuit the normal error handling.
1285                  * We now traverse our list of pending CCBs and process
1286                  * any that were terminated by the recovery CCBs action.
1287                  * We also reinstate timeouts for all remaining, pending,
1288                  * CCBs.
1289                  */
1290                 struct cam_path *path;
1291                 struct ccb_hdr *ccb_h;
1292                 cam_status error;
1293
1294                 /* Notify all clients that a BDR occured */
1295                 error = xpt_create_path(&path, /*periph*/NULL,
1296                                         cam_sim_path(aha->sim),
1297                                         accb->hccb.target,
1298                                         CAM_LUN_WILDCARD);
1299                 
1300                 if (error == CAM_REQ_CMP)
1301                         xpt_async(AC_SENT_BDR, path, NULL);
1302
1303                 ccb_h = LIST_FIRST(&aha->pending_ccbs);
1304                 while (ccb_h != NULL) {
1305                         struct aha_ccb *pending_accb;
1306
1307                         pending_accb = (struct aha_ccb *)ccb_h->ccb_accb_ptr;
1308                         if (pending_accb->hccb.target == accb->hccb.target) {
1309                                 pending_accb->hccb.ahastat = AHASTAT_HA_BDR;
1310                                 ccb_h = LIST_NEXT(ccb_h, sim_links.le);
1311                                 ahadone(aha, pending_accb, AMBI_ERROR);
1312                         } else {
1313                                 ccb_h->timeout_ch =
1314                                     timeout(ahatimeout, (caddr_t)pending_accb,
1315                                             (ccb_h->timeout * hz) / 1000);
1316                                 ccb_h = LIST_NEXT(ccb_h, sim_links.le);
1317                         }
1318                 }
1319                 printf("%s: No longer in timeout\n", aha_name(aha));
1320                 return;
1321         }
1322
1323         untimeout(ahatimeout, accb, ccb->ccb_h.timeout_ch);
1324
1325         switch (comp_code) {
1326         case AMBI_FREE:
1327                 printf("%s: ahadone - CCB completed with free status!\n",
1328                        aha_name(aha));
1329                 break;
1330         case AMBI_NOT_FOUND:
1331                 printf("%s: ahadone - CCB Abort failed to find CCB\n",
1332                        aha_name(aha));
1333                 break;
1334         case AMBI_ABORT:
1335         case AMBI_ERROR:
1336                 /* An error occured */
1337                 if (accb->hccb.opcode < INITIATOR_CCB_WRESID)
1338                         csio->resid = 0;
1339                 else
1340                         csio->resid = aha_a24tou(accb->hccb.data_len);
1341                 switch(accb->hccb.ahastat) {
1342                 case AHASTAT_DATARUN_ERROR:
1343                 {
1344                         if (csio->resid <= 0) {
1345                                 csio->ccb_h.status = CAM_DATA_RUN_ERR;
1346                                 break;
1347                         }
1348                         /* FALLTHROUGH */
1349                 }
1350                 case AHASTAT_NOERROR:
1351                         csio->scsi_status = accb->hccb.sdstat;
1352                         csio->ccb_h.status |= CAM_SCSI_STATUS_ERROR;
1353                         switch(csio->scsi_status) {
1354                         case SCSI_STATUS_CHECK_COND:
1355                         case SCSI_STATUS_CMD_TERMINATED:
1356                                 csio->ccb_h.status |= CAM_AUTOSNS_VALID;
1357                                 /*
1358                                  * The aha writes the sense data at different
1359                                  * offsets based on the scsi cmd len
1360                                  */
1361                                 bcopy((caddr_t) &accb->hccb.scsi_cdb +
1362                                         accb->hccb.cmd_len, 
1363                                         (caddr_t) &csio->sense_data,
1364                                         accb->hccb.sense_len);
1365                                 break;
1366                         default:
1367                                 break;
1368                         case SCSI_STATUS_OK:
1369                                 csio->ccb_h.status = CAM_REQ_CMP;
1370                                 break;
1371                         }
1372                         break;
1373                 case AHASTAT_SELTIMEOUT:
1374                         csio->ccb_h.status = CAM_SEL_TIMEOUT;
1375                         break;
1376                 case AHASTAT_UNEXPECTED_BUSFREE:
1377                         csio->ccb_h.status = CAM_UNEXP_BUSFREE;
1378                         break;
1379                 case AHASTAT_INVALID_PHASE:
1380                         csio->ccb_h.status = CAM_SEQUENCE_FAIL;
1381                         break;
1382                 case AHASTAT_INVALID_ACTION_CODE:
1383                         panic("%s: Inavlid Action code", aha_name(aha));
1384                         break;
1385                 case AHASTAT_INVALID_OPCODE:
1386                         if (accb->hccb.opcode < INITIATOR_CCB_WRESID)
1387                                 panic("%s: Invalid CCB Opcode %x hccb = %p",
1388                                         aha_name(aha), accb->hccb.opcode,
1389                                         &accb->hccb);
1390                         printf("%s: AHA-1540A detected, compensating\n",
1391                                 aha_name(aha));
1392                         aha->ccb_sg_opcode = INITIATOR_SG_CCB;
1393                         aha->ccb_ccb_opcode = INITIATOR_CCB;
1394                         xpt_freeze_devq(ccb->ccb_h.path, /*count*/1);
1395                         csio->ccb_h.status = CAM_REQUEUE_REQ;
1396                         break;
1397                 case AHASTAT_LINKED_CCB_LUN_MISMATCH:
1398                         /* We don't even support linked commands... */
1399                         panic("%s: Linked CCB Lun Mismatch", aha_name(aha));
1400                         break;
1401                 case AHASTAT_INVALID_CCB_OR_SG_PARAM:
1402                         panic("%s: Invalid CCB or SG list", aha_name(aha));
1403                         break;
1404                 case AHASTAT_HA_SCSI_BUS_RESET:
1405                         if ((csio->ccb_h.status & CAM_STATUS_MASK)
1406                             != CAM_CMD_TIMEOUT)
1407                                 csio->ccb_h.status = CAM_SCSI_BUS_RESET;
1408                         break;
1409                 case AHASTAT_HA_BDR:
1410                         if ((accb->flags & ACCB_DEVICE_RESET) == 0)
1411                                 csio->ccb_h.status = CAM_BDR_SENT;
1412                         else
1413                                 csio->ccb_h.status = CAM_CMD_TIMEOUT;
1414                         break;
1415                 }
1416                 if (csio->ccb_h.status != CAM_REQ_CMP) {
1417                         xpt_freeze_devq(csio->ccb_h.path, /*count*/1);
1418                         csio->ccb_h.status |= CAM_DEV_QFRZN;
1419                 }
1420                 if ((accb->flags & ACCB_RELEASE_SIMQ) != 0)
1421                         ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1422                 ahafreeccb(aha, accb);
1423                 xpt_done(ccb);
1424                 break;
1425         case AMBI_OK:
1426                 /* All completed without incident */
1427                 /* XXX DO WE NEED TO COPY SENSE BYTES HERE???? XXX */
1428                 /* I don't think so since it works???? */
1429                 ccb->ccb_h.status |= CAM_REQ_CMP;
1430                 if ((accb->flags & ACCB_RELEASE_SIMQ) != 0)
1431                         ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1432                 ahafreeccb(aha, accb);
1433                 xpt_done(ccb);
1434                 break;
1435         }
1436 }
1437
1438 static int
1439 ahareset(struct aha_softc* aha, int hard_reset)
1440 {
1441         struct   ccb_hdr *ccb_h;
1442         u_int    status;
1443         u_int    timeout;
1444         u_int8_t reset_type;
1445
1446         if (hard_reset != 0)
1447                 reset_type = HARD_RESET;
1448         else
1449                 reset_type = SOFT_RESET;
1450         aha_outb(aha, CONTROL_REG, reset_type);
1451
1452         /* Wait 5sec. for Diagnostic start */
1453         timeout = 5 * 10000;
1454         while (--timeout) {
1455                 status = aha_inb(aha, STATUS_REG);
1456                 if ((status & DIAG_ACTIVE) != 0)
1457                         break;
1458                 DELAY(100);
1459         }
1460         if (timeout == 0) {
1461                 PRVERB(("%s: ahareset - Diagnostic Active failed to "
1462                         "assert. status = 0x%x\n", aha_name(aha),
1463                         status));
1464                 return (ETIMEDOUT);
1465         }
1466
1467         /* Wait 10sec. for Diagnostic end */
1468         timeout = 10 * 10000;
1469         while (--timeout) {
1470                 status = aha_inb(aha, STATUS_REG);
1471                 if ((status & DIAG_ACTIVE) == 0)
1472                         break;
1473                 DELAY(100);
1474         }
1475         if (timeout == 0) {
1476                 panic("%s: ahareset - Diagnostic Active failed to drop. "
1477                        "status = 0x%x\n", aha_name(aha), status);
1478                 return (ETIMEDOUT);
1479         }
1480
1481         /* Wait for the host adapter to become ready or report a failure */
1482         timeout = 10000;
1483         while (--timeout) {
1484                 status = aha_inb(aha, STATUS_REG);
1485                 if ((status & (DIAG_FAIL|HA_READY|DATAIN_REG_READY)) != 0)
1486                         break;
1487                 DELAY(100);
1488         }
1489         if (timeout == 0) {
1490                 printf("%s: ahareset - Host adapter failed to come ready. "
1491                        "status = 0x%x\n", aha_name(aha), status);
1492                 return (ETIMEDOUT);
1493         }
1494
1495         /* If the diagnostics failed, tell the user */
1496         if ((status & DIAG_FAIL) != 0
1497          || (status & HA_READY) == 0) {
1498                 printf("%s: ahareset - Adapter failed diagnostics\n",
1499                        aha_name(aha));
1500
1501                 if ((status & DATAIN_REG_READY) != 0)
1502                         printf("%s: ahareset - Host Adapter Error "
1503                                "code = 0x%x\n", aha_name(aha),
1504                                aha_inb(aha, DATAIN_REG));
1505                 return (ENXIO);
1506         }
1507
1508         /* If we've allocated mailboxes, initialize them */
1509         if (aha->init_level > 4)
1510                 ahainitmboxes(aha);
1511
1512         /* If we've attached to the XPT, tell it about the event */
1513         if (aha->path != NULL)
1514                 xpt_async(AC_BUS_RESET, aha->path, NULL);
1515
1516         /*
1517          * Perform completion processing for all outstanding CCBs.
1518          */
1519         while ((ccb_h = LIST_FIRST(&aha->pending_ccbs)) != NULL) {
1520                 struct aha_ccb *pending_accb;
1521
1522                 pending_accb = (struct aha_ccb *)ccb_h->ccb_accb_ptr;
1523                 pending_accb->hccb.ahastat = AHASTAT_HA_SCSI_BUS_RESET;
1524                 ahadone(aha, pending_accb, AMBI_ERROR);
1525         }
1526
1527         return (0);
1528 }
1529
1530 /*
1531  * Send a command to the adapter.
1532  */
1533 int
1534 aha_cmd(struct aha_softc *aha, aha_op_t opcode, u_int8_t *params, 
1535         u_int param_len, u_int8_t *reply_data, u_int reply_len, 
1536         u_int cmd_timeout)
1537 {
1538         u_int   timeout;
1539         u_int   status;
1540         u_int   saved_status;
1541         u_int   intstat;
1542         u_int   reply_buf_size;
1543         int     s;
1544         int     cmd_complete;
1545         int     error;
1546
1547         /* No data returned to start */
1548         reply_buf_size = reply_len;
1549         reply_len = 0;
1550         intstat = 0;
1551         cmd_complete = 0;
1552         saved_status = 0;
1553         error = 0;
1554
1555         /*
1556          * All commands except for the "start mailbox" and the "enable
1557          * outgoing mailbox read interrupt" commands cannot be issued
1558          * while there are pending transactions.  Freeze our SIMQ
1559          * and wait for all completions to occur if necessary.
1560          */
1561         timeout = 100000;
1562         s = splcam();
1563         while (LIST_FIRST(&aha->pending_ccbs) != NULL && --timeout) {
1564                 /* Fire the interrupt handler in case interrupts are blocked */
1565                 aha_intr(aha);
1566                 splx(s);
1567                 DELAY(100);
1568                 s = splcam();
1569         }
1570         splx(s);
1571
1572         if (timeout == 0) {
1573                 printf("%s: aha_cmd: Timeout waiting for adapter idle\n",
1574                        aha_name(aha));
1575                 return (ETIMEDOUT);
1576         }
1577         aha->command_cmp = 0;
1578         /*
1579          * Wait up to 10 sec. for the adapter to become
1580          * ready to accept commands.
1581          */
1582         timeout = 100000;
1583         while (--timeout) {
1584
1585                 status = aha_inb(aha, STATUS_REG);
1586                 if ((status & HA_READY) != 0
1587                  && (status & CMD_REG_BUSY) == 0)
1588                         break;
1589                 /*
1590                  * Throw away any pending data which may be
1591                  * left over from earlier commands that we
1592                  * timedout on.
1593                  */
1594                 if ((status & DATAIN_REG_READY) != 0)
1595                         (void)aha_inb(aha, DATAIN_REG);
1596                 DELAY(100);
1597         }
1598         if (timeout == 0) {
1599                 printf("%s: aha_cmd: Timeout waiting for adapter ready, "
1600                        "status = 0x%x\n", aha_name(aha), status);
1601                 return (ETIMEDOUT);
1602         }
1603
1604         /*
1605          * Send the opcode followed by any necessary parameter bytes.
1606          */
1607         aha_outb(aha, COMMAND_REG, opcode);
1608
1609         /*
1610          * Wait for up to 1sec to get the parameter list sent
1611          */
1612         timeout = 10000;
1613         while (param_len && --timeout) {
1614                 DELAY(100);
1615                 s = splcam();
1616                 status = aha_inb(aha, STATUS_REG);
1617                 intstat = aha_inb(aha, INTSTAT_REG);
1618                 splx(s);
1619
1620                 if ((intstat & (INTR_PENDING|CMD_COMPLETE))
1621                  == (INTR_PENDING|CMD_COMPLETE)) {
1622                         saved_status = status;
1623                         cmd_complete = 1;
1624                         break;
1625                 }
1626
1627                 if (aha->command_cmp != 0) {
1628                         saved_status = aha->latched_status;
1629                         cmd_complete = 1;
1630                         break;
1631                 }
1632                 if ((status & DATAIN_REG_READY) != 0)
1633                         break;
1634                 if ((status & CMD_REG_BUSY) == 0) {
1635                         aha_outb(aha, COMMAND_REG, *params++);
1636                         param_len--;
1637                         timeout = 10000;
1638                 }
1639         }
1640         if (timeout == 0) {
1641                 printf("%s: aha_cmd: Timeout sending parameters, "
1642                        "status = 0x%x\n", aha_name(aha), status);
1643                 error = ETIMEDOUT;
1644         }
1645
1646         /*
1647          * For all other commands, we wait for any output data
1648          * and the final comand completion interrupt.
1649          */
1650         while (cmd_complete == 0 && --cmd_timeout) {
1651
1652                 s = splcam();
1653                 status = aha_inb(aha, STATUS_REG);
1654                 intstat = aha_inb(aha, INTSTAT_REG);
1655                 splx(s);
1656
1657                 if (aha->command_cmp != 0) {
1658                         cmd_complete = 1;
1659                         saved_status = aha->latched_status;
1660                 } else if ((intstat & (INTR_PENDING|CMD_COMPLETE))
1661                         == (INTR_PENDING|CMD_COMPLETE)) {
1662                         /*
1663                          * Our poll (in case interrupts are blocked)
1664                          * saw the CMD_COMPLETE interrupt.
1665                          */
1666                         cmd_complete = 1;
1667                         saved_status = status;
1668                 }
1669                 if ((status & DATAIN_REG_READY) != 0) {
1670                         u_int8_t data;
1671
1672                         data = aha_inb(aha, DATAIN_REG);
1673                         if (reply_len < reply_buf_size) {
1674                                 *reply_data++ = data;
1675                         } else {
1676                                 printf("%s: aha_cmd - Discarded reply data "
1677                                        "byte for opcode 0x%x\n", aha_name(aha),
1678                                        opcode);
1679                         }
1680                         /*
1681                          * Reset timeout to ensure at least a second
1682                          * between response bytes.
1683                          */
1684                         cmd_timeout = MAX(cmd_timeout, 10000);
1685                         reply_len++;
1686                 }
1687                 DELAY(100);
1688         }
1689         if (cmd_timeout == 0) {
1690                 printf("%s: aha_cmd: Timeout waiting for reply data and "
1691                        "command complete.\n%s: status = 0x%x, intstat = 0x%x, "
1692                        "reply_len = %d\n", aha_name(aha), aha_name(aha), status,
1693                        intstat, reply_len);
1694                 return (ETIMEDOUT);
1695         }
1696
1697         /*
1698          * Clear any pending interrupts.  Block interrupts so our
1699          * interrupt handler is not re-entered.
1700          */
1701         s = splcam();
1702         aha_intr(aha);
1703         splx(s);
1704         
1705         if (error != 0)
1706                 return (error);
1707
1708         /*
1709          * If the command was rejected by the controller, tell the caller.
1710          */
1711         if ((saved_status & CMD_INVALID) != 0) {
1712                 PRVERB(("%s: Invalid Command 0x%x\n", aha_name(aha), opcode));
1713                 /*
1714                  * Some early adapters may not recover properly from
1715                  * an invalid command.  If it appears that the controller
1716                  * has wedged (i.e. status was not cleared by our interrupt
1717                  * reset above), perform a soft reset.
1718                  */
1719                 DELAY(1000);
1720                 status = aha_inb(aha, STATUS_REG);
1721                 if ((status & (CMD_INVALID|STATUS_REG_RSVD|DATAIN_REG_READY|
1722                               CMD_REG_BUSY|DIAG_FAIL|DIAG_ACTIVE)) != 0
1723                  || (status & (HA_READY|INIT_REQUIRED))
1724                   != (HA_READY|INIT_REQUIRED)) {
1725                         ahareset(aha, /*hard_reset*/FALSE);
1726                 }
1727                 return (EINVAL);
1728         }
1729
1730         if (param_len > 0) {
1731                 /* The controller did not accept the full argument list */
1732                 PRVERB(("%s: Controller did not accept full argument list "
1733                         "(%d > 0)\n",
1734                         aha_name(aha), param_len));
1735                 return (E2BIG);
1736         }
1737
1738         if (reply_len != reply_buf_size) {
1739                 /* Too much or too little data received */
1740                 PRVERB(("%s: Too much or too little data received (%d != %d)\n",
1741                         aha_name(aha), reply_len, reply_buf_size));
1742                 return (EMSGSIZE);
1743         }
1744
1745         /* We were successful */
1746         return (0);
1747 }
1748
1749 static int
1750 ahainitmboxes(struct aha_softc *aha) 
1751 {
1752         int error;
1753         init_24b_mbox_params_t init_mbox;
1754
1755         bzero(aha->in_boxes, sizeof(aha_mbox_in_t) * aha->num_boxes);
1756         bzero(aha->out_boxes, sizeof(aha_mbox_out_t) * aha->num_boxes);
1757         aha->cur_inbox = aha->in_boxes;
1758         aha->last_inbox = aha->in_boxes + aha->num_boxes - 1;
1759         aha->cur_outbox = aha->out_boxes;
1760         aha->last_outbox = aha->out_boxes + aha->num_boxes - 1;
1761
1762         /* Tell the adapter about them */
1763         init_mbox.num_mboxes = aha->num_boxes;
1764         ahautoa24(aha->mailbox_physbase, init_mbox.base_addr);
1765         error = aha_cmd(aha, AOP_INITIALIZE_MBOX, (u_int8_t *)&init_mbox,
1766                        /*parmlen*/sizeof(init_mbox), /*reply_buf*/NULL,
1767                        /*reply_len*/0, DEFAULT_CMD_TIMEOUT);
1768
1769         if (error != 0)
1770                 printf("ahainitmboxes: Initialization command failed\n");
1771         return (error);
1772 }
1773
1774 /*
1775  * Update the XPT's idea of the negotiated transfer
1776  * parameters for a particular target.
1777  */
1778 static void
1779 ahafetchtransinfo(struct aha_softc *aha, struct ccb_trans_settings* cts)
1780 {
1781         setup_data_t    setup_info;
1782         u_int           target;
1783         u_int           targ_offset;
1784         u_int           sync_period;
1785         int             error;
1786         u_int8_t        param;
1787         targ_syncinfo_t sync_info;
1788
1789         target = cts->ccb_h.target_id;
1790         targ_offset = (target & 0x7);
1791
1792         /*
1793          * Inquire Setup Information.  This command retreives
1794          * the sync info for older models.
1795          */
1796         param = sizeof(setup_info);
1797         error = aha_cmd(aha, AOP_INQUIRE_SETUP_INFO, &param, /*paramlen*/1,
1798                        (u_int8_t*)&setup_info, sizeof(setup_info),
1799                        DEFAULT_CMD_TIMEOUT);
1800
1801         if (error != 0) {
1802                 printf("%s: ahafetchtransinfo - Inquire Setup Info Failed %d\n",
1803                        aha_name(aha), error);
1804                 return;
1805         }
1806
1807         sync_info = setup_info.syncinfo[targ_offset];
1808
1809         if (sync_info.sync == 0)
1810                 cts->sync_offset = 0;
1811         else
1812                 cts->sync_offset = sync_info.offset;
1813
1814         cts->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
1815
1816         if (aha->boardid >= BOARD_1542CF)
1817                 sync_period = 1000;
1818         else
1819                 sync_period = 2000;
1820         sync_period += 500 * sync_info.period;
1821
1822         /* Convert ns value to standard SCSI sync rate */
1823         if (cts->sync_offset != 0)
1824                 cts->sync_period = scsi_calc_syncparam(sync_period);
1825         else
1826                 cts->sync_period = 0;
1827         
1828         cts->valid = CCB_TRANS_SYNC_RATE_VALID
1829                    | CCB_TRANS_SYNC_OFFSET_VALID
1830                    | CCB_TRANS_BUS_WIDTH_VALID;
1831         xpt_async(AC_TRANSFER_NEG, cts->ccb_h.path, cts);
1832 }
1833
1834 static void
1835 ahamapmboxes(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1836 {
1837         struct aha_softc* aha;
1838
1839         aha = (struct aha_softc*)arg;
1840         aha->mailbox_physbase = segs->ds_addr;
1841 }
1842
1843 static void
1844 ahamapccbs(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1845 {
1846         struct aha_softc* aha;
1847
1848         aha = (struct aha_softc*)arg;
1849         aha->aha_ccb_physbase = segs->ds_addr;
1850 }
1851
1852 static void
1853 ahamapsgs(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1854 {
1855
1856         struct aha_softc* aha;
1857
1858         aha = (struct aha_softc*)arg;
1859         SLIST_FIRST(&aha->sg_maps)->sg_physaddr = segs->ds_addr;
1860 }
1861
1862 static void
1863 ahapoll(struct cam_sim *sim)
1864 {
1865         aha_intr(cam_sim_softc(sim));
1866 }
1867
1868 static void
1869 ahatimeout(void *arg)
1870 {
1871         struct aha_ccb  *accb;
1872         union  ccb      *ccb;
1873         struct aha_softc *aha;
1874         int              s;
1875         u_int32_t       paddr;
1876
1877         accb = (struct aha_ccb *)arg;
1878         ccb = accb->ccb;
1879         aha = (struct aha_softc *)ccb->ccb_h.ccb_aha_ptr;
1880         xpt_print_path(ccb->ccb_h.path);
1881         printf("CCB %p - timed out\n", (void *)accb);
1882
1883         s = splcam();
1884
1885         if ((accb->flags & ACCB_ACTIVE) == 0) {
1886                 xpt_print_path(ccb->ccb_h.path);
1887                 printf("CCB %p - timed out CCB already completed\n",
1888                        (void *)accb);
1889                 splx(s);
1890                 return;
1891         }
1892
1893         /*
1894          * In order to simplify the recovery process, we ask the XPT
1895          * layer to halt the queue of new transactions and we traverse
1896          * the list of pending CCBs and remove their timeouts. This
1897          * means that the driver attempts to clear only one error
1898          * condition at a time.  In general, timeouts that occur
1899          * close together are related anyway, so there is no benefit
1900          * in attempting to handle errors in parrallel.  Timeouts will
1901          * be reinstated when the recovery process ends.
1902          */
1903         if ((accb->flags & ACCB_DEVICE_RESET) == 0) {
1904                 struct ccb_hdr *ccb_h;
1905
1906                 if ((accb->flags & ACCB_RELEASE_SIMQ) == 0) {
1907                         xpt_freeze_simq(aha->sim, /*count*/1);
1908                         accb->flags |= ACCB_RELEASE_SIMQ;
1909                 }
1910
1911                 ccb_h = LIST_FIRST(&aha->pending_ccbs);
1912                 while (ccb_h != NULL) {
1913                         struct aha_ccb *pending_accb;
1914
1915                         pending_accb = (struct aha_ccb *)ccb_h->ccb_accb_ptr;
1916                         untimeout(ahatimeout, pending_accb, ccb_h->timeout_ch);
1917                         ccb_h = LIST_NEXT(ccb_h, sim_links.le);
1918                 }
1919         }
1920
1921         if ((accb->flags & ACCB_DEVICE_RESET) != 0
1922          || aha->cur_outbox->action_code != AMBO_FREE) {
1923                 /*
1924                  * Try a full host adapter/SCSI bus reset.
1925                  * We do this only if we have already attempted
1926                  * to clear the condition with a BDR, or we cannot
1927                  * attempt a BDR for lack of mailbox resources.
1928                  */
1929                 ccb->ccb_h.status = CAM_CMD_TIMEOUT;
1930                 ahareset(aha, /*hardreset*/TRUE);
1931                 printf("%s: No longer in timeout\n", aha_name(aha));
1932         } else {
1933                 /*    
1934                  * Send a Bus Device Reset message:
1935                  * The target that is holding up the bus may not
1936                  * be the same as the one that triggered this timeout
1937                  * (different commands have different timeout lengths),
1938                  * but we have no way of determining this from our
1939                  * timeout handler.  Our strategy here is to queue a
1940                  * BDR message to the target of the timed out command.
1941                  * If this fails, we'll get another timeout 2 seconds
1942                  * later which will attempt a bus reset.
1943                  */
1944                 accb->flags |= ACCB_DEVICE_RESET;
1945                 ccb->ccb_h.timeout_ch = timeout(ahatimeout, (caddr_t)accb, 2 * hz);
1946                 aha->recovery_accb->hccb.opcode = INITIATOR_BUS_DEV_RESET;
1947
1948                 /* No Data Transfer */
1949                 aha->recovery_accb->hccb.datain = TRUE;
1950                 aha->recovery_accb->hccb.dataout = TRUE;
1951                 aha->recovery_accb->hccb.ahastat = 0;
1952                 aha->recovery_accb->hccb.sdstat = 0;
1953                 aha->recovery_accb->hccb.target = ccb->ccb_h.target_id;
1954
1955                 /* Tell the adapter about this command */
1956                 paddr = ahaccbvtop(aha, aha->recovery_accb);
1957                 ahautoa24(paddr, aha->cur_outbox->ccb_addr);
1958                 aha->cur_outbox->action_code = AMBO_START;
1959                 aha_outb(aha, COMMAND_REG, AOP_START_MBOX);
1960                 ahanextoutbox(aha);
1961         }
1962
1963         splx(s);
1964 }
1965
1966 int
1967 aha_detach(struct aha_softc *aha)
1968 {
1969         xpt_async(AC_LOST_DEVICE, aha->path, NULL);
1970         xpt_free_path(aha->path);
1971         xpt_bus_deregister(cam_sim_path(aha->sim));
1972         cam_sim_free(aha->sim, /*free_devq*/TRUE);
1973         return (0);
1974 }