Rename malloc->kmalloc, free->kfree, and realloc->krealloc. Pass 1
[dragonfly.git] / sys / dev / disk / buslogic / bt.c
1 /*
2  * Generic driver for the BusLogic MultiMaster SCSI host adapters
3  * Product specific probe and attach routines can be found in:
4  * sys/dev/buslogic/bt_isa.c    BT-54X, BT-445 cards
5  * sys/dev/buslogic/bt_eisa.c   BT-74X, BT-75x cards, SDC3222F
6  * sys/dev/buslogic/bt_pci.c    BT-946, BT-948, BT-956, BT-958 cards
7  *
8  * Copyright (c) 1998, 1999 Justin T. Gibbs.
9  * All rights reserved.
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  * $FreeBSD: src/sys/dev/buslogic/bt.c,v 1.25.2.1 2000/08/02 22:32:26 peter Exp $
33  * $DragonFly: src/sys/dev/disk/buslogic/bt.c,v 1.12 2006/09/05 00:55:37 dillon Exp $
34  */
35
36  /*
37   * Special thanks to Leonard N. Zubkoff for writing such a complete and
38   * well documented Mylex/BusLogic MultiMaster driver for Linux.  Support
39   * in this driver for the wide range of MultiMaster controllers and
40   * firmware revisions, with their otherwise undocumented quirks, would not
41   * have been possible without his efforts.
42   */
43
44 #include <sys/param.h>
45 #include <sys/systm.h> 
46 #include <sys/malloc.h>
47 #include <sys/buf.h>
48 #include <sys/kernel.h>
49 #include <sys/sysctl.h>
50 #include <sys/bus.h>
51 #include <sys/thread2.h>
52  
53 /*
54  * XXX It appears that BusLogic PCI adapters go out to lunch if you 
55  *     attempt to perform memory mapped I/O.
56  */
57 #if 0
58 #include "use_pci.h"
59 #if NPCI > 0
60 #include <machine/bus_memio.h>
61 #endif
62 #endif
63 #include <machine/bus_pio.h>
64 #include <machine/bus.h>
65 #include <machine/clock.h>
66 #include <sys/rman.h>
67
68 #include <bus/cam/cam.h>
69 #include <bus/cam/cam_ccb.h>
70 #include <bus/cam/cam_sim.h>
71 #include <bus/cam/cam_xpt_sim.h>
72 #include <bus/cam/cam_debug.h>
73
74 #include <bus/cam/scsi/scsi_message.h>
75
76 #include <vm/vm.h>
77 #include <vm/pmap.h>
78  
79 #include "btreg.h"
80
81 /* MailBox Management functions */
82 static __inline void    btnextinbox(struct bt_softc *bt);
83 static __inline void    btnextoutbox(struct bt_softc *bt);
84
85 static __inline void
86 btnextinbox(struct bt_softc *bt)
87 {
88         if (bt->cur_inbox == bt->last_inbox)
89                 bt->cur_inbox = bt->in_boxes;
90         else
91                 bt->cur_inbox++;
92 }
93
94 static __inline void
95 btnextoutbox(struct bt_softc *bt)
96 {
97         if (bt->cur_outbox == bt->last_outbox)
98                 bt->cur_outbox = bt->out_boxes;
99         else
100                 bt->cur_outbox++;
101 }
102
103 /* CCB Mangement functions */
104 static __inline u_int32_t               btccbvtop(struct bt_softc *bt,
105                                                   struct bt_ccb *bccb);
106 static __inline struct bt_ccb*          btccbptov(struct bt_softc *bt,
107                                                   u_int32_t ccb_addr);
108 static __inline u_int32_t               btsensepaddr(struct bt_softc *bt,
109                                                      struct bt_ccb *bccb);
110 static __inline struct scsi_sense_data* btsensevaddr(struct bt_softc *bt,
111                                                      struct bt_ccb *bccb);
112
113 static __inline u_int32_t
114 btccbvtop(struct bt_softc *bt, struct bt_ccb *bccb)
115 {
116         return (bt->bt_ccb_physbase
117               + (u_int32_t)((caddr_t)bccb - (caddr_t)bt->bt_ccb_array));
118 }
119
120 static __inline struct bt_ccb *
121 btccbptov(struct bt_softc *bt, u_int32_t ccb_addr)
122 {
123         return (bt->bt_ccb_array +
124                 ((struct bt_ccb*)ccb_addr-(struct bt_ccb*)bt->bt_ccb_physbase));
125 }
126
127 static __inline u_int32_t
128 btsensepaddr(struct bt_softc *bt, struct bt_ccb *bccb)
129 {
130         u_int index;
131
132         index = (u_int)(bccb - bt->bt_ccb_array);
133         return (bt->sense_buffers_physbase
134                 + (index * sizeof(struct scsi_sense_data)));
135 }
136
137 static __inline struct scsi_sense_data *
138 btsensevaddr(struct bt_softc *bt, struct bt_ccb *bccb)
139 {
140         u_int index;
141
142         index = (u_int)(bccb - bt->bt_ccb_array);
143         return (bt->sense_buffers + index);
144 }
145
146 static __inline struct bt_ccb*  btgetccb(struct bt_softc *bt);
147 static __inline void            btfreeccb(struct bt_softc *bt,
148                                           struct bt_ccb *bccb);
149 static void             btallocccbs(struct bt_softc *bt);
150 static bus_dmamap_callback_t btexecuteccb;
151 static void             btdone(struct bt_softc *bt, struct bt_ccb *bccb,
152                                bt_mbi_comp_code_t comp_code);
153
154 /* Host adapter command functions */
155 static int      btreset(struct bt_softc* bt, int hard_reset);
156
157 /* Initialization functions */
158 static int                      btinitmboxes(struct bt_softc *bt);
159 static bus_dmamap_callback_t    btmapmboxes;
160 static bus_dmamap_callback_t    btmapccbs;
161 static bus_dmamap_callback_t    btmapsgs;
162
163 /* Transfer Negotiation Functions */
164 static void btfetchtransinfo(struct bt_softc *bt,
165                              struct ccb_trans_settings *cts);
166
167 /* CAM SIM entry points */
168 #define ccb_bccb_ptr spriv_ptr0
169 #define ccb_bt_ptr spriv_ptr1
170 static void     btaction(struct cam_sim *sim, union ccb *ccb);
171 static void     btpoll(struct cam_sim *sim);
172
173 /* Our timeout handler */
174 timeout_t bttimeout;
175
176 u_long bt_unit = 0;
177
178 /*
179  * XXX
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 struct bt_isa_port bt_isa_ports[] =
185 {
186         { 0x130, 0, 4 },
187         { 0x134, 0, 5 },
188         { 0x230, 0, 2 },
189         { 0x234, 0, 3 },
190         { 0x330, 0, 0 },
191         { 0x334, 0, 1 }
192 };
193
194 /*
195  * I/O ports listed in the order enumerated by the
196  * card for certain op codes.
197  */
198 u_int16_t bt_board_ports[] =
199 {
200         0x330,
201         0x334,
202         0x230,
203         0x234,
204         0x130,
205         0x134
206 };
207
208 /* Exported functions */
209 void
210 bt_init_softc(device_t dev, struct resource *port,
211               struct resource *irq, struct resource *drq)
212 {
213         struct bt_softc *bt = device_get_softc(dev);
214
215         SLIST_INIT(&bt->free_bt_ccbs);
216         LIST_INIT(&bt->pending_ccbs);
217         SLIST_INIT(&bt->sg_maps);
218         bt->dev = dev;
219         bt->unit = device_get_unit(dev);
220         bt->port = port;
221         bt->irq = irq;
222         bt->drq = drq;
223         bt->tag = rman_get_bustag(port);
224         bt->bsh = rman_get_bushandle(port);
225 }
226
227 void
228 bt_free_softc(device_t dev)
229 {
230         struct bt_softc *bt = device_get_softc(dev);
231
232         switch (bt->init_level) {
233         default:
234         case 11:
235                 bus_dmamap_unload(bt->sense_dmat, bt->sense_dmamap);
236         case 10:
237                 bus_dmamem_free(bt->sense_dmat, bt->sense_buffers,
238                                 bt->sense_dmamap);
239         case 9:
240                 bus_dma_tag_destroy(bt->sense_dmat);
241         case 8:
242         {
243                 struct sg_map_node *sg_map;
244
245                 while ((sg_map = SLIST_FIRST(&bt->sg_maps))!= NULL) {
246                         SLIST_REMOVE_HEAD(&bt->sg_maps, links);
247                         bus_dmamap_unload(bt->sg_dmat,
248                                           sg_map->sg_dmamap);
249                         bus_dmamem_free(bt->sg_dmat, sg_map->sg_vaddr,
250                                         sg_map->sg_dmamap);
251                         kfree(sg_map, M_DEVBUF);
252                 }
253                 bus_dma_tag_destroy(bt->sg_dmat);
254         }
255         case 7:
256                 bus_dmamap_unload(bt->ccb_dmat, bt->ccb_dmamap);
257         case 6:
258                 bus_dmamem_free(bt->ccb_dmat, bt->bt_ccb_array,
259                                 bt->ccb_dmamap);
260                 bus_dmamap_destroy(bt->ccb_dmat, bt->ccb_dmamap);
261         case 5:
262                 bus_dma_tag_destroy(bt->ccb_dmat);
263         case 4:
264                 bus_dmamap_unload(bt->mailbox_dmat, bt->mailbox_dmamap);
265         case 3:
266                 bus_dmamem_free(bt->mailbox_dmat, bt->in_boxes,
267                                 bt->mailbox_dmamap);
268                 bus_dmamap_destroy(bt->mailbox_dmat, bt->mailbox_dmamap);
269         case 2:
270                 bus_dma_tag_destroy(bt->buffer_dmat);
271         case 1:
272                 bus_dma_tag_destroy(bt->mailbox_dmat);
273         case 0:
274                 break;
275         }
276 }
277
278 int
279 bt_port_probe(device_t dev, struct bt_probe_info *info)
280 {
281         struct bt_softc *bt = device_get_softc(dev);
282         config_data_t config_data;
283         int error;
284
285         /* See if there is really a card present */
286         if (bt_probe(dev) || bt_fetch_adapter_info(dev))
287                 return(1);
288
289         /*
290          * Determine our IRQ, and DMA settings and
291          * export them to the configuration system.
292          */
293         error = bt_cmd(bt, BOP_INQUIRE_CONFIG, NULL, /*parmlen*/0,
294                        (u_int8_t*)&config_data, sizeof(config_data),
295                        DEFAULT_CMD_TIMEOUT);
296         if (error != 0) {
297                 printf("bt_port_probe: Could not determine IRQ or DMA "
298                        "settings for adapter.\n");
299                 return (1);
300         }
301
302         if (bt->model[0] == '5') {
303                 /* DMA settings only make sense for ISA cards */
304                 switch (config_data.dma_chan) {
305                 case DMA_CHAN_5:
306                         info->drq = 5;
307                         break;
308                 case DMA_CHAN_6:
309                         info->drq = 6;
310                         break;
311                 case DMA_CHAN_7:
312                         info->drq = 7;
313                         break;
314                 default:
315                         printf("bt_port_probe: Invalid DMA setting "
316                                "detected for adapter.\n");
317                         return (1);
318                 }
319         } else {
320                 /* VL/EISA/PCI DMA */
321                 info->drq = -1;
322         }
323         switch (config_data.irq) {
324         case IRQ_9:
325         case IRQ_10:
326         case IRQ_11:
327         case IRQ_12:
328         case IRQ_14:
329         case IRQ_15:
330                 info->irq = ffs(config_data.irq) + 8;
331                 break;
332         default:
333                 printf("bt_port_probe: Invalid IRQ setting %x"
334                        "detected for adapter.\n", config_data.irq);
335                 return (1);
336         }
337         return (0);
338 }
339
340 /*
341  * Probe the adapter and verify that the card is a BusLogic.
342  */
343 int
344 bt_probe(device_t dev)
345 {
346         struct bt_softc *bt = device_get_softc(dev);
347         esetup_info_data_t esetup_info;
348         u_int    status;
349         u_int    intstat;
350         u_int    geometry;
351         int      error;
352         u_int8_t param;
353
354         /*
355          * See if the three I/O ports look reasonable.
356          * Touch the minimal number of registers in the
357          * failure case.
358          */
359         status = bt_inb(bt, STATUS_REG);
360         if ((status == 0)
361          || (status & (DIAG_ACTIVE|CMD_REG_BUSY|
362                        STATUS_REG_RSVD|CMD_INVALID)) != 0) {
363                 if (bootverbose)
364                         device_printf(dev, "Failed Status Reg Test - %x\n",
365                                status);
366                 return (ENXIO);
367         }
368
369         intstat = bt_inb(bt, INTSTAT_REG);
370         if ((intstat & INTSTAT_REG_RSVD) != 0) {
371                 device_printf(dev, "Failed Intstat Reg Test\n");
372                 return (ENXIO);
373         }
374
375         geometry = bt_inb(bt, GEOMETRY_REG);
376         if (geometry == 0xFF) {
377                 if (bootverbose)
378                         device_printf(dev, "Failed Geometry Reg Test\n");
379                 return (ENXIO);
380         }
381
382         /*
383          * Looking good so far.  Final test is to reset the
384          * adapter and attempt to fetch the extended setup
385          * information.  This should filter out all 1542 cards.
386          */
387         if ((error = btreset(bt, /*hard_reset*/TRUE)) != 0) {
388                 if (bootverbose)
389                         device_printf(dev, "Failed Reset\n");
390                 return (ENXIO);
391         }
392         
393         param = sizeof(esetup_info);
394         error = bt_cmd(bt, BOP_INQUIRE_ESETUP_INFO, &param, /*parmlen*/1,
395                        (u_int8_t*)&esetup_info, sizeof(esetup_info),
396                        DEFAULT_CMD_TIMEOUT);
397         if (error != 0) {
398                 return (ENXIO);
399         }
400
401         return (0);
402 }
403
404 /*
405  * Pull the boards setup information and record it in our softc.
406  */
407 int
408 bt_fetch_adapter_info(device_t dev)
409 {
410         struct bt_softc *bt = device_get_softc(dev);
411         board_id_data_t board_id;
412         esetup_info_data_t esetup_info;
413         config_data_t config_data;
414         int      error;
415         u_int8_t length_param;
416
417         /* First record the firmware version */
418         error = bt_cmd(bt, BOP_INQUIRE_BOARD_ID, NULL, /*parmlen*/0,
419                        (u_int8_t*)&board_id, sizeof(board_id),
420                        DEFAULT_CMD_TIMEOUT);
421         if (error != 0) {
422                 device_printf(dev, "bt_fetch_adapter_info - Failed Get Board Info\n");
423                 return (error);
424         }
425         bt->firmware_ver[0] = board_id.firmware_rev_major;
426         bt->firmware_ver[1] = '.';
427         bt->firmware_ver[2] = board_id.firmware_rev_minor;
428         bt->firmware_ver[3] = '\0';
429                 
430         /*
431          * Depending on the firmware major and minor version,
432          * we may be able to fetch additional minor version info.
433          */
434         if (bt->firmware_ver[0] > '0') {
435                 
436                 error = bt_cmd(bt, BOP_INQUIRE_FW_VER_3DIG, NULL, /*parmlen*/0,
437                                (u_int8_t*)&bt->firmware_ver[3], 1,
438                                DEFAULT_CMD_TIMEOUT);
439                 if (error != 0) {
440                         device_printf(dev,
441                                       "bt_fetch_adapter_info - Failed Get "
442                                       "Firmware 3rd Digit\n");
443                         return (error);
444                 }
445                 if (bt->firmware_ver[3] == ' ')
446                         bt->firmware_ver[3] = '\0';
447                 bt->firmware_ver[4] = '\0';
448         }
449
450         if (strcmp(bt->firmware_ver, "3.3") >= 0) {
451
452                 error = bt_cmd(bt, BOP_INQUIRE_FW_VER_4DIG, NULL, /*parmlen*/0,
453                                (u_int8_t*)&bt->firmware_ver[4], 1,
454                                DEFAULT_CMD_TIMEOUT);
455                 if (error != 0) {
456                         device_printf(dev,
457                                       "bt_fetch_adapter_info - Failed Get "
458                                       "Firmware 4th Digit\n");
459                         return (error);
460                 }
461                 if (bt->firmware_ver[4] == ' ')
462                         bt->firmware_ver[4] = '\0';
463                 bt->firmware_ver[5] = '\0';
464         }
465
466         /*
467          * Some boards do not handle the "recently documented"
468          * Inquire Board Model Number command correctly or do not give
469          * exact information.  Use the Firmware and Extended Setup
470          * information in these cases to come up with the right answer.
471          * The major firmware revision number indicates:
472          *
473          *      5.xx    BusLogic "W" Series Host Adapters:
474          *              BT-948/958/958D
475          *      4.xx    BusLogic "C" Series Host Adapters:
476          *              BT-946C/956C/956CD/747C/757C/757CD/445C/545C/540CF
477          *      3.xx    BusLogic "S" Series Host Adapters:
478          *              BT-747S/747D/757S/757D/445S/545S/542D
479          *              BT-542B/742A (revision H)
480          *      2.xx    BusLogic "A" Series Host Adapters:
481          *              BT-542B/742A (revision G and below)
482          *      0.xx    AMI FastDisk VLB/EISA BusLogic Clone Host Adapter
483          */
484         length_param = sizeof(esetup_info);
485         error = bt_cmd(bt, BOP_INQUIRE_ESETUP_INFO, &length_param, /*parmlen*/1,
486                        (u_int8_t*)&esetup_info, sizeof(esetup_info),
487                        DEFAULT_CMD_TIMEOUT);
488         if (error != 0) {
489                 return (error);
490         }
491         
492         bt->bios_addr = esetup_info.bios_addr << 12;
493
494         if (esetup_info.bus_type == 'A'
495          && bt->firmware_ver[0] == '2') {
496                 snprintf(bt->model, sizeof(bt->model), "542B");
497         } else if (esetup_info.bus_type == 'E'
498                 && (strncmp(bt->firmware_ver, "2.1", 3) == 0
499                  || strncmp(bt->firmware_ver, "2.20", 4) == 0)) {
500                 snprintf(bt->model, sizeof(bt->model), "742A");
501         } else if (esetup_info.bus_type == 'E'
502                 && bt->firmware_ver[0] == '0') {
503                 /* AMI FastDisk EISA Series 441 0.x */
504                 snprintf(bt->model, sizeof(bt->model), "747A");
505         } else {
506                 ha_model_data_t model_data;
507                 int i;
508
509                 length_param = sizeof(model_data);
510                 error = bt_cmd(bt, BOP_INQUIRE_MODEL, &length_param, 1,
511                                (u_int8_t*)&model_data, sizeof(model_data),
512                                DEFAULT_CMD_TIMEOUT);
513                 if (error != 0) {
514                         device_printf(dev,
515                                       "bt_fetch_adapter_info - Failed Inquire "
516                                       "Model Number\n");
517                         return (error);
518                 }
519                 for (i = 0; i < sizeof(model_data.ascii_model); i++) {
520                         bt->model[i] = model_data.ascii_model[i];
521                         if (bt->model[i] == ' ')
522                                 break;
523                 }
524                 bt->model[i] = '\0';
525         }
526
527         bt->level_trigger_ints = esetup_info.level_trigger_ints ? 1 : 0;
528
529         /* SG element limits */
530         bt->max_sg = esetup_info.max_sg;
531
532         /* Set feature flags */
533         bt->wide_bus = esetup_info.wide_bus;
534         bt->diff_bus = esetup_info.diff_bus;
535         bt->ultra_scsi = esetup_info.ultra_scsi;
536
537         if ((bt->firmware_ver[0] == '5')
538          || (bt->firmware_ver[0] == '4' && bt->wide_bus))
539                 bt->extended_lun = TRUE;
540
541         bt->strict_rr = (strcmp(bt->firmware_ver, "3.31") >= 0);
542
543         bt->extended_trans =
544             ((bt_inb(bt, GEOMETRY_REG) & EXTENDED_TRANSLATION) != 0);
545
546         /*
547          * Determine max CCB count and whether tagged queuing is
548          * available based on controller type. Tagged queuing
549          * only works on 'W' series adapters, 'C' series adapters
550          * with firmware of rev 4.42 and higher, and 'S' series
551          * adapters with firmware of rev 3.35 and higher.  The
552          * maximum CCB counts are as follows:
553          *
554          *      192     BT-948/958/958D
555          *      100     BT-946C/956C/956CD/747C/757C/757CD/445C
556          *      50      BT-545C/540CF
557          *      30      BT-747S/747D/757S/757D/445S/545S/542D/542B/742A
558          */
559         if (bt->firmware_ver[0] == '5') {
560                 bt->max_ccbs = 192;
561                 bt->tag_capable = TRUE;
562         } else if (bt->firmware_ver[0] == '4') {
563                 if (bt->model[0] == '5')
564                         bt->max_ccbs = 50;
565                 else
566                         bt->max_ccbs = 100;
567                 bt->tag_capable = (strcmp(bt->firmware_ver, "4.22") >= 0);
568         } else {
569                 bt->max_ccbs = 30;
570                 if (bt->firmware_ver[0] == '3'
571                  && (strcmp(bt->firmware_ver, "3.35") >= 0))
572                         bt->tag_capable = TRUE;
573                 else
574                         bt->tag_capable = FALSE;
575         }
576
577         if (bt->tag_capable != FALSE)
578                 bt->tags_permitted = ALL_TARGETS;
579
580         /* Determine Sync/Wide/Disc settings */
581         if (bt->firmware_ver[0] >= '4') {
582                 auto_scsi_data_t auto_scsi_data;
583                 fetch_lram_params_t fetch_lram_params;
584                 int error;
585                 
586                 /*
587                  * These settings are stored in the
588                  * AutoSCSI data in LRAM of 'W' and 'C'
589                  * adapters.
590                  */
591                 fetch_lram_params.offset = AUTO_SCSI_BYTE_OFFSET;
592                 fetch_lram_params.response_len = sizeof(auto_scsi_data);
593                 error = bt_cmd(bt, BOP_FETCH_LRAM,
594                                (u_int8_t*)&fetch_lram_params,
595                                sizeof(fetch_lram_params),
596                                (u_int8_t*)&auto_scsi_data,
597                                sizeof(auto_scsi_data), DEFAULT_CMD_TIMEOUT);
598
599                 if (error != 0) {
600                         device_printf(dev,
601                                       "bt_fetch_adapter_info - Failed "
602                                       "Get Auto SCSI Info\n");
603                         return (error);
604                 }
605
606                 bt->disc_permitted = auto_scsi_data.low_disc_permitted
607                                    | (auto_scsi_data.high_disc_permitted << 8);
608                 bt->sync_permitted = auto_scsi_data.low_sync_permitted
609                                    | (auto_scsi_data.high_sync_permitted << 8);
610                 bt->fast_permitted = auto_scsi_data.low_fast_permitted
611                                    | (auto_scsi_data.high_fast_permitted << 8);
612                 bt->ultra_permitted = auto_scsi_data.low_ultra_permitted
613                                    | (auto_scsi_data.high_ultra_permitted << 8);
614                 bt->wide_permitted = auto_scsi_data.low_wide_permitted
615                                    | (auto_scsi_data.high_wide_permitted << 8);
616
617                 if (bt->ultra_scsi == FALSE)
618                         bt->ultra_permitted = 0;
619
620                 if (bt->wide_bus == FALSE)
621                         bt->wide_permitted = 0;
622         } else {
623                 /*
624                  * 'S' and 'A' series have this information in the setup
625                  * information structure.
626                  */
627                 setup_data_t    setup_info;
628
629                 length_param = sizeof(setup_info);
630                 error = bt_cmd(bt, BOP_INQUIRE_SETUP_INFO, &length_param,
631                                /*paramlen*/1, (u_int8_t*)&setup_info,
632                                sizeof(setup_info), DEFAULT_CMD_TIMEOUT);
633
634                 if (error != 0) {
635                         device_printf(dev,
636                                       "bt_fetch_adapter_info - Failed "
637                                       "Get Setup Info\n");
638                         return (error);
639                 }
640
641                 if (setup_info.initiate_sync != 0) {
642                         bt->sync_permitted = ALL_TARGETS;
643
644                         if (bt->model[0] == '7') {
645                                 if (esetup_info.sync_neg10MB != 0)
646                                         bt->fast_permitted = ALL_TARGETS;
647                                 if (strcmp(bt->model, "757") == 0)
648                                         bt->wide_permitted = ALL_TARGETS;
649                         }
650                 }
651                 bt->disc_permitted = ALL_TARGETS;
652         }
653
654         /* We need as many mailboxes as we can have ccbs */
655         bt->num_boxes = bt->max_ccbs;
656
657         /* Determine our SCSI ID */
658         
659         error = bt_cmd(bt, BOP_INQUIRE_CONFIG, NULL, /*parmlen*/0,
660                        (u_int8_t*)&config_data, sizeof(config_data),
661                        DEFAULT_CMD_TIMEOUT);
662         if (error != 0) {
663                 device_printf(dev,
664                               "bt_fetch_adapter_info - Failed Get Config\n");
665                 return (error);
666         }
667         bt->scsi_id = config_data.scsi_id;
668
669         return (0);
670 }
671
672 /*
673  * Start the board, ready for normal operation
674  */
675 int
676 bt_init(device_t dev)
677 {
678         struct bt_softc *bt = device_get_softc(dev);
679
680         /* Announce the Adapter */
681         device_printf(dev, "BT-%s FW Rev. %s ", bt->model, bt->firmware_ver);
682
683         if (bt->ultra_scsi != 0)
684                 printf("Ultra ");
685
686         if (bt->wide_bus != 0)
687                 printf("Wide ");
688         else
689                 printf("Narrow ");
690
691         if (bt->diff_bus != 0)
692                 printf("Diff ");
693
694         printf("SCSI Host Adapter, SCSI ID %d, %d CCBs\n", bt->scsi_id,
695                bt->max_ccbs);
696
697         /*
698          * Create our DMA tags.  These tags define the kinds of device
699          * accessible memory allocations and memory mappings we will 
700          * need to perform during normal operation.
701          *
702          * Unless we need to further restrict the allocation, we rely
703          * on the restrictions of the parent dmat, hence the common
704          * use of MAXADDR and MAXSIZE.
705          */
706
707         /* DMA tag for mapping buffers into device visible space. */
708         if (bus_dma_tag_create(bt->parent_dmat, /*alignment*/1, /*boundary*/0,
709                                /*lowaddr*/BUS_SPACE_MAXADDR,
710                                /*highaddr*/BUS_SPACE_MAXADDR,
711                                /*filter*/NULL, /*filterarg*/NULL,
712                                /*maxsize*/MAXBSIZE, /*nsegments*/BT_NSEG,
713                                /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
714                                /*flags*/BUS_DMA_ALLOCNOW,
715                                &bt->buffer_dmat) != 0) {
716                 goto error_exit;
717         }
718
719         bt->init_level++;
720         /* DMA tag for our mailboxes */
721         if (bus_dma_tag_create(bt->parent_dmat, /*alignment*/1, /*boundary*/0,
722                                /*lowaddr*/BUS_SPACE_MAXADDR,
723                                /*highaddr*/BUS_SPACE_MAXADDR,
724                                /*filter*/NULL, /*filterarg*/NULL,
725                                bt->num_boxes * (sizeof(bt_mbox_in_t)
726                                               + sizeof(bt_mbox_out_t)),
727                                /*nsegments*/1,
728                                /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
729                                /*flags*/0, &bt->mailbox_dmat) != 0) {
730                 goto error_exit;
731         }
732
733         bt->init_level++;
734
735         /* Allocation for our mailboxes */
736         if (bus_dmamem_alloc(bt->mailbox_dmat, (void **)&bt->out_boxes,
737                              BUS_DMA_NOWAIT, &bt->mailbox_dmamap) != 0) {
738                 goto error_exit;
739         }
740
741         bt->init_level++;
742
743         /* And permanently map them */
744         bus_dmamap_load(bt->mailbox_dmat, bt->mailbox_dmamap,
745                         bt->out_boxes,
746                         bt->num_boxes * (sizeof(bt_mbox_in_t)
747                                        + sizeof(bt_mbox_out_t)),
748                         btmapmboxes, bt, /*flags*/0);
749
750         bt->init_level++;
751
752         bt->in_boxes = (bt_mbox_in_t *)&bt->out_boxes[bt->num_boxes];
753
754         btinitmboxes(bt);
755
756         /* DMA tag for our ccb structures */
757         if (bus_dma_tag_create(bt->parent_dmat, /*alignment*/1, /*boundary*/0,
758                                /*lowaddr*/BUS_SPACE_MAXADDR,
759                                /*highaddr*/BUS_SPACE_MAXADDR,
760                                /*filter*/NULL, /*filterarg*/NULL,
761                                bt->max_ccbs * sizeof(struct bt_ccb),
762                                /*nsegments*/1,
763                                /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
764                                /*flags*/0, &bt->ccb_dmat) != 0) {
765                 goto error_exit;
766         }
767
768         bt->init_level++;
769
770         /* Allocation for our ccbs */
771         if (bus_dmamem_alloc(bt->ccb_dmat, (void **)&bt->bt_ccb_array,
772                              BUS_DMA_NOWAIT, &bt->ccb_dmamap) != 0) {
773                 goto error_exit;
774         }
775
776         bt->init_level++;
777
778         /* And permanently map them */
779         bus_dmamap_load(bt->ccb_dmat, bt->ccb_dmamap,
780                         bt->bt_ccb_array,
781                         bt->max_ccbs * sizeof(struct bt_ccb),
782                         btmapccbs, bt, /*flags*/0);
783
784         bt->init_level++;
785
786         /* DMA tag for our S/G structures.  We allocate in page sized chunks */
787         if (bus_dma_tag_create(bt->parent_dmat, /*alignment*/1, /*boundary*/0,
788                                /*lowaddr*/BUS_SPACE_MAXADDR,
789                                /*highaddr*/BUS_SPACE_MAXADDR,
790                                /*filter*/NULL, /*filterarg*/NULL,
791                                PAGE_SIZE, /*nsegments*/1,
792                                /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
793                                /*flags*/0, &bt->sg_dmat) != 0) {
794                 goto error_exit;
795         }
796
797         bt->init_level++;
798
799         /* Perform initial CCB allocation */
800         bzero(bt->bt_ccb_array, bt->max_ccbs * sizeof(struct bt_ccb));
801         btallocccbs(bt);
802
803         if (bt->num_ccbs == 0) {
804                 device_printf(dev,
805                               "bt_init - Unable to allocate initial ccbs\n");
806                 goto error_exit;
807         }
808
809         /*
810          * Note that we are going and return (to probe)
811          */
812         return 0;
813
814 error_exit:
815
816         return (ENXIO);
817 }
818
819 int
820 bt_attach(device_t dev)
821 {
822         struct bt_softc *bt = device_get_softc(dev);
823         int tagged_dev_openings;
824         struct cam_devq *devq;
825         int error;
826
827         /*
828          * We reserve 1 ccb for error recovery, so don't
829          * tell the XPT about it.
830          */
831         if (bt->tag_capable != 0)
832                 tagged_dev_openings = bt->max_ccbs - 1;
833         else
834                 tagged_dev_openings = 0;
835
836         /*
837          * Create the device queue for our SIM.
838          */
839         devq = cam_simq_alloc(bt->max_ccbs - 1);
840         if (devq == NULL)
841                 return (ENOMEM);
842
843         /*
844          * Construct our SIM entry
845          */
846         bt->sim = cam_sim_alloc(btaction, btpoll, "bt", bt, bt->unit,
847                                 2, tagged_dev_openings, devq);
848         cam_simq_release(devq);
849         if (bt->sim == NULL)
850                 return (ENOMEM);
851         
852         if (xpt_bus_register(bt->sim, 0) != CAM_SUCCESS) {
853                 cam_sim_free(bt->sim);
854                 return (ENXIO);
855         }
856         
857         if (xpt_create_path(&bt->path, /*periph*/NULL,
858                             cam_sim_path(bt->sim), CAM_TARGET_WILDCARD,
859                             CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
860                 xpt_bus_deregister(cam_sim_path(bt->sim));
861                 cam_sim_free(bt->sim);
862                 return (ENXIO);
863         }
864                 
865         /*
866          * Setup interrupt.
867          */
868         error = bus_setup_intr(dev, bt->irq, 0,
869                                bt_intr, bt, &bt->ih, NULL);
870         if (error) {
871                 device_printf(dev, "bus_setup_intr() failed: %d\n", error);
872                 return (error);
873         }
874
875         return (0);
876 }
877
878 int
879 bt_check_probed_iop(u_int ioport)
880 {
881         u_int i;
882
883         for (i = 0; i < BT_NUM_ISAPORTS; i++) {
884                 if (bt_isa_ports[i].addr == ioport) {
885                         if (bt_isa_ports[i].probed != 0)
886                                 return (1);
887                         else {
888                                 return (0);
889                         }
890                 }
891         }
892         return (1);
893 }
894
895 void
896 bt_mark_probed_bio(isa_compat_io_t port)
897 {
898         if (port < BIO_DISABLED)
899                 bt_mark_probed_iop(bt_board_ports[port]);
900 }
901
902 void
903 bt_mark_probed_iop(u_int ioport)
904 {
905         u_int i;
906
907         for (i = 0; i < BT_NUM_ISAPORTS; i++) {
908                 if (ioport == bt_isa_ports[i].addr) {
909                         bt_isa_ports[i].probed = 1;
910                         break;
911                 }
912         }
913 }
914
915 void
916 bt_find_probe_range(int ioport, int *port_index, int *max_port_index)
917 {
918         if (ioport > 0) {
919                 int i;
920
921                 for (i = 0;i < BT_NUM_ISAPORTS; i++)
922                         if (ioport <= bt_isa_ports[i].addr)
923                                 break;
924                 if ((i >= BT_NUM_ISAPORTS)
925                  || (ioport != bt_isa_ports[i].addr)) {
926                         printf("\nbt_isa_probe: Invalid baseport of 0x%x specified.\n"
927                                "bt_isa_probe: Nearest valid baseport is 0x%x.\n"
928                                "bt_isa_probe: Failing probe.\n",
929                                ioport,
930                                (i < BT_NUM_ISAPORTS)
931                                     ? bt_isa_ports[i].addr
932                                     : bt_isa_ports[BT_NUM_ISAPORTS - 1].addr);
933                         *port_index = *max_port_index = -1;
934                         return;
935                 }
936                 *port_index = *max_port_index = bt_isa_ports[i].bio;
937         } else {
938                 *port_index = 0;
939                 *max_port_index = BT_NUM_ISAPORTS - 1;
940         }
941 }
942
943 int
944 bt_iop_from_bio(isa_compat_io_t bio_index)
945 {
946         if (bio_index >= 0 && bio_index < BT_NUM_ISAPORTS)
947                 return (bt_board_ports[bio_index]);
948         return (-1);
949 }
950
951
952 static void
953 btallocccbs(struct bt_softc *bt)
954 {
955         struct bt_ccb *next_ccb;
956         struct sg_map_node *sg_map;
957         bus_addr_t physaddr;
958         bt_sg_t *segs;
959         int newcount;
960         int i;
961
962         if (bt->num_ccbs >= bt->max_ccbs)
963                 /* Can't allocate any more */
964                 return;
965
966         next_ccb = &bt->bt_ccb_array[bt->num_ccbs];
967
968         sg_map = kmalloc(sizeof(*sg_map), M_DEVBUF, M_WAITOK);
969
970         /* Allocate S/G space for the next batch of CCBS */
971         if (bus_dmamem_alloc(bt->sg_dmat, (void **)&sg_map->sg_vaddr,
972                              BUS_DMA_NOWAIT, &sg_map->sg_dmamap) != 0) {
973                 kfree(sg_map, M_DEVBUF);
974                 goto error_exit;
975         }
976
977         SLIST_INSERT_HEAD(&bt->sg_maps, sg_map, links);
978
979         bus_dmamap_load(bt->sg_dmat, sg_map->sg_dmamap, sg_map->sg_vaddr,
980                         PAGE_SIZE, btmapsgs, bt, /*flags*/0);
981         
982         segs = sg_map->sg_vaddr;
983         physaddr = sg_map->sg_physaddr;
984
985         newcount = (PAGE_SIZE / (BT_NSEG * sizeof(bt_sg_t)));
986         for (i = 0; bt->num_ccbs < bt->max_ccbs && i < newcount; i++) {
987                 int error;
988
989                 next_ccb->sg_list = segs;
990                 next_ccb->sg_list_phys = physaddr;
991                 next_ccb->flags = BCCB_FREE;
992                 error = bus_dmamap_create(bt->buffer_dmat, /*flags*/0,
993                                           &next_ccb->dmamap);
994                 if (error != 0)
995                         break;
996                 SLIST_INSERT_HEAD(&bt->free_bt_ccbs, next_ccb, links);
997                 segs += BT_NSEG;
998                 physaddr += (BT_NSEG * sizeof(bt_sg_t));
999                 next_ccb++;
1000                 bt->num_ccbs++;
1001         }
1002
1003         /* Reserve a CCB for error recovery */
1004         if (bt->recovery_bccb == NULL) {
1005                 bt->recovery_bccb = SLIST_FIRST(&bt->free_bt_ccbs);
1006                 SLIST_REMOVE_HEAD(&bt->free_bt_ccbs, links);
1007         }
1008
1009         if (SLIST_FIRST(&bt->free_bt_ccbs) != NULL)
1010                 return;
1011
1012 error_exit:
1013         device_printf(bt->dev, "Can't malloc BCCBs\n");
1014 }
1015
1016 static __inline void
1017 btfreeccb(struct bt_softc *bt, struct bt_ccb *bccb)
1018 {
1019         crit_enter();
1020         if ((bccb->flags & BCCB_ACTIVE) != 0)
1021                 LIST_REMOVE(&bccb->ccb->ccb_h, sim_links.le);
1022         if (bt->resource_shortage != 0
1023          && (bccb->ccb->ccb_h.status & CAM_RELEASE_SIMQ) == 0) {
1024                 bccb->ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1025                 bt->resource_shortage = FALSE;
1026         }
1027         bccb->flags = BCCB_FREE;
1028         SLIST_INSERT_HEAD(&bt->free_bt_ccbs, bccb, links);
1029         bt->active_ccbs--;
1030         crit_exit();
1031 }
1032
1033 static __inline struct bt_ccb*
1034 btgetccb(struct bt_softc *bt)
1035 {
1036         struct  bt_ccb* bccb;
1037
1038         crit_enter();
1039         if ((bccb = SLIST_FIRST(&bt->free_bt_ccbs)) != NULL) {
1040                 SLIST_REMOVE_HEAD(&bt->free_bt_ccbs, links);
1041                 bt->active_ccbs++;
1042         } else {
1043                 btallocccbs(bt);
1044                 bccb = SLIST_FIRST(&bt->free_bt_ccbs);
1045                 if (bccb != NULL) {
1046                         SLIST_REMOVE_HEAD(&bt->free_bt_ccbs, links);
1047                         bt->active_ccbs++;
1048                 }
1049         }
1050         crit_exit();
1051
1052         return (bccb);
1053 }
1054
1055 static void
1056 btaction(struct cam_sim *sim, union ccb *ccb)
1057 {
1058         struct  bt_softc *bt;
1059
1060         CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("btaction\n"));
1061         
1062         bt = (struct bt_softc *)cam_sim_softc(sim);
1063         
1064         switch (ccb->ccb_h.func_code) {
1065         /* Common cases first */
1066         case XPT_SCSI_IO:       /* Execute the requested I/O operation */
1067         case XPT_RESET_DEV:     /* Bus Device Reset the specified SCSI device */
1068         {
1069                 struct  bt_ccb  *bccb;
1070                 struct  bt_hccb *hccb;
1071
1072                 /*
1073                  * get a bccb to use.
1074                  */
1075                 if ((bccb = btgetccb(bt)) == NULL) {
1076                         crit_enter();
1077                         bt->resource_shortage = TRUE;
1078                         crit_exit();
1079                         xpt_freeze_simq(bt->sim, /*count*/1);
1080                         ccb->ccb_h.status = CAM_REQUEUE_REQ;
1081                         xpt_done(ccb);
1082                         return;
1083                 }
1084                 
1085                 hccb = &bccb->hccb;
1086
1087                 /*
1088                  * So we can find the BCCB when an abort is requested
1089                  */
1090                 bccb->ccb = ccb;
1091                 ccb->ccb_h.ccb_bccb_ptr = bccb;
1092                 ccb->ccb_h.ccb_bt_ptr = bt;
1093
1094                 /*
1095                  * Put all the arguments for the xfer in the bccb
1096                  */
1097                 hccb->target_id = ccb->ccb_h.target_id;
1098                 hccb->target_lun = ccb->ccb_h.target_lun;
1099                 hccb->btstat = 0;
1100                 hccb->sdstat = 0;
1101
1102                 if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1103                         struct ccb_scsiio *csio;
1104                         struct ccb_hdr *ccbh;
1105
1106                         csio = &ccb->csio;
1107                         ccbh = &csio->ccb_h;
1108                         hccb->opcode = INITIATOR_CCB_WRESID;
1109                         hccb->datain = (ccb->ccb_h.flags & CAM_DIR_IN) ? 1 : 0;
1110                         hccb->dataout =(ccb->ccb_h.flags & CAM_DIR_OUT) ? 1 : 0;
1111                         hccb->cmd_len = csio->cdb_len;
1112                         if (hccb->cmd_len > sizeof(hccb->scsi_cdb)) {
1113                                 ccb->ccb_h.status = CAM_REQ_INVALID;
1114                                 btfreeccb(bt, bccb);
1115                                 xpt_done(ccb);
1116                                 return;
1117                         }
1118                         hccb->sense_len = csio->sense_len;
1119                         if ((ccbh->flags & CAM_TAG_ACTION_VALID) != 0
1120                          && ccb->csio.tag_action != CAM_TAG_ACTION_NONE) {
1121                                 hccb->tag_enable = TRUE;
1122                                 hccb->tag_type = (ccb->csio.tag_action & 0x3);
1123                         } else {
1124                                 hccb->tag_enable = FALSE;
1125                                 hccb->tag_type = 0;
1126                         }
1127                         if ((ccbh->flags & CAM_CDB_POINTER) != 0) {
1128                                 if ((ccbh->flags & CAM_CDB_PHYS) == 0) {
1129                                         bcopy(csio->cdb_io.cdb_ptr,
1130                                               hccb->scsi_cdb, hccb->cmd_len);
1131                                 } else {
1132                                         /* I guess I could map it in... */
1133                                         ccbh->status = CAM_REQ_INVALID;
1134                                         btfreeccb(bt, bccb);
1135                                         xpt_done(ccb);
1136                                         return;
1137                                 }
1138                         } else {
1139                                 bcopy(csio->cdb_io.cdb_bytes,
1140                                       hccb->scsi_cdb, hccb->cmd_len);
1141                         }
1142                         /* If need be, bounce our sense buffer */
1143                         if (bt->sense_buffers != NULL) {
1144                                 hccb->sense_addr = btsensepaddr(bt, bccb);
1145                         } else {
1146                                 hccb->sense_addr = vtophys(&csio->sense_data);
1147                         }
1148                         /*
1149                          * If we have any data to send with this command,
1150                          * map it into bus space.
1151                          */
1152                         /* Only use S/G if there is a transfer */
1153                         if ((ccbh->flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1154                                 if ((ccbh->flags & CAM_SCATTER_VALID) == 0) {
1155                                         /*
1156                                          * We've been given a pointer
1157                                          * to a single buffer.
1158                                          */
1159                                         if ((ccbh->flags & CAM_DATA_PHYS)==0) {
1160                                                 int error;
1161
1162                                                 crit_enter();
1163                                                 error = bus_dmamap_load(
1164                                                     bt->buffer_dmat,
1165                                                     bccb->dmamap,
1166                                                     csio->data_ptr,
1167                                                     csio->dxfer_len,
1168                                                     btexecuteccb,
1169                                                     bccb,
1170                                                     /*flags*/0);
1171                                                 if (error == EINPROGRESS) {
1172                                                         /*
1173                                                          * So as to maintain
1174                                                          * ordering, freeze the
1175                                                          * controller queue
1176                                                          * until our mapping is
1177                                                          * returned.
1178                                                          */
1179                                                         xpt_freeze_simq(bt->sim,
1180                                                                         1);
1181                                                         csio->ccb_h.status |=
1182                                                             CAM_RELEASE_SIMQ;
1183                                                 }
1184                                                 crit_exit();
1185                                         } else {
1186                                                 struct bus_dma_segment seg; 
1187
1188                                                 /* Pointer to physical buffer */
1189                                                 seg.ds_addr =
1190                                                     (bus_addr_t)csio->data_ptr;
1191                                                 seg.ds_len = csio->dxfer_len;
1192                                                 btexecuteccb(bccb, &seg, 1, 0);
1193                                         }
1194                                 } else {
1195                                         struct bus_dma_segment *segs;
1196
1197                                         if ((ccbh->flags & CAM_DATA_PHYS) != 0)
1198                                                 panic("btaction - Physical "
1199                                                       "segment pointers "
1200                                                       "unsupported");
1201
1202                                         if ((ccbh->flags&CAM_SG_LIST_PHYS)==0)
1203                                                 panic("btaction - Virtual "
1204                                                       "segment addresses "
1205                                                       "unsupported");
1206
1207                                         /* Just use the segments provided */
1208                                         segs = (struct bus_dma_segment *)
1209                                             csio->data_ptr;
1210                                         btexecuteccb(bccb, segs,
1211                                                      csio->sglist_cnt, 0);
1212                                 }
1213                         } else {
1214                                 btexecuteccb(bccb, NULL, 0, 0);
1215                         }
1216                 } else {
1217                         hccb->opcode = INITIATOR_BUS_DEV_RESET;
1218                         /* No data transfer */
1219                         hccb->datain = TRUE;
1220                         hccb->dataout = TRUE;
1221                         hccb->cmd_len = 0;
1222                         hccb->sense_len = 0;
1223                         hccb->tag_enable = FALSE;
1224                         hccb->tag_type = 0;
1225                         btexecuteccb(bccb, NULL, 0, 0);
1226                 }
1227                 break;
1228         }
1229         case XPT_EN_LUN:                /* Enable LUN as a target */
1230         case XPT_TARGET_IO:             /* Execute target I/O request */
1231         case XPT_ACCEPT_TARGET_IO:      /* Accept Host Target Mode CDB */
1232         case XPT_CONT_TARGET_IO:        /* Continue Host Target I/O Connection*/
1233         case XPT_ABORT:                 /* Abort the specified CCB */
1234                 /* XXX Implement */
1235                 ccb->ccb_h.status = CAM_REQ_INVALID;
1236                 xpt_done(ccb);
1237                 break;
1238         case XPT_SET_TRAN_SETTINGS:
1239         {
1240                 /* XXX Implement */
1241                 ccb->ccb_h.status = CAM_PROVIDE_FAIL;
1242                 xpt_done(ccb);
1243                 break;
1244         }
1245         case XPT_GET_TRAN_SETTINGS:
1246         /* Get default/user set transfer settings for the target */
1247         {
1248                 struct  ccb_trans_settings *cts;
1249                 u_int   target_mask;
1250
1251                 cts = &ccb->cts;
1252                 target_mask = 0x01 << ccb->ccb_h.target_id;
1253                 if ((cts->flags & CCB_TRANS_USER_SETTINGS) != 0) {
1254                         cts->flags = 0;
1255                         if ((bt->disc_permitted & target_mask) != 0)
1256                                 cts->flags |= CCB_TRANS_DISC_ENB;
1257                         if ((bt->tags_permitted & target_mask) != 0)
1258                                 cts->flags |= CCB_TRANS_TAG_ENB;
1259                         if ((bt->wide_permitted & target_mask) != 0)
1260                                 cts->bus_width = MSG_EXT_WDTR_BUS_16_BIT;
1261                         else
1262                                 cts->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
1263                         if ((bt->ultra_permitted & target_mask) != 0)
1264                                 cts->sync_period = 12;
1265                         else if ((bt->fast_permitted & target_mask) != 0)
1266                                 cts->sync_period = 25;
1267                         else if ((bt->sync_permitted & target_mask) != 0)
1268                                 cts->sync_period = 50;
1269                         else
1270                                 cts->sync_period = 0;
1271
1272                         if (cts->sync_period != 0)
1273                                 cts->sync_offset = 15;
1274
1275                         cts->valid = CCB_TRANS_SYNC_RATE_VALID
1276                                    | CCB_TRANS_SYNC_OFFSET_VALID
1277                                    | CCB_TRANS_BUS_WIDTH_VALID
1278                                    | CCB_TRANS_DISC_VALID
1279                                    | CCB_TRANS_TQ_VALID;
1280                 } else {
1281                         btfetchtransinfo(bt, cts);
1282                 }
1283
1284                 ccb->ccb_h.status = CAM_REQ_CMP;
1285                 xpt_done(ccb);
1286                 break;
1287         }
1288         case XPT_CALC_GEOMETRY:
1289         {
1290                 struct    ccb_calc_geometry *ccg;
1291                 u_int32_t size_mb;
1292                 u_int32_t secs_per_cylinder;
1293
1294                 ccg = &ccb->ccg;
1295                 size_mb = ccg->volume_size
1296                         / ((1024L * 1024L) / ccg->block_size);
1297                 
1298                 if (size_mb >= 1024 && (bt->extended_trans != 0)) {
1299                         if (size_mb >= 2048) {
1300                                 ccg->heads = 255;
1301                                 ccg->secs_per_track = 63;
1302                         } else {
1303                                 ccg->heads = 128;
1304                                 ccg->secs_per_track = 32;
1305                         }
1306                 } else {
1307                         ccg->heads = 64;
1308                         ccg->secs_per_track = 32;
1309                 }
1310                 secs_per_cylinder = ccg->heads * ccg->secs_per_track;
1311                 ccg->cylinders = ccg->volume_size / secs_per_cylinder;
1312                 ccb->ccb_h.status = CAM_REQ_CMP;
1313                 xpt_done(ccb);
1314                 break;
1315         }
1316         case XPT_RESET_BUS:             /* Reset the specified SCSI bus */
1317         {
1318                 btreset(bt, /*hardreset*/TRUE);
1319                 ccb->ccb_h.status = CAM_REQ_CMP;
1320                 xpt_done(ccb);
1321                 break;
1322         }
1323         case XPT_TERM_IO:               /* Terminate the I/O process */
1324                 /* XXX Implement */
1325                 ccb->ccb_h.status = CAM_REQ_INVALID;
1326                 xpt_done(ccb);
1327                 break;
1328         case XPT_PATH_INQ:              /* Path routing inquiry */
1329         {
1330                 struct ccb_pathinq *cpi = &ccb->cpi;
1331                 
1332                 cpi->version_num = 1; /* XXX??? */
1333                 cpi->hba_inquiry = PI_SDTR_ABLE;
1334                 if (bt->tag_capable != 0)
1335                         cpi->hba_inquiry |= PI_TAG_ABLE;
1336                 if (bt->wide_bus != 0)
1337                         cpi->hba_inquiry |= PI_WIDE_16;
1338                 cpi->target_sprt = 0;
1339                 cpi->hba_misc = 0;
1340                 cpi->hba_eng_cnt = 0;
1341                 cpi->max_target = bt->wide_bus ? 15 : 7;
1342                 cpi->max_lun = 7;
1343                 cpi->initiator_id = bt->scsi_id;
1344                 cpi->bus_id = cam_sim_bus(sim);
1345                 cpi->base_transfer_speed = 3300;
1346                 strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
1347                 strncpy(cpi->hba_vid, "BusLogic", HBA_IDLEN);
1348                 strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
1349                 cpi->unit_number = cam_sim_unit(sim);
1350                 cpi->ccb_h.status = CAM_REQ_CMP;
1351                 xpt_done(ccb);
1352                 break;
1353         }
1354         default:
1355                 ccb->ccb_h.status = CAM_REQ_INVALID;
1356                 xpt_done(ccb);
1357                 break;
1358         }
1359 }
1360
1361 static void
1362 btexecuteccb(void *arg, bus_dma_segment_t *dm_segs, int nseg, int error)
1363 {
1364         struct   bt_ccb *bccb;
1365         union    ccb *ccb;
1366         struct   bt_softc *bt;
1367
1368         bccb = (struct bt_ccb *)arg;
1369         ccb = bccb->ccb;
1370         bt = (struct bt_softc *)ccb->ccb_h.ccb_bt_ptr;
1371
1372         if (error != 0) {
1373                 if (error != EFBIG)
1374                         device_printf(bt->dev,
1375                                       "Unexepected error 0x%x returned from "
1376                                       "bus_dmamap_load\n", error);
1377                 if (ccb->ccb_h.status == CAM_REQ_INPROG) {
1378                         xpt_freeze_devq(ccb->ccb_h.path, /*count*/1);
1379                         ccb->ccb_h.status = CAM_REQ_TOO_BIG|CAM_DEV_QFRZN;
1380                 }
1381                 btfreeccb(bt, bccb);
1382                 xpt_done(ccb);
1383                 return;
1384         }
1385                 
1386         if (nseg != 0) {
1387                 bt_sg_t *sg;
1388                 bus_dma_segment_t *end_seg;
1389                 bus_dmasync_op_t op;
1390
1391                 end_seg = dm_segs + nseg;
1392
1393                 /* Copy the segments into our SG list */
1394                 sg = bccb->sg_list;
1395                 while (dm_segs < end_seg) {
1396                         sg->len = dm_segs->ds_len;
1397                         sg->addr = dm_segs->ds_addr;
1398                         sg++;
1399                         dm_segs++;
1400                 }
1401
1402                 if (nseg > 1) {
1403                         bccb->hccb.opcode = INITIATOR_SG_CCB_WRESID;
1404                         bccb->hccb.data_len = sizeof(bt_sg_t) * nseg;
1405                         bccb->hccb.data_addr = bccb->sg_list_phys;
1406                 } else {
1407                         bccb->hccb.data_len = bccb->sg_list->len;
1408                         bccb->hccb.data_addr = bccb->sg_list->addr;
1409                 }
1410
1411                 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN)
1412                         op = BUS_DMASYNC_PREREAD;
1413                 else
1414                         op = BUS_DMASYNC_PREWRITE;
1415
1416                 bus_dmamap_sync(bt->buffer_dmat, bccb->dmamap, op);
1417
1418         } else {
1419                 bccb->hccb.opcode = INITIATOR_CCB;
1420                 bccb->hccb.data_len = 0;
1421                 bccb->hccb.data_addr = 0;
1422         }
1423
1424         crit_enter();
1425
1426         /*
1427          * Last time we need to check if this CCB needs to
1428          * be aborted.
1429          */
1430         if (ccb->ccb_h.status != CAM_REQ_INPROG) {
1431                 if (nseg != 0)
1432                         bus_dmamap_unload(bt->buffer_dmat, bccb->dmamap);
1433                 btfreeccb(bt, bccb);
1434                 xpt_done(ccb);
1435                 crit_exit();
1436                 return;
1437         }
1438                 
1439         bccb->flags = BCCB_ACTIVE;
1440         ccb->ccb_h.status |= CAM_SIM_QUEUED;
1441         LIST_INSERT_HEAD(&bt->pending_ccbs, &ccb->ccb_h, sim_links.le);
1442
1443         callout_reset(&ccb->ccb_h.timeout_ch, (ccb->ccb_h.timeout * hz) / 1000,
1444             bttimeout, bccb);
1445
1446         /* Tell the adapter about this command */
1447         bt->cur_outbox->ccb_addr = btccbvtop(bt, bccb);
1448         if (bt->cur_outbox->action_code != BMBO_FREE) {
1449                 /*
1450                  * We should never encounter a busy mailbox.
1451                  * If we do, warn the user, and treat it as
1452                  * a resource shortage.  If the controller is
1453                  * hung, one of the pending transactions will
1454                  * timeout causing us to start recovery operations.
1455                  */
1456                 device_printf(bt->dev,
1457                               "Encountered busy mailbox with %d out of %d "
1458                               "commands active!!!\n", bt->active_ccbs,
1459                               bt->max_ccbs);
1460                 callout_stop(&ccb->ccb_h.timeout_ch);
1461                 if (nseg != 0)
1462                         bus_dmamap_unload(bt->buffer_dmat, bccb->dmamap);
1463                 btfreeccb(bt, bccb);
1464                 bt->resource_shortage = TRUE;
1465                 xpt_freeze_simq(bt->sim, /*count*/1);
1466                 ccb->ccb_h.status = CAM_REQUEUE_REQ;
1467                 xpt_done(ccb);
1468                 return;
1469         }
1470         bt->cur_outbox->action_code = BMBO_START;       
1471         bt_outb(bt, COMMAND_REG, BOP_START_MBOX);
1472         btnextoutbox(bt);
1473         crit_exit();
1474 }
1475
1476 void
1477 bt_intr(void *arg)
1478 {
1479         struct  bt_softc *bt;
1480         u_int   intstat;
1481
1482         bt = (struct bt_softc *)arg;
1483         while (((intstat = bt_inb(bt, INTSTAT_REG)) & INTR_PENDING) != 0) {
1484
1485                 if ((intstat & CMD_COMPLETE) != 0) {
1486                         bt->latched_status = bt_inb(bt, STATUS_REG);
1487                         bt->command_cmp = TRUE;
1488                 }
1489
1490                 bt_outb(bt, CONTROL_REG, RESET_INTR);
1491
1492                 if ((intstat & IMB_LOADED) != 0) {
1493                         while (bt->cur_inbox->comp_code != BMBI_FREE) {
1494                                 btdone(bt,
1495                                        btccbptov(bt, bt->cur_inbox->ccb_addr),
1496                                        bt->cur_inbox->comp_code);
1497                                 bt->cur_inbox->comp_code = BMBI_FREE;
1498                                 btnextinbox(bt);
1499                         }
1500                 }
1501
1502                 if ((intstat & SCSI_BUS_RESET) != 0) {
1503                         btreset(bt, /*hardreset*/FALSE);
1504                 }
1505         }
1506 }
1507
1508 static void
1509 btdone(struct bt_softc *bt, struct bt_ccb *bccb, bt_mbi_comp_code_t comp_code)
1510 {
1511         union  ccb        *ccb;
1512         struct ccb_scsiio *csio;
1513
1514         ccb = bccb->ccb;
1515         csio = &bccb->ccb->csio;
1516
1517         if ((bccb->flags & BCCB_ACTIVE) == 0) {
1518                 device_printf(bt->dev,
1519                               "btdone - Attempt to free non-active BCCB %p\n",
1520                               (void *)bccb);
1521                 return;
1522         }
1523
1524         if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1525                 bus_dmasync_op_t op;
1526
1527                 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN)
1528                         op = BUS_DMASYNC_POSTREAD;
1529                 else
1530                         op = BUS_DMASYNC_POSTWRITE;
1531                 bus_dmamap_sync(bt->buffer_dmat, bccb->dmamap, op);
1532                 bus_dmamap_unload(bt->buffer_dmat, bccb->dmamap);
1533         }
1534
1535         if (bccb == bt->recovery_bccb) {
1536                 /*
1537                  * The recovery BCCB does not have a CCB associated
1538                  * with it, so short circuit the normal error handling.
1539                  * We now traverse our list of pending CCBs and process
1540                  * any that were terminated by the recovery CCBs action.
1541                  * We also reinstate timeouts for all remaining, pending,
1542                  * CCBs.
1543                  */
1544                 struct cam_path *path;
1545                 struct ccb_hdr *ccb_h;
1546                 cam_status error;
1547
1548                 /* Notify all clients that a BDR occured */
1549                 error = xpt_create_path(&path, /*periph*/NULL,
1550                                         cam_sim_path(bt->sim),
1551                                         bccb->hccb.target_id,
1552                                         CAM_LUN_WILDCARD);
1553                 
1554                 if (error == CAM_REQ_CMP)
1555                         xpt_async(AC_SENT_BDR, path, NULL);
1556
1557                 ccb_h = LIST_FIRST(&bt->pending_ccbs);
1558                 while (ccb_h != NULL) {
1559                         struct bt_ccb *pending_bccb;
1560
1561                         pending_bccb = (struct bt_ccb *)ccb_h->ccb_bccb_ptr;
1562                         if (pending_bccb->hccb.target_id
1563                          == bccb->hccb.target_id) {
1564                                 pending_bccb->hccb.btstat = BTSTAT_HA_BDR;
1565                                 ccb_h = LIST_NEXT(ccb_h, sim_links.le);
1566                                 btdone(bt, pending_bccb, BMBI_ERROR);
1567                         } else {
1568                                 callout_reset(&ccb_h->timeout_ch,
1569                                     (ccb_h->timeout * hz) / 1000,
1570                                     bttimeout, pending_bccb);
1571                                 ccb_h = LIST_NEXT(ccb_h, sim_links.le);
1572                         }
1573                 }
1574                 device_printf(bt->dev, "No longer in timeout\n");
1575                 return;
1576         }
1577
1578         callout_stop(&ccb->ccb_h.timeout_ch);
1579
1580         switch (comp_code) {
1581         case BMBI_FREE:
1582                 device_printf(bt->dev,
1583                               "btdone - CCB completed with free status!\n");
1584                 break;
1585         case BMBI_NOT_FOUND:
1586                 device_printf(bt->dev,
1587                               "btdone - CCB Abort failed to find CCB\n");
1588                 break;
1589         case BMBI_ABORT:
1590         case BMBI_ERROR:
1591                 if (bootverbose) {
1592                         printf("bt: ccb %p - error %x occured.  "
1593                                "btstat = %x, sdstat = %x\n",
1594                                (void *)bccb, comp_code, bccb->hccb.btstat,
1595                                bccb->hccb.sdstat);
1596                 }
1597                 /* An error occured */
1598                 switch(bccb->hccb.btstat) {
1599                 case BTSTAT_DATARUN_ERROR:
1600                         if (bccb->hccb.data_len == 0) {
1601                                 /*
1602                                  * At least firmware 4.22, does this
1603                                  * for a QUEUE FULL condition.
1604                                  */
1605                                 bccb->hccb.sdstat = SCSI_STATUS_QUEUE_FULL;
1606                         } else if (bccb->hccb.data_len < 0) {
1607                                 csio->ccb_h.status = CAM_DATA_RUN_ERR;
1608                                 break;
1609                         }
1610                         /* FALLTHROUGH */
1611                 case BTSTAT_NOERROR:
1612                 case BTSTAT_LINKED_CMD_COMPLETE:
1613                 case BTSTAT_LINKED_CMD_FLAG_COMPLETE:
1614                 case BTSTAT_DATAUNDERUN_ERROR:
1615
1616                         csio->scsi_status = bccb->hccb.sdstat;
1617                         csio->ccb_h.status |= CAM_SCSI_STATUS_ERROR;
1618                         switch(csio->scsi_status) {
1619                         case SCSI_STATUS_CHECK_COND:
1620                         case SCSI_STATUS_CMD_TERMINATED:
1621                                 csio->ccb_h.status |= CAM_AUTOSNS_VALID;
1622                                 /* Bounce sense back if necessary */
1623                                 if (bt->sense_buffers != NULL) {
1624                                         csio->sense_data =
1625                                             *btsensevaddr(bt, bccb);
1626                                 }
1627                                 break;
1628                         default:
1629                                 break;
1630                         case SCSI_STATUS_OK:
1631                                 csio->ccb_h.status = CAM_REQ_CMP;
1632                                 break;
1633                         }
1634                         csio->resid = bccb->hccb.data_len;
1635                         break;
1636                 case BTSTAT_SELTIMEOUT:
1637                         csio->ccb_h.status = CAM_SEL_TIMEOUT;
1638                         break;
1639                 case BTSTAT_UNEXPECTED_BUSFREE:
1640                         csio->ccb_h.status = CAM_UNEXP_BUSFREE;
1641                         break;
1642                 case BTSTAT_INVALID_PHASE:
1643                         csio->ccb_h.status = CAM_SEQUENCE_FAIL;
1644                         break;
1645                 case BTSTAT_INVALID_ACTION_CODE:
1646                         panic("%s: Inavlid Action code", bt_name(bt));
1647                         break;
1648                 case BTSTAT_INVALID_OPCODE:
1649                         panic("%s: Inavlid CCB Opcode code", bt_name(bt));
1650                         break;
1651                 case BTSTAT_LINKED_CCB_LUN_MISMATCH:
1652                         /* We don't even support linked commands... */
1653                         panic("%s: Linked CCB Lun Mismatch", bt_name(bt));
1654                         break;
1655                 case BTSTAT_INVALID_CCB_OR_SG_PARAM:
1656                         panic("%s: Invalid CCB or SG list", bt_name(bt));
1657                         break;
1658                 case BTSTAT_AUTOSENSE_FAILED:
1659                         csio->ccb_h.status = CAM_AUTOSENSE_FAIL;
1660                         break;
1661                 case BTSTAT_TAGGED_MSG_REJECTED:
1662                 {
1663                         struct ccb_trans_settings neg; 
1664  
1665                         xpt_print_path(csio->ccb_h.path);
1666                         printf("refuses tagged commands.  Performing "
1667                                "non-tagged I/O\n");
1668                         neg.flags = 0;
1669                         neg.valid = CCB_TRANS_TQ_VALID;
1670                         xpt_setup_ccb(&neg.ccb_h, csio->ccb_h.path,
1671                                       /*priority*/1); 
1672                         xpt_async(AC_TRANSFER_NEG, csio->ccb_h.path, &neg);
1673                         bt->tags_permitted &= ~(0x01 << csio->ccb_h.target_id);
1674                         csio->ccb_h.status = CAM_MSG_REJECT_REC;
1675                         break;
1676                 }
1677                 case BTSTAT_UNSUPPORTED_MSG_RECEIVED:
1678                         /*
1679                          * XXX You would think that this is
1680                          *     a recoverable error... Hmmm.
1681                          */
1682                         csio->ccb_h.status = CAM_REQ_CMP_ERR;
1683                         break;
1684                 case BTSTAT_HA_SOFTWARE_ERROR:
1685                 case BTSTAT_HA_WATCHDOG_ERROR:
1686                 case BTSTAT_HARDWARE_FAILURE:
1687                         /* Hardware reset ??? Can we recover ??? */
1688                         csio->ccb_h.status = CAM_NO_HBA;
1689                         break;
1690                 case BTSTAT_TARGET_IGNORED_ATN:
1691                 case BTSTAT_OTHER_SCSI_BUS_RESET:
1692                 case BTSTAT_HA_SCSI_BUS_RESET:
1693                         if ((csio->ccb_h.status & CAM_STATUS_MASK)
1694                          != CAM_CMD_TIMEOUT)
1695                                 csio->ccb_h.status = CAM_SCSI_BUS_RESET;
1696                         break;
1697                 case BTSTAT_HA_BDR:
1698                         if ((bccb->flags & BCCB_DEVICE_RESET) == 0)
1699                                 csio->ccb_h.status = CAM_BDR_SENT;
1700                         else
1701                                 csio->ccb_h.status = CAM_CMD_TIMEOUT;
1702                         break;
1703                 case BTSTAT_INVALID_RECONNECT:
1704                 case BTSTAT_ABORT_QUEUE_GENERATED:
1705                         csio->ccb_h.status = CAM_REQ_TERMIO;
1706                         break;
1707                 case BTSTAT_SCSI_PERROR_DETECTED:
1708                         csio->ccb_h.status = CAM_UNCOR_PARITY;
1709                         break;
1710                 }
1711                 if (csio->ccb_h.status != CAM_REQ_CMP) {
1712                         xpt_freeze_devq(csio->ccb_h.path, /*count*/1);
1713                         csio->ccb_h.status |= CAM_DEV_QFRZN;
1714                 }
1715                 if ((bccb->flags & BCCB_RELEASE_SIMQ) != 0)
1716                         ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1717                 btfreeccb(bt, bccb);
1718                 xpt_done(ccb);
1719                 break;
1720         case BMBI_OK:
1721                 /* All completed without incident */
1722                 ccb->ccb_h.status |= CAM_REQ_CMP;
1723                 if ((bccb->flags & BCCB_RELEASE_SIMQ) != 0)
1724                         ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1725                 btfreeccb(bt, bccb);
1726                 xpt_done(ccb);
1727                 break;
1728         }
1729 }
1730
1731 static int
1732 btreset(struct bt_softc* bt, int hard_reset)
1733 {
1734         struct   ccb_hdr *ccb_h;
1735         u_int    status;
1736         u_int    timeout;
1737         u_int8_t reset_type;
1738
1739         if (hard_reset != 0)
1740                 reset_type = HARD_RESET;
1741         else
1742                 reset_type = SOFT_RESET;
1743         bt_outb(bt, CONTROL_REG, reset_type);
1744
1745         /* Wait 5sec. for Diagnostic start */
1746         timeout = 5 * 10000;
1747         while (--timeout) {
1748                 status = bt_inb(bt, STATUS_REG);
1749                 if ((status & DIAG_ACTIVE) != 0)
1750                         break;
1751                 DELAY(100);
1752         }
1753         if (timeout == 0) {
1754                 if (bootverbose)
1755                         printf("%s: btreset - Diagnostic Active failed to "
1756                                 "assert. status = 0x%x\n", bt_name(bt), status);
1757                 return (ETIMEDOUT);
1758         }
1759
1760         /* Wait 10sec. for Diagnostic end */
1761         timeout = 10 * 10000;
1762         while (--timeout) {
1763                 status = bt_inb(bt, STATUS_REG);
1764                 if ((status & DIAG_ACTIVE) == 0)
1765                         break;
1766                 DELAY(100);
1767         }
1768         if (timeout == 0) {
1769                 panic("%s: btreset - Diagnostic Active failed to drop. "
1770                        "status = 0x%x\n", bt_name(bt), status);
1771                 return (ETIMEDOUT);
1772         }
1773
1774         /* Wait for the host adapter to become ready or report a failure */
1775         timeout = 10000;
1776         while (--timeout) {
1777                 status = bt_inb(bt, STATUS_REG);
1778                 if ((status & (DIAG_FAIL|HA_READY|DATAIN_REG_READY)) != 0)
1779                         break;
1780                 DELAY(100);
1781         }
1782         if (timeout == 0) {
1783                 printf("%s: btreset - Host adapter failed to come ready. "
1784                        "status = 0x%x\n", bt_name(bt), status);
1785                 return (ETIMEDOUT);
1786         }
1787
1788         /* If the diagnostics failed, tell the user */
1789         if ((status & DIAG_FAIL) != 0
1790          || (status & HA_READY) == 0) {
1791                 printf("%s: btreset - Adapter failed diagnostics\n",
1792                        bt_name(bt));
1793
1794                 if ((status & DATAIN_REG_READY) != 0)
1795                         printf("%s: btreset - Host Adapter Error code = 0x%x\n",
1796                                bt_name(bt), bt_inb(bt, DATAIN_REG));
1797                 return (ENXIO);
1798         }
1799
1800         /* If we've allocated mailboxes, initialize them */
1801         if (bt->init_level > 4)
1802                 btinitmboxes(bt);
1803
1804         /* If we've attached to the XPT, tell it about the event */
1805         if (bt->path != NULL)
1806                 xpt_async(AC_BUS_RESET, bt->path, NULL);
1807
1808         /*
1809          * Perform completion processing for all outstanding CCBs.
1810          */
1811         while ((ccb_h = LIST_FIRST(&bt->pending_ccbs)) != NULL) {
1812                 struct bt_ccb *pending_bccb;
1813
1814                 pending_bccb = (struct bt_ccb *)ccb_h->ccb_bccb_ptr;
1815                 pending_bccb->hccb.btstat = BTSTAT_HA_SCSI_BUS_RESET;
1816                 btdone(bt, pending_bccb, BMBI_ERROR);
1817         }
1818
1819         return (0);
1820 }
1821
1822 /*
1823  * Send a command to the adapter.
1824  */
1825 int
1826 bt_cmd(struct bt_softc *bt, bt_op_t opcode, u_int8_t *params, u_int param_len,
1827       u_int8_t *reply_data, u_int reply_len, u_int cmd_timeout)
1828 {
1829         u_int   timeout;
1830         u_int   status;
1831         u_int   saved_status;
1832         u_int   intstat;
1833         u_int   reply_buf_size;
1834         int     cmd_complete;
1835         int     error;
1836
1837         /* No data returned to start */
1838         reply_buf_size = reply_len;
1839         reply_len = 0;
1840         intstat = 0;
1841         cmd_complete = 0;
1842         saved_status = 0;
1843         error = 0;
1844
1845         bt->command_cmp = 0;
1846         /*
1847          * Wait up to 10 sec. for the adapter to become
1848          * ready to accept commands.
1849          */
1850         timeout = 100000;
1851         while (--timeout) {
1852                 status = bt_inb(bt, STATUS_REG);
1853                 if ((status & HA_READY) != 0
1854                  && (status & CMD_REG_BUSY) == 0)
1855                         break;
1856                 /*
1857                  * Throw away any pending data which may be
1858                  * left over from earlier commands that we
1859                  * timedout on.
1860                  */
1861                 if ((status & DATAIN_REG_READY) != 0)
1862                         (void)bt_inb(bt, DATAIN_REG);
1863                 DELAY(100);
1864         }
1865         if (timeout == 0) {
1866                 printf("%s: bt_cmd: Timeout waiting for adapter ready, "
1867                        "status = 0x%x\n", bt_name(bt), status);
1868                 return (ETIMEDOUT);
1869         }
1870
1871         /*
1872          * Send the opcode followed by any necessary parameter bytes.
1873          */
1874         bt_outb(bt, COMMAND_REG, opcode);
1875
1876         /*
1877          * Wait for up to 1sec for each byte of the the
1878          * parameter list sent to be sent.
1879          */
1880         timeout = 10000;
1881         while (param_len && --timeout) {
1882                 DELAY(100);
1883                 crit_enter();
1884                 status = bt_inb(bt, STATUS_REG);
1885                 intstat = bt_inb(bt, INTSTAT_REG);
1886                 crit_exit();
1887         
1888                 if ((intstat & (INTR_PENDING|CMD_COMPLETE))
1889                  == (INTR_PENDING|CMD_COMPLETE)) {
1890                         saved_status = status;
1891                         cmd_complete = 1;
1892                         break;
1893                 }
1894                 if (bt->command_cmp != 0) {
1895                         saved_status = bt->latched_status;
1896                         cmd_complete = 1;
1897                         break;
1898                 }
1899                 if ((status & DATAIN_REG_READY) != 0)
1900                         break;
1901                 if ((status & CMD_REG_BUSY) == 0) {
1902                         bt_outb(bt, COMMAND_REG, *params++);
1903                         param_len--;
1904                         timeout = 10000;
1905                 }
1906         }
1907         if (timeout == 0) {
1908                 printf("%s: bt_cmd: Timeout sending parameters, "
1909                        "status = 0x%x\n", bt_name(bt), status);
1910                 cmd_complete = 1;
1911                 saved_status = status;
1912                 error = ETIMEDOUT;
1913         }
1914
1915         /*
1916          * Wait for the command to complete.
1917          */
1918         while (cmd_complete == 0 && --cmd_timeout) {
1919
1920                 crit_enter();
1921                 status = bt_inb(bt, STATUS_REG);
1922                 intstat = bt_inb(bt, INTSTAT_REG);
1923                 /*
1924                  * It may be that this command was issued with
1925                  * controller interrupts disabled.  We'll never
1926                  * get to our command if an incoming mailbox
1927                  * interrupt is pending, so take care of completed
1928                  * mailbox commands by calling our interrupt handler.
1929                  */
1930                 if ((intstat & (INTR_PENDING|IMB_LOADED))
1931                  == (INTR_PENDING|IMB_LOADED))
1932                         bt_intr(bt);
1933                 crit_exit();
1934
1935                 if (bt->command_cmp != 0) {
1936                         /*
1937                          * Our interrupt handler saw CMD_COMPLETE
1938                          * status before we did.
1939                          */
1940                         cmd_complete = 1;
1941                         saved_status = bt->latched_status;
1942                 } else if ((intstat & (INTR_PENDING|CMD_COMPLETE))
1943                         == (INTR_PENDING|CMD_COMPLETE)) {
1944                         /*
1945                          * Our poll (in case interrupts are blocked)
1946                          * saw the CMD_COMPLETE interrupt.
1947                          */
1948                         cmd_complete = 1;
1949                         saved_status = status;
1950                 } else if (opcode == BOP_MODIFY_IO_ADDR
1951                         && (status & CMD_REG_BUSY) == 0) {
1952                         /*
1953                          * The BOP_MODIFY_IO_ADDR does not issue a CMD_COMPLETE,
1954                          * but it should update the status register.  So, we
1955                          * consider this command complete when the CMD_REG_BUSY
1956                          * status clears.
1957                          */
1958                         saved_status = status;
1959                         cmd_complete = 1;
1960                 } else if ((status & DATAIN_REG_READY) != 0) {
1961                         u_int8_t data;
1962
1963                         data = bt_inb(bt, DATAIN_REG);
1964                         if (reply_len < reply_buf_size) {
1965                                 *reply_data++ = data;
1966                         } else {
1967                                 printf("%s: bt_cmd - Discarded reply data byte "
1968                                        "for opcode 0x%x\n", bt_name(bt),
1969                                        opcode);
1970                         }
1971                         /*
1972                          * Reset timeout to ensure at least a second
1973                          * between response bytes.
1974                          */
1975                         cmd_timeout = MAX(cmd_timeout, 10000);
1976                         reply_len++;
1977
1978                 } else if ((opcode == BOP_FETCH_LRAM)
1979                         && (status & HA_READY) != 0) {
1980                                 saved_status = status;
1981                                 cmd_complete = 1;
1982                 }
1983                 DELAY(100);
1984         }
1985         if (cmd_timeout == 0) {
1986                 printf("%s: bt_cmd: Timeout waiting for command (%x) "
1987                        "to complete.\n%s: status = 0x%x, intstat = 0x%x, "
1988                        "rlen %d\n", bt_name(bt), opcode,
1989                        bt_name(bt), status, intstat, reply_len);
1990                 error = (ETIMEDOUT);
1991         }
1992
1993         /*
1994          * Clear any pending interrupts.  Block interrupts so our
1995          * interrupt handler is not re-entered.
1996          */
1997         crit_enter();
1998         bt_intr(bt);
1999         crit_exit();
2000         
2001         if (error != 0)
2002                 return (error);
2003
2004         /*
2005          * If the command was rejected by the controller, tell the caller.
2006          */
2007         if ((saved_status & CMD_INVALID) != 0) {
2008                 /*
2009                  * Some early adapters may not recover properly from
2010                  * an invalid command.  If it appears that the controller
2011                  * has wedged (i.e. status was not cleared by our interrupt
2012                  * reset above), perform a soft reset.
2013                  */
2014                 if (bootverbose)
2015                         printf("%s: Invalid Command 0x%x\n", bt_name(bt), 
2016                                 opcode);
2017                 DELAY(1000);
2018                 status = bt_inb(bt, STATUS_REG);
2019                 if ((status & (CMD_INVALID|STATUS_REG_RSVD|DATAIN_REG_READY|
2020                               CMD_REG_BUSY|DIAG_FAIL|DIAG_ACTIVE)) != 0
2021                  || (status & (HA_READY|INIT_REQUIRED))
2022                   != (HA_READY|INIT_REQUIRED)) {
2023                         btreset(bt, /*hard_reset*/FALSE);
2024                 }
2025                 return (EINVAL);
2026         }
2027
2028         if (param_len > 0) {
2029                 /* The controller did not accept the full argument list */
2030                 return (E2BIG);
2031         }
2032
2033         if (reply_len != reply_buf_size) {
2034                 /* Too much or too little data received */
2035                 return (EMSGSIZE);
2036         }
2037
2038         /* We were successful */
2039         return (0);
2040 }
2041
2042 static int
2043 btinitmboxes(struct bt_softc *bt) {
2044         init_32b_mbox_params_t init_mbox;
2045         int error;
2046
2047         bzero(bt->in_boxes, sizeof(bt_mbox_in_t) * bt->num_boxes);
2048         bzero(bt->out_boxes, sizeof(bt_mbox_out_t) * bt->num_boxes);
2049         bt->cur_inbox = bt->in_boxes;
2050         bt->last_inbox = bt->in_boxes + bt->num_boxes - 1;
2051         bt->cur_outbox = bt->out_boxes;
2052         bt->last_outbox = bt->out_boxes + bt->num_boxes - 1;
2053
2054         /* Tell the adapter about them */
2055         init_mbox.num_boxes = bt->num_boxes;
2056         init_mbox.base_addr[0] = bt->mailbox_physbase & 0xFF;
2057         init_mbox.base_addr[1] = (bt->mailbox_physbase >> 8) & 0xFF;
2058         init_mbox.base_addr[2] = (bt->mailbox_physbase >> 16) & 0xFF;
2059         init_mbox.base_addr[3] = (bt->mailbox_physbase >> 24) & 0xFF;
2060         error = bt_cmd(bt, BOP_INITIALIZE_32BMBOX, (u_int8_t *)&init_mbox,
2061                        /*parmlen*/sizeof(init_mbox), /*reply_buf*/NULL,
2062                        /*reply_len*/0, DEFAULT_CMD_TIMEOUT);
2063
2064         if (error != 0)
2065                 printf("btinitmboxes: Initialization command failed\n");
2066         else if (bt->strict_rr != 0) {
2067                 /*
2068                  * If the controller supports
2069                  * strict round robin mode,
2070                  * enable it
2071                  */
2072                 u_int8_t param;
2073
2074                 param = 0;
2075                 error = bt_cmd(bt, BOP_ENABLE_STRICT_RR, &param, 1,
2076                                /*reply_buf*/NULL, /*reply_len*/0,
2077                                DEFAULT_CMD_TIMEOUT);
2078
2079                 if (error != 0) {
2080                         printf("btinitmboxes: Unable to enable strict RR\n");
2081                         error = 0;
2082                 } else if (bootverbose) {
2083                         printf("%s: Using Strict Round Robin Mailbox Mode\n",
2084                                bt_name(bt));
2085                 }
2086         }
2087         
2088         return (error);
2089 }
2090
2091 /*
2092  * Update the XPT's idea of the negotiated transfer
2093  * parameters for a particular target.
2094  */
2095 static void
2096 btfetchtransinfo(struct bt_softc *bt, struct ccb_trans_settings* cts)
2097 {
2098         setup_data_t    setup_info;
2099         u_int           target;
2100         u_int           targ_offset;
2101         u_int           targ_mask;
2102         u_int           sync_period;
2103         int             error;
2104         u_int8_t        param;
2105         targ_syncinfo_t sync_info;
2106
2107         target = cts->ccb_h.target_id;
2108         targ_offset = (target & 0x7);
2109         targ_mask = (0x01 << targ_offset);
2110
2111         /*
2112          * Inquire Setup Information.  This command retreives the
2113          * Wide negotiation status for recent adapters as well as
2114          * the sync info for older models.
2115          */
2116         param = sizeof(setup_info);
2117         error = bt_cmd(bt, BOP_INQUIRE_SETUP_INFO, &param, /*paramlen*/1,
2118                        (u_int8_t*)&setup_info, sizeof(setup_info),
2119                        DEFAULT_CMD_TIMEOUT);
2120
2121         if (error != 0) {
2122                 printf("%s: btfetchtransinfo - Inquire Setup Info Failed %x\n",
2123                        bt_name(bt), error);
2124                 cts->valid = 0;
2125                 return;
2126         }
2127
2128         sync_info = (target < 8) ? setup_info.low_syncinfo[targ_offset]
2129                                  : setup_info.high_syncinfo[targ_offset];
2130
2131         if (sync_info.sync == 0)
2132                 cts->sync_offset = 0;
2133         else
2134                 cts->sync_offset = sync_info.offset;
2135
2136         cts->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
2137         if (strcmp(bt->firmware_ver, "5.06L") >= 0) {
2138                 u_int wide_active;
2139
2140                 wide_active =
2141                     (target < 8) ? (setup_info.low_wide_active & targ_mask)
2142                                  : (setup_info.high_wide_active & targ_mask);
2143
2144                 if (wide_active)
2145                         cts->bus_width = MSG_EXT_WDTR_BUS_16_BIT;
2146         } else if ((bt->wide_permitted & targ_mask) != 0) {
2147                 struct ccb_getdev cgd;
2148
2149                 /*
2150                  * Prior to rev 5.06L, wide status isn't provided,
2151                  * so we "guess" that wide transfers are in effect
2152                  * if the user settings allow for wide and the inquiry
2153                  * data for the device indicates that it can handle
2154                  * wide transfers.
2155                  */
2156                 xpt_setup_ccb(&cgd.ccb_h, cts->ccb_h.path, /*priority*/1);
2157                 cgd.ccb_h.func_code = XPT_GDEV_TYPE;
2158                 xpt_action((union ccb *)&cgd);
2159                 if ((cgd.ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP
2160                  && (cgd.inq_data.flags & SID_WBus16) != 0)
2161                         cts->bus_width = MSG_EXT_WDTR_BUS_16_BIT;
2162         }
2163
2164         if (bt->firmware_ver[0] >= '3') {
2165                 /*
2166                  * For adapters that can do fast or ultra speeds,
2167                  * use the more exact Target Sync Information command.
2168                  */
2169                 target_sync_info_data_t sync_info;
2170
2171                 param = sizeof(sync_info);
2172                 error = bt_cmd(bt, BOP_TARG_SYNC_INFO, &param, /*paramlen*/1,
2173                                (u_int8_t*)&sync_info, sizeof(sync_info),
2174                                DEFAULT_CMD_TIMEOUT);
2175                 
2176                 if (error != 0) {
2177                         printf("%s: btfetchtransinfo - Inquire Sync "
2178                                "Info Failed 0x%x\n", bt_name(bt), error);
2179                         cts->valid = 0;
2180                         return;
2181                 }
2182                 sync_period = sync_info.sync_rate[target] * 100;
2183         } else {
2184                 sync_period = 2000 + (500 * sync_info.period);
2185         }
2186
2187         /* Convert ns value to standard SCSI sync rate */
2188         if (cts->sync_offset != 0)
2189                 cts->sync_period = scsi_calc_syncparam(sync_period);
2190         else
2191                 cts->sync_period = 0;
2192         
2193         cts->valid = CCB_TRANS_SYNC_RATE_VALID
2194                    | CCB_TRANS_SYNC_OFFSET_VALID
2195                    | CCB_TRANS_BUS_WIDTH_VALID;
2196         xpt_async(AC_TRANSFER_NEG, cts->ccb_h.path, cts);
2197 }
2198
2199 static void
2200 btmapmboxes(void *arg, bus_dma_segment_t *segs, int nseg, int error)
2201 {
2202         struct bt_softc* bt;
2203
2204         bt = (struct bt_softc*)arg;
2205         bt->mailbox_physbase = segs->ds_addr;
2206 }
2207
2208 static void
2209 btmapccbs(void *arg, bus_dma_segment_t *segs, int nseg, int error)
2210 {
2211         struct bt_softc* bt;
2212
2213         bt = (struct bt_softc*)arg;
2214         bt->bt_ccb_physbase = segs->ds_addr;
2215 }
2216
2217 static void
2218 btmapsgs(void *arg, bus_dma_segment_t *segs, int nseg, int error)
2219 {
2220
2221         struct bt_softc* bt;
2222
2223         bt = (struct bt_softc*)arg;
2224         SLIST_FIRST(&bt->sg_maps)->sg_physaddr = segs->ds_addr;
2225 }
2226
2227 static void
2228 btpoll(struct cam_sim *sim)
2229 {
2230         bt_intr(cam_sim_softc(sim));
2231 }
2232
2233 void
2234 bttimeout(void *arg)
2235 {
2236         struct bt_ccb   *bccb;
2237         union  ccb      *ccb;
2238         struct bt_softc *bt;
2239
2240         bccb = (struct bt_ccb *)arg;
2241         ccb = bccb->ccb;
2242         bt = (struct bt_softc *)ccb->ccb_h.ccb_bt_ptr;
2243         xpt_print_path(ccb->ccb_h.path);
2244         printf("CCB %p - timed out\n", (void *)bccb);
2245
2246         crit_enter();
2247
2248         if ((bccb->flags & BCCB_ACTIVE) == 0) {
2249                 xpt_print_path(ccb->ccb_h.path);
2250                 printf("CCB %p - timed out CCB already completed\n",
2251                        (void *)bccb);
2252                 crit_exit();
2253                 return;
2254         }
2255
2256         /*
2257          * In order to simplify the recovery process, we ask the XPT
2258          * layer to halt the queue of new transactions and we traverse
2259          * the list of pending CCBs and remove their timeouts. This
2260          * means that the driver attempts to clear only one error
2261          * condition at a time.  In general, timeouts that occur
2262          * close together are related anyway, so there is no benefit
2263          * in attempting to handle errors in parrallel.  Timeouts will
2264          * be reinstated when the recovery process ends.
2265          */
2266         if ((bccb->flags & BCCB_DEVICE_RESET) == 0) {
2267                 struct ccb_hdr *ccb_h;
2268
2269                 if ((bccb->flags & BCCB_RELEASE_SIMQ) == 0) {
2270                         xpt_freeze_simq(bt->sim, /*count*/1);
2271                         bccb->flags |= BCCB_RELEASE_SIMQ;
2272                 }
2273
2274                 ccb_h = LIST_FIRST(&bt->pending_ccbs);
2275                 while (ccb_h != NULL) {
2276                         struct bt_ccb *pending_bccb;
2277
2278                         pending_bccb = (struct bt_ccb *)ccb_h->ccb_bccb_ptr;
2279                         callout_stop(&ccb_h->timeout_ch);
2280                         ccb_h = LIST_NEXT(ccb_h, sim_links.le);
2281                 }
2282         }
2283
2284         if ((bccb->flags & BCCB_DEVICE_RESET) != 0
2285          || bt->cur_outbox->action_code != BMBO_FREE
2286          || ((bccb->hccb.tag_enable == TRUE)
2287           && (bt->firmware_ver[0] < '5'))) {
2288                 /*
2289                  * Try a full host adapter/SCSI bus reset.
2290                  * We do this only if we have already attempted
2291                  * to clear the condition with a BDR, or we cannot
2292                  * attempt a BDR for lack of mailbox resources
2293                  * or because of faulty firmware.  It turns out
2294                  * that firmware versions prior to 5.xx treat BDRs
2295                  * as untagged commands that cannot be sent until
2296                  * all outstanding tagged commands have been processed.
2297                  * This makes it somewhat difficult to use a BDR to
2298                  * clear up a problem with an uncompleted tagged command.
2299                  */
2300                 ccb->ccb_h.status = CAM_CMD_TIMEOUT;
2301                 btreset(bt, /*hardreset*/TRUE);
2302                 printf("%s: No longer in timeout\n", bt_name(bt));
2303         } else {
2304                 /*    
2305                  * Send a Bus Device Reset message:
2306                  * The target that is holding up the bus may not
2307                  * be the same as the one that triggered this timeout
2308                  * (different commands have different timeout lengths),
2309                  * but we have no way of determining this from our
2310                  * timeout handler.  Our strategy here is to queue a
2311                  * BDR message to the target of the timed out command.
2312                  * If this fails, we'll get another timeout 2 seconds
2313                  * later which will attempt a bus reset.
2314                  */
2315                 bccb->flags |= BCCB_DEVICE_RESET;
2316                 callout_reset(&ccb->ccb_h.timeout_ch, 2 * hz, bttimeout, bccb);
2317
2318                 bt->recovery_bccb->hccb.opcode = INITIATOR_BUS_DEV_RESET;
2319
2320                 /* No Data Transfer */
2321                 bt->recovery_bccb->hccb.datain = TRUE;
2322                 bt->recovery_bccb->hccb.dataout = TRUE;
2323                 bt->recovery_bccb->hccb.btstat = 0;
2324                 bt->recovery_bccb->hccb.sdstat = 0;
2325                 bt->recovery_bccb->hccb.target_id = ccb->ccb_h.target_id;
2326
2327                 /* Tell the adapter about this command */
2328                 bt->cur_outbox->ccb_addr = btccbvtop(bt, bt->recovery_bccb);
2329                 bt->cur_outbox->action_code = BMBO_START;
2330                 bt_outb(bt, COMMAND_REG, BOP_START_MBOX);
2331                 btnextoutbox(bt);
2332         }
2333
2334         crit_exit();
2335 }
2336