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