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