Home | History | Annotate | Line # | Download | only in pci
twa.c revision 1.8
      1 /*	$NetBSD: twa.c,v 1.8 2006/07/29 00:13:57 wrstuden Exp $ */
      2 /*	$wasabi: twa.c,v 1.27 2006/07/28 18:17:21 wrstuden Exp $	*/
      3 
      4 /*-
      5  * Copyright (c) 2004 The NetBSD Foundation, Inc.
      6  * All rights reserved.
      7  *
      8  * This code is derived from software contributed to The NetBSD Foundation
      9  * by Jordan Rhody of Wasabi Systems, Inc.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  * 3. All advertising materials mentioning features or use of this software
     20  *    must display the following acknowledgement:
     21  *        This product includes software developed by the NetBSD
     22  *        Foundation, Inc. and its contributors.
     23  * 4. Neither the name of The NetBSD Foundation nor the names of its
     24  *    contributors may be used to endorse or promote products derived
     25  *    from this software without specific prior written permission.
     26  *
     27  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     29  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     30  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     31  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     37  * POSSIBILITY OF SUCH DAMAGE.
     38  */
     39 
     40 /*-
     41  * Copyright (c) 2003-04 3ware, Inc.
     42  * Copyright (c) 2000 Michael Smith
     43  * Copyright (c) 2000 BSDi
     44  * All rights reserved.
     45  *
     46  * Redistribution and use in source and binary forms, with or without
     47  * modification, are permitted provided that the following conditions
     48  * are met:
     49  * 1. Redistributions of source code must retain the above copyright
     50  *    notice, this list of conditions and the following disclaimer.
     51  * 2. Redistributions in binary form must reproduce the above copyright
     52  *    notice, this list of conditions and the following disclaimer in the
     53  *    documentation and/or other materials provided with the distribution.
     54  *
     55  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
     56  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     57  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     58  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     59  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     60  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     61  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     62  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     63  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     64  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     65  * SUCH DAMAGE.
     66  *
     67  *	$FreeBSD: src/sys/dev/twa/twa.c,v 1.2 2004/04/02 15:09:57 des Exp $
     68  */
     69 
     70 /*
     71  * 3ware driver for 9000 series storage controllers.
     72  *
     73  * Author: Vinod Kashyap
     74  */
     75 
     76 #include <sys/cdefs.h>
     77 __KERNEL_RCSID(0, "$NetBSD: twa.c,v 1.8 2006/07/29 00:13:57 wrstuden Exp $");
     78 
     79 #include <sys/param.h>
     80 #include <sys/systm.h>
     81 #include <sys/kernel.h>
     82 #include <sys/device.h>
     83 #include <sys/queue.h>
     84 #include <sys/proc.h>
     85 #include <sys/bswap.h>
     86 #include <sys/buf.h>
     87 #include <sys/bufq.h>
     88 #include <sys/endian.h>
     89 #include <sys/malloc.h>
     90 #include <sys/conf.h>
     91 #include <sys/disk.h>
     92 #include <sys/syslog.h>
     93 
     94 #include <uvm/uvm_extern.h>
     95 
     96 #include <machine/bus.h>
     97 
     98 #include <dev/pci/pcireg.h>
     99 #include <dev/pci/pcivar.h>
    100 #include <dev/pci/pcidevs.h>
    101 #include <dev/pci/twareg.h>
    102 #include <dev/pci/twavar.h>
    103 #include <dev/pci/twaio.h>
    104 
    105 #include <dev/scsipi/scsipi_all.h>
    106 #include <dev/scsipi/scsipi_disk.h>
    107 #include <dev/scsipi/scsipiconf.h>
    108 #include <dev/scsipi/scsi_spc.h>
    109 
    110 #include <dev/ldvar.h>
    111 
    112 #include "locators.h"
    113 
    114 #define	PCI_CBIO	0x10
    115 
    116 static int	twa_fetch_aen(struct twa_softc *);
    117 static void	twa_aen_callback(struct twa_request *);
    118 static int	twa_find_aen(struct twa_softc *sc, uint16_t);
    119 static uint16_t	twa_enqueue_aen(struct twa_softc *sc,
    120 			struct twa_command_header *);
    121 
    122 static void	twa_attach(struct device *, struct device *, void *);
    123 static void	twa_shutdown(void *);
    124 static int	twa_init_connection(struct twa_softc *, uint16_t, uint32_t,
    125 				    uint16_t, uint16_t, uint16_t, uint16_t, uint16_t *,
    126 					uint16_t *, uint16_t *, uint16_t *, uint32_t *);
    127 static int	twa_intr(void *);
    128 static int 	twa_match(struct device *, struct cfdata *, void *);
    129 static int	twa_reset(struct twa_softc *);
    130 
    131 static int	twa_print(void *, const char *);
    132 static int	twa_soft_reset(struct twa_softc *);
    133 
    134 static int	twa_check_ctlr_state(struct twa_softc *, uint32_t);
    135 static int	twa_get_param(struct twa_softc *, int, int, size_t,
    136 				void (* callback)(struct twa_request *),
    137 				struct twa_param_9k **);
    138 static int 	twa_set_param(struct twa_softc *, int, int, int, void *,
    139 				void (* callback)(struct twa_request *));
    140 static void	twa_describe_controller(struct twa_softc *);
    141 static int	twa_wait_status(struct twa_softc *, uint32_t, uint32_t);
    142 static int	twa_done(struct twa_softc *);
    143 #if 0
    144 static int	twa_flash_firmware(struct twa_softc *sc);
    145 static int	twa_hard_reset(struct twa_softc *sc);
    146 #endif
    147 
    148 extern struct	cfdriver twa_cd;
    149 extern uint32_t twa_fw_img_size;
    150 extern uint8_t	twa_fw_img[];
    151 
    152 CFATTACH_DECL(twa, sizeof(struct twa_softc),
    153     twa_match, twa_attach, NULL, NULL);
    154 
    155 /* AEN messages. */
    156 static const struct twa_message	twa_aen_table[] = {
    157 	{0x0000, "AEN queue empty"},
    158 	{0x0001, "Controller reset occurred"},
    159 	{0x0002, "Degraded unit detected"},
    160 	{0x0003, "Controller error occured"},
    161 	{0x0004, "Background rebuild failed"},
    162 	{0x0005, "Background rebuild done"},
    163 	{0x0006, "Incomplete unit detected"},
    164 	{0x0007, "Background initialize done"},
    165 	{0x0008, "Unclean shutdown detected"},
    166 	{0x0009, "Drive timeout detected"},
    167 	{0x000A, "Drive error detected"},
    168 	{0x000B, "Rebuild started"},
    169 	{0x000C, "Background initialize started"},
    170 	{0x000D, "Entire logical unit was deleted"},
    171 	{0x000E, "Background initialize failed"},
    172 	{0x000F, "SMART attribute exceeded threshold"},
    173 	{0x0010, "Power supply reported AC under range"},
    174 	{0x0011, "Power supply reported DC out of range"},
    175 	{0x0012, "Power supply reported a malfunction"},
    176 	{0x0013, "Power supply predicted malfunction"},
    177 	{0x0014, "Battery charge is below threshold"},
    178 	{0x0015, "Fan speed is below threshold"},
    179 	{0x0016, "Temperature sensor is above threshold"},
    180 	{0x0017, "Power supply was removed"},
    181 	{0x0018, "Power supply was inserted"},
    182 	{0x0019, "Drive was removed from a bay"},
    183 	{0x001A, "Drive was inserted into a bay"},
    184 	{0x001B, "Drive bay cover door was opened"},
    185 	{0x001C, "Drive bay cover door was closed"},
    186 	{0x001D, "Product case was opened"},
    187 	{0x0020, "Prepare for shutdown (power-off)"},
    188 	{0x0021, "Downgrade UDMA mode to lower speed"},
    189 	{0x0022, "Upgrade UDMA mode to higher speed"},
    190 	{0x0023, "Sector repair completed"},
    191 	{0x0024, "Sbuf memory test failed"},
    192 	{0x0025, "Error flushing cached write data to disk"},
    193 	{0x0026, "Drive reported data ECC error"},
    194 	{0x0027, "DCB has checksum error"},
    195 	{0x0028, "DCB version is unsupported"},
    196 	{0x0029, "Background verify started"},
    197 	{0x002A, "Background verify failed"},
    198 	{0x002B, "Background verify done"},
    199 	{0x002C, "Bad sector overwritten during rebuild"},
    200 	{0x002E, "Replace failed because replacement drive too small"},
    201 	{0x002F, "Verify failed because array was never initialized"},
    202 	{0x0030, "Unsupported ATA drive"},
    203 	{0x0031, "Synchronize host/controller time"},
    204 	{0x0032, "Spare capacity is inadequate for some units"},
    205 	{0x0033, "Background migration started"},
    206 	{0x0034, "Background migration failed"},
    207 	{0x0035, "Background migration done"},
    208 	{0x0036, "Verify detected and fixed data/parity mismatch"},
    209 	{0x0037, "SO-DIMM incompatible"},
    210 	{0x0038, "SO-DIMM not detected"},
    211 	{0x0039, "Corrected Sbuf ECC error"},
    212 	{0x003A, "Drive power on reset detected"},
    213 	{0x003B, "Background rebuild paused"},
    214 	{0x003C, "Background initialize paused"},
    215 	{0x003D, "Background verify paused"},
    216 	{0x003E, "Background migration paused"},
    217 	{0x003F, "Corrupt flash file system detected"},
    218 	{0x0040, "Flash file system repaired"},
    219 	{0x0041, "Unit number assignments were lost"},
    220 	{0x0042, "Error during read of primary DCB"},
    221 	{0x0043, "Latent error found in backup DCB"},
    222 	{0x0044, "Battery voltage is normal"},
    223 	{0x0045, "Battery voltage is low"},
    224 	{0x0046, "Battery voltage is high"},
    225 	{0x0047, "Battery voltage is too low"},
    226 	{0x0048, "Battery voltage is too high"},
    227 	{0x0049, "Battery temperature is normal"},
    228 	{0x004A, "Battery temperature is low"},
    229 	{0x004B, "Battery temperature is high"},
    230 	{0x004C, "Battery temperature is too low"},
    231 	{0x004D, "Battery temperature is too high"},
    232 	{0x004E, "Battery capacity test started"},
    233 	{0x004F, "Cache synchronization skipped"},
    234 	{0x0050, "Battery capacity test completed"},
    235 	{0x0051, "Battery health check started"},
    236 	{0x0052, "Battery health check completed"},
    237 	{0x0053, "Need to do a capacity test"},
    238 	{0x0054, "Charge termination voltage is at high level"},
    239 	{0x0055, "Battery charging started"},
    240 	{0x0056, "Battery charging completed"},
    241 	{0x0057, "Battery charging fault"},
    242 	{0x0058, "Battery capacity is below warning level"},
    243 	{0x0059, "Battery capacity is below error level"},
    244 	{0x005A, "Battery is present"},
    245 	{0x005B, "Battery is not present"},
    246 	{0x005C, "Battery is weak"},
    247 	{0x005D, "Battery health check failed"},
    248 	{0x005E, "Cache synchronized after power fail"},
    249 	{0x005F, "Cache synchronization failed; some data lost"},
    250 	{0x0060, "Bad cache meta data checksum"},
    251 	{0x0061, "Bad cache meta data signature"},
    252 	{0x0062, "Cache meta data restore failed"},
    253 	{0x0063, "BBU not found after power fail"},
    254 	{0x00FC, "Recovered/finished array membership update"},
    255 	{0x00FD, "Handler lockup"},
    256 	{0x00FE, "Retrying PCI transfer"},
    257 	{0x00FF, "AEN queue is full"},
    258 	{0xFFFFFFFF, (char *)NULL}
    259 };
    260 
    261 /* AEN severity table. */
    262 static const char	*twa_aen_severity_table[] = {
    263 	"None",
    264 	"ERROR",
    265 	"WARNING",
    266 	"INFO",
    267 	"DEBUG",
    268 	(char *)NULL
    269 };
    270 
    271 /* Error messages. */
    272 static const struct twa_message	twa_error_table[] = {
    273 	{0x0100, "SGL entry contains zero data"},
    274 	{0x0101, "Invalid command opcode"},
    275 	{0x0102, "SGL entry has unaligned address"},
    276 	{0x0103, "SGL size does not match command"},
    277 	{0x0104, "SGL entry has illegal length"},
    278 	{0x0105, "Command packet is not aligned"},
    279 	{0x0106, "Invalid request ID"},
    280 	{0x0107, "Duplicate request ID"},
    281 	{0x0108, "ID not locked"},
    282 	{0x0109, "LBA out of range"},
    283 	{0x010A, "Logical unit not supported"},
    284 	{0x010B, "Parameter table does not exist"},
    285 	{0x010C, "Parameter index does not exist"},
    286 	{0x010D, "Invalid field in CDB"},
    287 	{0x010E, "Specified port has invalid drive"},
    288 	{0x010F, "Parameter item size mismatch"},
    289 	{0x0110, "Failed memory allocation"},
    290 	{0x0111, "Memory request too large"},
    291 	{0x0112, "Out of memory segments"},
    292 	{0x0113, "Invalid address to deallocate"},
    293 	{0x0114, "Out of memory"},
    294 	{0x0115, "Out of heap"},
    295 	{0x0120, "Double degrade"},
    296 	{0x0121, "Drive not degraded"},
    297 	{0x0122, "Reconstruct error"},
    298 	{0x0123, "Replace not accepted"},
    299 	{0x0124, "Replace drive capacity too small"},
    300 	{0x0125, "Sector count not allowed"},
    301 	{0x0126, "No spares left"},
    302 	{0x0127, "Reconstruct error"},
    303 	{0x0128, "Unit is offline"},
    304 	{0x0129, "Cannot update status to DCB"},
    305 	{0x0130, "Invalid stripe handle"},
    306 	{0x0131, "Handle that was not locked"},
    307 	{0x0132, "Handle that was not empy"},
    308 	{0x0133, "Handle has different owner"},
    309 	{0x0140, "IPR has parent"},
    310 	{0x0150, "Illegal Pbuf address alignment"},
    311 	{0x0151, "Illegal Pbuf transfer length"},
    312 	{0x0152, "Illegal Sbuf address alignment"},
    313 	{0x0153, "Illegal Sbuf transfer length"},
    314 	{0x0160, "Command packet too large"},
    315 	{0x0161, "SGL exceeds maximum length"},
    316 	{0x0162, "SGL has too many entries"},
    317 	{0x0170, "Insufficient resources for rebuilder"},
    318 	{0x0171, "Verify error (data != parity)"},
    319 	{0x0180, "Requested segment not in directory of this DCB"},
    320 	{0x0181, "DCB segment has unsupported version"},
    321 	{0x0182, "DCB segment has checksum error"},
    322 	{0x0183, "DCB support (settings) segment invalid"},
    323 	{0x0184, "DCB UDB (unit descriptor block) segment invalid"},
    324 	{0x0185, "DCB GUID (globally unique identifier) segment invalid"},
    325 	{0x01A0, "Could not clear Sbuf"},
    326 	{0x01C0, "Flash identify failed"},
    327 	{0x01C1, "Flash out of bounds"},
    328 	{0x01C2, "Flash verify error"},
    329 	{0x01C3, "Flash file object not found"},
    330 	{0x01C4, "Flash file already present"},
    331 	{0x01C5, "Flash file system full"},
    332 	{0x01C6, "Flash file not present"},
    333 	{0x01C7, "Flash file size error"},
    334 	{0x01C8, "Bad flash file checksum"},
    335 	{0x01CA, "Corrupt flash file system detected"},
    336 	{0x01D0, "Invalid field in parameter list"},
    337 	{0x01D1, "Parameter list length error"},
    338 	{0x01D2, "Parameter item is not changeable"},
    339 	{0x01D3, "Parameter item is not saveable"},
    340 	{0x0200, "UDMA CRC error"},
    341 	{0x0201, "Internal CRC error"},
    342 	{0x0202, "Data ECC error"},
    343 	{0x0203, "ADP level 1 error"},
    344 	{0x0204, "Port timeout"},
    345 	{0x0205, "Drive power on reset"},
    346 	{0x0206, "ADP level 2 error"},
    347 	{0x0207, "Soft reset failed"},
    348 	{0x0208, "Drive not ready"},
    349 	{0x0209, "Unclassified port error"},
    350 	{0x020A, "Drive aborted command"},
    351 	{0x0210, "Internal CRC error"},
    352 	{0x0211, "Host PCI bus abort"},
    353 	{0x0212, "Host PCI parity error"},
    354 	{0x0213, "Port handler error"},
    355 	{0x0214, "Token interrupt count error"},
    356 	{0x0215, "Timeout waiting for PCI transfer"},
    357 	{0x0216, "Corrected buffer ECC"},
    358 	{0x0217, "Uncorrected buffer ECC"},
    359 	{0x0230, "Unsupported command during flash recovery"},
    360 	{0x0231, "Next image buffer expected"},
    361 	{0x0232, "Binary image architecture incompatible"},
    362 	{0x0233, "Binary image has no signature"},
    363 	{0x0234, "Binary image has bad checksum"},
    364 	{0x0235, "Image downloaded overflowed buffer"},
    365 	{0x0240, "I2C device not found"},
    366 	{0x0241, "I2C transaction aborted"},
    367 	{0x0242, "SO-DIMM parameter(s) incompatible using defaults"},
    368 	{0x0243, "SO-DIMM unsupported"},
    369 	{0x0248, "SPI transfer status error"},
    370 	{0x0249, "SPI transfer timeout error"},
    371 	{0x0250, "Invalid unit descriptor size in CreateUnit"},
    372 	{0x0251, "Unit descriptor size exceeds data buffer in CreateUnit"},
    373 	{0x0252, "Invalid value in CreateUnit descriptor"},
    374 	{0x0253, "Inadequate disk space to support descriptor in CreateUnit"},
    375 	{0x0254, "Unable to create data channel for this unit descriptor"},
    376 	{0x0255, "CreateUnit descriptor specifies a drive already in use"},
    377        {0x0256, "Unable to write configuration to all disks during CreateUnit"},
    378 	{0x0257, "CreateUnit does not support this descriptor version"},
    379 	{0x0258, "Invalid subunit for RAID 0 or 5 in CreateUnit"},
    380 	{0x0259, "Too many descriptors in CreateUnit"},
    381 	{0x025A, "Invalid configuration specified in CreateUnit descriptor"},
    382 	{0x025B, "Invalid LBA offset specified in CreateUnit descriptor"},
    383 	{0x025C, "Invalid stripelet size specified in CreateUnit descriptor"},
    384 	{0x0260, "SMART attribute exceeded threshold"},
    385 	{0xFFFFFFFF, (char *)NULL}
    386 };
    387 
    388 struct twa_pci_identity {
    389 	uint32_t	vendor_id;
    390 	uint32_t	product_id;
    391 	const char	*name;
    392 };
    393 
    394 static const struct twa_pci_identity pci_twa_products[] = {
    395 	{ PCI_VENDOR_3WARE,
    396 	  PCI_PRODUCT_3WARE_9000,
    397 	  "3ware 9000 series",
    398 	},
    399 	{ PCI_VENDOR_3WARE,
    400 	  PCI_PRODUCT_3WARE_9550,
    401 	  "3ware 9550SX series",
    402 	},
    403 	{ 0,
    404 	  0,
    405 	  NULL,
    406 	},
    407 };
    408 
    409 
    410 static inline void
    411 twa_outl(struct twa_softc *sc, int off, uint32_t val)
    412 {
    413 
    414 	bus_space_write_4(sc->twa_bus_iot, sc->twa_bus_ioh, off, val);
    415 	bus_space_barrier(sc->twa_bus_iot, sc->twa_bus_ioh, off, 4,
    416 	    BUS_SPACE_BARRIER_WRITE);
    417 }
    418 
    419 static inline uint32_t	twa_inl(struct twa_softc *sc, int off)
    420 {
    421 
    422 	bus_space_barrier(sc->twa_bus_iot, sc->twa_bus_ioh, off, 4,
    423 	    BUS_SPACE_BARRIER_WRITE | BUS_SPACE_BARRIER_READ);
    424 	return (bus_space_read_4(sc->twa_bus_iot, sc->twa_bus_ioh, off));
    425 }
    426 
    427 void
    428 twa_request_wait_handler(struct twa_request *tr)
    429 {
    430 
    431 	wakeup(tr);
    432 }
    433 
    434 static int
    435 twa_match(struct device *parent, struct cfdata *cfdata, void *aux)
    436 {
    437 	int i;
    438 	struct pci_attach_args *pa = aux;
    439 	const struct twa_pci_identity *entry = 0;
    440 
    441 	if (PCI_VENDOR(pa->pa_id) == PCI_VENDOR_3WARE) {
    442 		for (i = 0; (pci_twa_products[i].product_id); i++) {
    443 			entry = &pci_twa_products[i];
    444 			if (entry->product_id == PCI_PRODUCT(pa->pa_id)) {
    445 				aprint_normal("%s: (rev. 0x%02x)\n",
    446 				    entry->name, PCI_REVISION(pa->pa_class));
    447 				return (1);
    448 			}
    449 		}
    450 	}
    451 	return (0);
    452 }
    453 
    454 static const char *
    455 twa_find_msg_string(const struct twa_message *table, uint16_t code)
    456 {
    457 	int	i;
    458 
    459 	for (i = 0; table[i].message != NULL; i++)
    460 		if (table[i].code == code)
    461 			return(table[i].message);
    462 
    463 	return(table[i].message);
    464 }
    465 
    466 void
    467 twa_release_request(struct twa_request *tr)
    468 {
    469 	int s;
    470 	struct twa_softc *sc;
    471 
    472 	sc = tr->tr_sc;
    473 
    474 	if ((tr->tr_flags & TWA_CMD_AEN) == 0) {
    475 		s = splbio();
    476 		TAILQ_INSERT_TAIL(&tr->tr_sc->twa_free, tr, tr_link);
    477 		splx(s);
    478 		if (__predict_false((tr->tr_sc->twa_sc_flags &
    479 		    TWA_STATE_REQUEST_WAIT) != 0)) {
    480 			tr->tr_sc->twa_sc_flags &= ~TWA_STATE_REQUEST_WAIT;
    481 			wakeup(&sc->twa_free);
    482 		}
    483 	} else
    484 		tr->tr_flags &= ~TWA_CMD_AEN_BUSY;
    485 }
    486 
    487 static void
    488 twa_unmap_request(struct twa_request *tr)
    489 {
    490 	struct twa_softc	*sc = tr->tr_sc;
    491 	uint8_t			cmd_status;
    492 
    493 	/* If the command involved data, unmap that too. */
    494 	if (tr->tr_data != NULL) {
    495 		if (tr->tr_cmd_pkt_type & TWA_CMD_PKT_TYPE_9K)
    496 			cmd_status = tr->tr_command->command.cmd_pkt_9k.status;
    497 		else
    498 			cmd_status =
    499 			      tr->tr_command->command.cmd_pkt_7k.generic.status;
    500 
    501 		if (tr->tr_flags & TWA_CMD_DATA_OUT) {
    502 			bus_dmamap_sync(tr->tr_sc->twa_dma_tag, tr->tr_dma_map,
    503 				0, tr->tr_length, BUS_DMASYNC_POSTREAD);
    504 			/*
    505 			 * If we are using a bounce buffer, and we are reading
    506 			 * data, copy the real data in.
    507 			 */
    508 			if (tr->tr_flags & TWA_CMD_DATA_COPY_NEEDED)
    509 				if (cmd_status == 0)
    510 					memcpy(tr->tr_real_data, tr->tr_data,
    511 						tr->tr_real_length);
    512 		}
    513 		if (tr->tr_flags & TWA_CMD_DATA_IN)
    514 			bus_dmamap_sync(tr->tr_sc->twa_dma_tag, tr->tr_dma_map,
    515 				0, tr->tr_length, BUS_DMASYNC_POSTWRITE);
    516 
    517 		bus_dmamap_unload(sc->twa_dma_tag, tr->tr_dma_map);
    518 	}
    519 
    520 	/* Free alignment buffer if it was used. */
    521 	if (tr->tr_flags & TWA_CMD_DATA_COPY_NEEDED) {
    522 		uvm_km_free(kmem_map, (vaddr_t)tr->tr_data,
    523 		    tr->tr_length, UVM_KMF_WIRED);
    524 		tr->tr_data = tr->tr_real_data;
    525 		tr->tr_length = tr->tr_real_length;
    526 	}
    527 }
    528 
    529 /*
    530  * Function name:	twa_wait_request
    531  * Description:		Sends down a firmware cmd, and waits for the completion,
    532  *			but NOT in a tight loop.
    533  *
    534  * Input:		tr	-- ptr to request pkt
    535  *			timeout -- max # of seconds to wait before giving up
    536  * Output:		None
    537  * Return value:	0	-- success
    538  *			non-zero-- failure
    539  */
    540 static int
    541 twa_wait_request(struct twa_request *tr, uint32_t timeout)
    542 {
    543 	time_t	end_time;
    544 	struct timeval	t1;
    545 	int	s, rv;
    546 
    547 	tr->tr_flags |= TWA_CMD_SLEEP_ON_REQUEST;
    548 	tr->tr_callback = twa_request_wait_handler;
    549 	tr->tr_status = TWA_CMD_BUSY;
    550 
    551 	rv = twa_map_request(tr);
    552 
    553 	if (rv != 0)
    554 		return (rv);
    555 
    556 	microtime(&t1);
    557 	end_time = t1.tv_usec +
    558 		(timeout * 1000 * 100);
    559 
    560 	while (tr->tr_status != TWA_CMD_COMPLETE) {
    561 		rv = tr->tr_error;
    562 		if (rv != 0)
    563 			return(rv);
    564 		if ((rv = tsleep(tr, PRIBIO, "twawait", timeout * hz)) == 0)
    565 			break;
    566 
    567 		if (rv == EWOULDBLOCK) {
    568 			/*
    569 			 * We will reset the controller only if the request has
    570 			 * already been submitted, so as to not lose the
    571 			 * request packet.  If a busy request timed out, the
    572 			 * reset will take care of freeing resources.  If a
    573 			 * pending request timed out, we will free resources
    574 			 * for that request, right here.  So, the caller is
    575 			 * expected to NOT cleanup when ETIMEDOUT is returned.
    576 			 */
    577 			if (tr->tr_status == TWA_CMD_BUSY)
    578 				twa_reset(tr->tr_sc);
    579 			else {
    580 				/* Request was never submitted.  Clean up. */
    581 				s = splbio();
    582 				TAILQ_REMOVE(&tr->tr_sc->twa_pending, tr,
    583 				    tr_link);
    584 				splx(s);
    585 
    586 				twa_unmap_request(tr);
    587 				if (tr->tr_data)
    588 					free(tr->tr_data, M_DEVBUF);
    589 
    590 				twa_release_request(tr);
    591 			}
    592 			return(ETIMEDOUT);
    593 		}
    594 		/*
    595 		 * Either the request got completed, or we were woken up by a
    596 		 * signal. Calculate the new timeout, in case it was the
    597 		 * latter.
    598 		 */
    599 		microtime(&t1);
    600 
    601 		timeout = (end_time - t1.tv_usec) / (1000 * 100);
    602 	}
    603 	return(rv);
    604 }
    605 
    606 /*
    607  * Function name:	twa_immediate_request
    608  * Description:		Sends down a firmware cmd, and waits for the completion
    609  *			in a tight loop.
    610  *
    611  * Input:		tr	-- ptr to request pkt
    612  *			timeout -- max # of seconds to wait before giving up
    613  * Output:		None
    614  * Return value:	0	-- success
    615  *			non-zero-- failure
    616  */
    617 static int
    618 twa_immediate_request(struct twa_request *tr, uint32_t timeout)
    619 {
    620 	struct timeval t1;
    621 	int	s = 0, rv = 0;
    622 
    623 	rv = twa_map_request(tr);
    624 
    625 	if (rv != 0)
    626 		return(rv);
    627 
    628 	timeout = (timeout * 10000 * 10);
    629 
    630 	microtime(&t1);
    631 
    632 	timeout += t1.tv_usec;
    633 
    634 	do {
    635 		rv = tr->tr_error;
    636 		if (rv != 0)
    637 			return(rv);
    638 		s = splbio();
    639 		twa_done(tr->tr_sc);
    640 		splx(s);
    641 		if (tr->tr_status == TWA_CMD_COMPLETE)
    642 			return(rv);
    643 		microtime(&t1);
    644 	} while (t1.tv_usec <= timeout);
    645 
    646 	/*
    647 	 * We will reset the controller only if the request has
    648 	 * already been submitted, so as to not lose the
    649 	 * request packet.  If a busy request timed out, the
    650 	 * reset will take care of freeing resources.  If a
    651 	 * pending request timed out, we will free resources
    652 	 * for that request, right here.  So, the caller is
    653 	 * expected to NOT cleanup when ETIMEDOUT is returned.
    654 	 */
    655 	rv = ETIMEDOUT;
    656 
    657 	if (tr->tr_status == TWA_CMD_BUSY)
    658 		twa_reset(tr->tr_sc);
    659 	else {
    660 		/* Request was never submitted.  Clean up. */
    661 		s = splbio();
    662 		TAILQ_REMOVE(&tr->tr_sc->twa_pending, tr, tr_link);
    663 		splx(s);
    664 		twa_unmap_request(tr);
    665 		if (tr->tr_data)
    666 			free(tr->tr_data, M_DEVBUF);
    667 
    668 		twa_release_request(tr);
    669 	}
    670 	return (rv);
    671 }
    672 
    673 static int
    674 twa_inquiry(struct twa_request *tr, int lunid)
    675 {
    676 	int error;
    677 	struct twa_command_9k *tr_9k_cmd;
    678 
    679 	if (tr->tr_data == NULL)
    680 		return (ENOMEM);
    681 
    682 	memset(tr->tr_data, 0, TWA_SECTOR_SIZE);
    683 
    684 	tr->tr_length = TWA_SECTOR_SIZE;
    685 	tr->tr_cmd_pkt_type = TWA_CMD_PKT_TYPE_9K;
    686 	tr->tr_flags |= TWA_CMD_DATA_IN;
    687 
    688 	tr_9k_cmd = &tr->tr_command->command.cmd_pkt_9k;
    689 
    690 	tr_9k_cmd->command.opcode = TWA_OP_EXECUTE_SCSI_COMMAND;
    691 	tr_9k_cmd->unit = lunid;
    692 	tr_9k_cmd->request_id = tr->tr_request_id;
    693 	tr_9k_cmd->status = 0;
    694 	tr_9k_cmd->sgl_offset = 16;
    695 	tr_9k_cmd->sgl_entries = 1;
    696 	/* create the CDB here */
    697 	tr_9k_cmd->cdb[0] = INQUIRY;
    698 	tr_9k_cmd->cdb[1] = ((lunid << 5) & 0x0e);
    699 	tr_9k_cmd->cdb[4] = 255;
    700 
    701 	/* XXXX setup page data no lun device
    702 	 * it seems 9000 series does not indicate
    703 	 * NOTPRESENT - need more investigation
    704 	 */
    705 	((struct scsipi_inquiry_data *)tr->tr_data)->device =
    706 		SID_QUAL_LU_NOTPRESENT;
    707 
    708 	error = twa_immediate_request(tr, TWA_REQUEST_TIMEOUT_PERIOD);
    709 
    710 	if (error != 0)
    711 		return (error);
    712 
    713 	if (((struct scsipi_inquiry_data *)tr->tr_data)->device ==
    714 		SID_QUAL_LU_NOTPRESENT)
    715 		error = 1;
    716 
    717 	return (error);
    718 }
    719 
    720 static int
    721 twa_print_inquiry_data(struct twa_softc *sc, struct scsipi_inquiry_data *scsipi)
    722 {
    723 
    724     printf("%s: %s\n", sc->twa_dv.dv_xname, scsipi->vendor);
    725 
    726     return (1);
    727 }
    728 
    729 
    730 static uint64_t
    731 twa_read_capacity(struct twa_request *tr, int lunid)
    732 {
    733 	int error;
    734 	struct twa_command_9k *tr_9k_cmd;
    735 	uint64_t array_size = 0LL;
    736 
    737 	if (tr->tr_data == NULL)
    738 		return (ENOMEM);
    739 
    740 	memset(tr->tr_data, 0, TWA_SECTOR_SIZE);
    741 
    742 	tr->tr_length = TWA_SECTOR_SIZE;
    743 	tr->tr_cmd_pkt_type = TWA_CMD_PKT_TYPE_9K;
    744 	tr->tr_flags |= TWA_CMD_DATA_OUT;
    745 
    746 	tr_9k_cmd = &tr->tr_command->command.cmd_pkt_9k;
    747 
    748 	tr_9k_cmd->command.opcode = TWA_OP_EXECUTE_SCSI_COMMAND;
    749 	tr_9k_cmd->unit = lunid;
    750 	tr_9k_cmd->request_id = tr->tr_request_id;
    751 	tr_9k_cmd->status = 0;
    752 	tr_9k_cmd->sgl_offset = 16;
    753 	tr_9k_cmd->sgl_entries = 1;
    754 	/* create the CDB here */
    755 	tr_9k_cmd->cdb[0] = READ_CAPACITY_16;
    756 	tr_9k_cmd->cdb[1] = ((lunid << 5) & 0x0e) | SRC16_SERVICE_ACTION;
    757 
    758 	error = twa_immediate_request(tr, TWA_REQUEST_TIMEOUT_PERIOD);
    759 
    760 	if (error == 0) {
    761 #if BYTE_ORDER == BIG_ENDIAN
    762 		array_size = bswap64(_8btol(
    763 		    ((struct scsipi_read_capacity_16_data *)tr->tr_data->addr) + 1);
    764 #else
    765 		array_size = _8btol(((struct scsipi_read_capacity_16_data *)
    766 				tr->tr_data)->addr) + 1;
    767 #endif
    768 	}
    769 	return (array_size);
    770 }
    771 
    772 static int
    773 twa_request_sense(struct twa_request *tr, int lunid)
    774 {
    775 	int error = 1;
    776 	struct twa_command_9k *tr_9k_cmd;
    777 
    778 	if (tr->tr_data == NULL)
    779 		return (error);
    780 
    781 	memset(tr->tr_data, 0, TWA_SECTOR_SIZE);
    782 
    783 	tr->tr_length = TWA_SECTOR_SIZE;
    784 	tr->tr_cmd_pkt_type = TWA_CMD_PKT_TYPE_9K;
    785 	tr->tr_flags |= TWA_CMD_DATA_OUT;
    786 
    787 	tr_9k_cmd = &tr->tr_command->command.cmd_pkt_9k;
    788 
    789 	tr_9k_cmd->command.opcode = TWA_OP_EXECUTE_SCSI_COMMAND;
    790 	tr_9k_cmd->unit = lunid;
    791 	tr_9k_cmd->request_id = tr->tr_request_id;
    792 	tr_9k_cmd->status = 0;
    793 	tr_9k_cmd->sgl_offset = 16;
    794 	tr_9k_cmd->sgl_entries = 1;
    795 	/* create the CDB here */
    796 	tr_9k_cmd->cdb[0] = SCSI_REQUEST_SENSE;
    797 	tr_9k_cmd->cdb[1] = ((lunid << 5) & 0x0e);
    798 	tr_9k_cmd->cdb[4] = 255;
    799 
    800 	/*XXX AEN notification called in interrupt context
    801 	 * so just queue the request. Return as quickly
    802 	 * as possible from interrupt
    803 	 */
    804 	if ((tr->tr_flags & TWA_CMD_AEN) != 0)
    805 		error = twa_map_request(tr);
    806  	else
    807 		error = twa_immediate_request(tr, TWA_REQUEST_TIMEOUT_PERIOD);
    808 
    809 	return (error);
    810 }
    811 
    812 static int
    813 twa_alloc_req_pkts(struct twa_softc *sc, int num_reqs)
    814 {
    815 	struct twa_request	*tr;
    816 	struct twa_command_packet *tc;
    817 	bus_dma_segment_t	seg;
    818 	size_t max_segs, max_xfer;
    819 	int	i, rv, rseg, size;
    820 
    821 	if ((sc->twa_req_buf = malloc(num_reqs * sizeof(struct twa_request),
    822 					M_DEVBUF, M_NOWAIT)) == NULL)
    823 		return(ENOMEM);
    824 
    825 	size = num_reqs * sizeof(struct twa_command_packet);
    826 
    827 	/* Allocate memory for cmd pkts. */
    828 	if ((rv = bus_dmamem_alloc(sc->twa_dma_tag,
    829 		size, PAGE_SIZE, 0, &seg,
    830 		1, &rseg, BUS_DMA_NOWAIT)) != 0){
    831 			aprint_error("%s: unable to allocate "
    832 				"command packets, rv = %d\n",
    833 				sc->twa_dv.dv_xname, rv);
    834 			return (ENOMEM);
    835 	}
    836 
    837 	if ((rv = bus_dmamem_map(sc->twa_dma_tag,
    838 		&seg, rseg, size, (caddr_t *)&sc->twa_cmds,
    839 		BUS_DMA_NOWAIT | BUS_DMA_COHERENT)) != 0) {
    840 			aprint_error("%s: unable to map commands, rv = %d\n",
    841 				sc->twa_dv.dv_xname, rv);
    842 			return (1);
    843 	}
    844 
    845 	if ((rv = bus_dmamap_create(sc->twa_dma_tag,
    846 		size, num_reqs, size,
    847 		0, BUS_DMA_NOWAIT, &sc->twa_cmd_map)) != 0) {
    848 			aprint_error("%s: unable to create command DMA map, "
    849 				"rv = %d\n", sc->twa_dv.dv_xname, rv);
    850 			return (ENOMEM);
    851 	}
    852 
    853 	if ((rv = bus_dmamap_load(sc->twa_dma_tag, sc->twa_cmd_map,
    854 		sc->twa_cmds, size, NULL,
    855 		BUS_DMA_NOWAIT)) != 0) {
    856 			aprint_error("%s: unable to load command DMA map, "
    857 				"rv = %d\n", sc->twa_dv.dv_xname, rv);
    858 			return (1);
    859 	}
    860 
    861 	if ((uintptr_t)sc->twa_cmds % TWA_ALIGNMENT) {
    862 		aprint_error("%s: DMA map memory not aligned on %d boundary\n",
    863 			sc->twa_dv.dv_xname, TWA_ALIGNMENT);
    864 
    865 		return (1);
    866 	}
    867 	tc = sc->twa_cmd_pkt_buf = (struct twa_command_packet *)sc->twa_cmds;
    868 	sc->twa_cmd_pkt_phys = sc->twa_cmd_map->dm_segs[0].ds_addr;
    869 
    870 	memset(sc->twa_req_buf, 0, num_reqs * sizeof(struct twa_request));
    871 	memset(sc->twa_cmd_pkt_buf, 0,
    872 		num_reqs * sizeof(struct twa_command_packet));
    873 
    874 	sc->sc_twa_request = sc->twa_req_buf;
    875 	max_segs = twa_get_maxsegs();
    876 	max_xfer = twa_get_maxxfer(max_segs);
    877 
    878 	for (i = 0; i < num_reqs; i++, tc++) {
    879 		tr = &(sc->twa_req_buf[i]);
    880 		tr->tr_command = tc;
    881 		tr->tr_cmd_phys = sc->twa_cmd_pkt_phys +
    882 				(i * sizeof(struct twa_command_packet));
    883 		tr->tr_request_id = i;
    884 		tr->tr_sc = sc;
    885 
    886 		/*
    887 		 * Create a map for data buffers.  maxsize (256 * 1024) used in
    888 		 * bus_dma_tag_create above should suffice the bounce page needs
    889 		 * for data buffers, since the max I/O size we support is 128KB.
    890 		 * If we supported I/O's bigger than 256KB, we would have to
    891 		 * create a second dma_tag, with the appropriate maxsize.
    892 		 */
    893 		if ((rv = bus_dmamap_create(sc->twa_dma_tag,
    894 			max_xfer, max_segs, 1, 0, BUS_DMA_NOWAIT,
    895 			&tr->tr_dma_map)) != 0) {
    896 				aprint_error("%s: unable to create command "
    897 					"DMA map, rv = %d\n",
    898 					sc->twa_dv.dv_xname, rv);
    899 				return (ENOMEM);
    900 		}
    901 		/* Insert request into the free queue. */
    902 		if (i != 0) {
    903 			sc->twa_lookup[i] = tr;
    904 			twa_release_request(tr);
    905 		} else
    906 			tr->tr_flags |= TWA_CMD_AEN;
    907 	}
    908 	return(0);
    909 }
    910 
    911 static void
    912 twa_recompute_openings(struct twa_softc *sc)
    913 {
    914 	struct twa_drive *td;
    915 	int unit;
    916 	int openings;
    917 
    918 	if (sc->sc_nunits != 0)
    919 		openings = ((TWA_Q_LENGTH / 2) / sc->sc_nunits);
    920 	else
    921 		openings = 0;
    922 	if (openings == sc->sc_openings)
    923 		return;
    924 	sc->sc_openings = openings;
    925 
    926 #ifdef TWA_DEBUG
    927 	printf("%s: %d array%s, %d openings per array\n",
    928 	    sc->sc_twa.dv_xname, sc->sc_nunits,
    929 	    sc->sc_nunits == 1 ? "" : "s", sc->sc_openings);
    930 #endif
    931 	for (unit = 0; unit < TWA_MAX_UNITS; unit++) {
    932 		td = &sc->sc_units[unit];
    933 		if (td->td_dev != NULL)
    934 			(*td->td_callbacks->tcb_openings)(td->td_dev,
    935 				sc->sc_openings);
    936 	}
    937 }
    938 
    939 static int
    940 twa_request_bus_scan(struct twa_softc *sc)
    941 {
    942 	struct twa_drive *td;
    943 	struct twa_request *tr;
    944 	struct twa_attach_args twaa;
    945 	int locs[TWACF_NLOCS];
    946 	int s, unit;
    947 
    948 	s = splbio();
    949 	for (unit = 0; unit < TWA_MAX_UNITS; unit++) {
    950 
    951 		if ((tr = twa_get_request(sc, 0)) == NULL) {
    952 			splx(s);
    953 			return (EIO);
    954 		}
    955 
    956 		tr->tr_cmd_pkt_type |= TWA_CMD_PKT_TYPE_INTERNAL;
    957 
    958 		tr->tr_data = malloc(TWA_SECTOR_SIZE, M_DEVBUF, M_NOWAIT);
    959 
    960 		if (tr->tr_data == NULL) {
    961 			twa_release_request(tr);
    962 			splx(s);
    963 			return (ENOMEM);
    964 		}
    965 		td = &sc->sc_units[unit];
    966 
    967 		if (twa_inquiry(tr, unit) == 0) {
    968 			if (td->td_dev == NULL) {
    969             			twa_print_inquiry_data(sc,
    970 				   ((struct scsipi_inquiry_data *)tr->tr_data));
    971 
    972 				sc->sc_nunits++;
    973 
    974 				sc->sc_units[unit].td_size =
    975 					twa_read_capacity(tr, unit);
    976 
    977 				twaa.twaa_unit = unit;
    978 
    979 				twa_recompute_openings(sc);
    980 
    981 				locs[TWACF_UNIT] = unit;
    982 
    983 				sc->sc_units[unit].td_dev =
    984 				    config_found_sm_loc(&sc->twa_dv, "twa",
    985 				    locs, &twaa, twa_print, config_stdsubmatch);
    986 			}
    987 		} else {
    988 			if (td->td_dev != NULL) {
    989 				sc->sc_nunits--;
    990 
    991 				(void) config_detach(td->td_dev, DETACH_FORCE);
    992 				td->td_dev = NULL;
    993 				td->td_size = 0;
    994 
    995 				twa_recompute_openings(sc);
    996 			}
    997 		}
    998 		free(tr->tr_data, M_DEVBUF);
    999 
   1000 		twa_release_request(tr);
   1001 	}
   1002 	splx(s);
   1003 
   1004 	return (0);
   1005 }
   1006 
   1007 
   1008 #ifdef	DIAGNOSTIC
   1009 static inline void
   1010 twa_check_busy_q(struct twa_request *tr)
   1011 {
   1012 	struct twa_request *rq;
   1013 	struct twa_softc *sc = tr->tr_sc;
   1014 
   1015 	TAILQ_FOREACH(rq, &sc->twa_busy, tr_link) {
   1016 		if (tr->tr_request_id == rq->tr_request_id) {
   1017 			panic("cannot submit same request more than once");
   1018 		} else if (tr->bp == rq->bp && tr->bp != 0) {
   1019 			/* XXX A check for 0 for the buf ptr is needed to
   1020 			 * guard against ioctl requests with a buf ptr of
   1021 			 * 0 and also aen notifications. Looking for
   1022 			 * external cmds only.
   1023 			 */
   1024 			panic("cannot submit same buf more than once");
   1025 		} else {
   1026 			/* Empty else statement */
   1027 		}
   1028 	}
   1029 }
   1030 #endif
   1031 
   1032 static int
   1033 twa_start(struct twa_request *tr)
   1034 {
   1035 	struct twa_softc	*sc = tr->tr_sc;
   1036 	uint32_t		status_reg;
   1037 	int			s;
   1038 	int			error;
   1039 
   1040 	s = splbio();
   1041 	/* Check to see if we can post a command. */
   1042 	status_reg = twa_inl(sc, TWA_STATUS_REGISTER_OFFSET);
   1043 	if ((error = twa_check_ctlr_state(sc, status_reg)))
   1044 		goto out;
   1045 
   1046 	if (status_reg & TWA_STATUS_COMMAND_QUEUE_FULL) {
   1047 			if (tr->tr_status != TWA_CMD_PENDING) {
   1048 				tr->tr_status = TWA_CMD_PENDING;
   1049 				TAILQ_INSERT_TAIL(&tr->tr_sc->twa_pending,
   1050 					tr, tr_link);
   1051 			}
   1052 			twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   1053 					TWA_CONTROL_UNMASK_COMMAND_INTERRUPT);
   1054 			error = EBUSY;
   1055 	} else {
   1056 	   	bus_dmamap_sync(sc->twa_dma_tag, sc->twa_cmd_map,
   1057 			(caddr_t)tr->tr_command - sc->twa_cmds,
   1058 			sizeof(struct twa_command_packet),
   1059 			BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
   1060 
   1061 		/* Cmd queue is not full.  Post the command. */
   1062 		TWA_WRITE_COMMAND_QUEUE(sc, tr->tr_cmd_phys +
   1063 			sizeof(struct twa_command_header));
   1064 
   1065 		/* Mark the request as currently being processed. */
   1066 		tr->tr_status = TWA_CMD_BUSY;
   1067 
   1068 #ifdef	DIAGNOSTIC
   1069 		twa_check_busy_q(tr);
   1070 #endif
   1071 
   1072 		/* Move the request into the busy queue. */
   1073 		TAILQ_INSERT_TAIL(&tr->tr_sc->twa_busy, tr, tr_link);
   1074 	}
   1075 out:
   1076 	splx(s);
   1077 	return(error);
   1078 }
   1079 
   1080 static int
   1081 twa_drain_response_queue(struct twa_softc *sc)
   1082 {
   1083 	union twa_response_queue	rq;
   1084 	uint32_t			status_reg;
   1085 
   1086 	for (;;) {
   1087 		status_reg = twa_inl(sc, TWA_STATUS_REGISTER_OFFSET);
   1088 		if (twa_check_ctlr_state(sc, status_reg))
   1089 			return(1);
   1090 		if (status_reg & TWA_STATUS_RESPONSE_QUEUE_EMPTY)
   1091 			return(0); /* no more response queue entries */
   1092 		rq = (union twa_response_queue)twa_inl(sc,
   1093 		    TWA_RESPONSE_QUEUE_OFFSET);
   1094 	}
   1095 }
   1096 
   1097 static void
   1098 twa_drain_busy_queue(struct twa_softc *sc)
   1099 {
   1100 	struct twa_request	*tr;
   1101 
   1102 	/* Walk the busy queue. */
   1103 
   1104 	while ((tr = TAILQ_FIRST(&sc->twa_busy)) != NULL) {
   1105 		TAILQ_REMOVE(&sc->twa_busy, tr, tr_link);
   1106 
   1107 		twa_unmap_request(tr);
   1108 		if ((tr->tr_cmd_pkt_type & TWA_CMD_PKT_TYPE_INTERNAL) ||
   1109 			(tr->tr_cmd_pkt_type & TWA_CMD_PKT_TYPE_IOCTL)) {
   1110 			/* It's an internal/ioctl request.  Simply free it. */
   1111 			if (tr->tr_data)
   1112 				free(tr->tr_data, M_DEVBUF);
   1113 			twa_release_request(tr);
   1114 		} else {
   1115 			/* It's a SCSI request.  Complete it. */
   1116 			tr->tr_command->command.cmd_pkt_9k.status = EIO;
   1117 			if (tr->tr_callback)
   1118 				tr->tr_callback(tr);
   1119 		}
   1120 	}
   1121 }
   1122 
   1123 static int
   1124 twa_drain_pending_queue(struct twa_softc *sc)
   1125 {
   1126 	struct twa_request	*tr;
   1127 	int			s, error = 0;
   1128 
   1129 	/*
   1130 	 * Pull requests off the pending queue, and submit them.
   1131 	 */
   1132 	s = splbio();
   1133 	while ((tr = TAILQ_FIRST(&sc->twa_pending)) != NULL) {
   1134 		TAILQ_REMOVE(&sc->twa_pending, tr, tr_link);
   1135 
   1136 		if ((error = twa_start(tr))) {
   1137 			if (error == EBUSY) {
   1138 				tr->tr_status = TWA_CMD_PENDING;
   1139 
   1140 				/* queue at the head */
   1141 				TAILQ_INSERT_HEAD(&tr->tr_sc->twa_pending,
   1142 					tr, tr_link);
   1143 				error = 0;
   1144 				break;
   1145 			} else {
   1146 				if (tr->tr_flags & TWA_CMD_SLEEP_ON_REQUEST) {
   1147 					tr->tr_error = error;
   1148 					tr->tr_callback(tr);
   1149 					error = EIO;
   1150 				}
   1151 			}
   1152 		}
   1153 	}
   1154 	splx(s);
   1155 
   1156 	return(error);
   1157 }
   1158 
   1159 static int
   1160 twa_drain_aen_queue(struct twa_softc *sc)
   1161 {
   1162 	int				s, error = 0;
   1163 	struct twa_request		*tr;
   1164 	struct twa_command_header	*cmd_hdr;
   1165 	struct timeval	t1;
   1166 	uint32_t		timeout;
   1167 
   1168 	for (;;) {
   1169 		if ((tr = twa_get_request(sc, 0)) == NULL) {
   1170 			error = EIO;
   1171 			break;
   1172 		}
   1173 		tr->tr_cmd_pkt_type |= TWA_CMD_PKT_TYPE_INTERNAL;
   1174 		tr->tr_callback = NULL;
   1175 
   1176 		tr->tr_data = malloc(TWA_SECTOR_SIZE, M_DEVBUF, M_NOWAIT);
   1177 
   1178 		if (tr->tr_data == NULL) {
   1179 			error = 1;
   1180 			goto out;
   1181 		}
   1182 
   1183 		if (twa_request_sense(tr, 0) != 0) {
   1184 			error = 1;
   1185 			break;
   1186 		}
   1187 
   1188 		timeout = (1000/*ms*/ * 100/*us*/ * TWA_REQUEST_TIMEOUT_PERIOD);
   1189 
   1190 		microtime(&t1);
   1191 
   1192 		timeout += t1.tv_usec;
   1193 
   1194 		do {
   1195 			s = splbio();
   1196 			twa_done(tr->tr_sc);
   1197 			splx(s);
   1198 			if (tr->tr_status != TWA_CMD_BUSY)
   1199 				break;
   1200 			microtime(&t1);
   1201 		} while (t1.tv_usec <= timeout);
   1202 
   1203 		if (tr->tr_status != TWA_CMD_COMPLETE) {
   1204 			error = ETIMEDOUT;
   1205 			break;
   1206 		}
   1207 
   1208 		if ((error = tr->tr_command->command.cmd_pkt_9k.status))
   1209 			break;
   1210 
   1211 		cmd_hdr = (struct twa_command_header *)(tr->tr_data);
   1212 		if ((cmd_hdr->status_block.error) /* aen_code */
   1213 				== TWA_AEN_QUEUE_EMPTY)
   1214 			break;
   1215 		(void)twa_enqueue_aen(sc, cmd_hdr);
   1216 
   1217 		free(tr->tr_data, M_DEVBUF);
   1218 		twa_release_request(tr);
   1219 	}
   1220 out:
   1221 	if (tr) {
   1222 		if (tr->tr_data)
   1223 			free(tr->tr_data, M_DEVBUF);
   1224 
   1225 		twa_release_request(tr);
   1226 	}
   1227 	return(error);
   1228 }
   1229 
   1230 
   1231 #ifdef		DIAGNOSTIC
   1232 static void
   1233 twa_check_response_q(struct twa_request *tr, int clear)
   1234 {
   1235 	int j;
   1236 	static int i = 0;
   1237 	static struct twa_request	*req = 0;
   1238 	static struct buf		*hist[255];
   1239 
   1240 
   1241 	if (clear) {
   1242 		i = 0;
   1243 		for (j = 0; j < 255; j++)
   1244 			hist[j] = 0;
   1245 		return;
   1246 	}
   1247 
   1248 	if (req == 0)
   1249 		req = tr;
   1250 
   1251 	if ((tr->tr_cmd_pkt_type & TWA_CMD_PKT_TYPE_EXTERNAL) != 0) {
   1252 		if (req->tr_request_id == tr->tr_request_id)
   1253 			panic("req id: %d on controller queue twice",
   1254 		    	    tr->tr_request_id);
   1255 
   1256 		for (j = 0; j < i; j++)
   1257 			if (tr->bp == hist[j])
   1258 				panic("req id: %d buf found twice",
   1259 		    	    	    tr->tr_request_id);
   1260 		}
   1261 	req = tr;
   1262 
   1263 	hist[i++] = req->bp;
   1264 }
   1265 #endif
   1266 
   1267 static int
   1268 twa_done(struct twa_softc *sc)
   1269 {
   1270 	union twa_response_queue	rq;
   1271 	struct twa_request		*tr;
   1272 	int				rv = 0;
   1273 	uint32_t			status_reg;
   1274 
   1275 	for (;;) {
   1276 		status_reg = twa_inl(sc, TWA_STATUS_REGISTER_OFFSET);
   1277 		if ((rv = twa_check_ctlr_state(sc, status_reg)))
   1278 			break;
   1279 		if (status_reg & TWA_STATUS_RESPONSE_QUEUE_EMPTY)
   1280 			break;
   1281 		/* Response queue is not empty. */
   1282 		rq = (union twa_response_queue)twa_inl(sc,
   1283 			TWA_RESPONSE_QUEUE_OFFSET);
   1284 		tr = sc->sc_twa_request + rq.u.response_id;
   1285 #ifdef		DIAGNOSTIC
   1286 		twa_check_response_q(tr, 0);
   1287 #endif
   1288 		/* Unmap the command packet, and any associated data buffer. */
   1289 		twa_unmap_request(tr);
   1290 
   1291 		tr->tr_status = TWA_CMD_COMPLETE;
   1292 		TAILQ_REMOVE(&tr->tr_sc->twa_busy, tr, tr_link);
   1293 
   1294 		if (tr->tr_callback)
   1295 			tr->tr_callback(tr);
   1296 	}
   1297 	(void)twa_drain_pending_queue(sc);
   1298 
   1299 #ifdef		DIAGNOSTIC
   1300 	twa_check_response_q(NULL, 1);
   1301 #endif
   1302 	return(rv);
   1303 }
   1304 
   1305 /*
   1306  * Function name:	twa_init_ctlr
   1307  * Description:		Establishes a logical connection with the controller.
   1308  *			If bundled with firmware, determines whether or not
   1309  *			to flash firmware, based on arch_id, fw SRL (Spec.
   1310  *			Revision Level), branch & build #'s.  Also determines
   1311  *			whether or not the driver is compatible with the
   1312  *			firmware on the controller, before proceeding to work
   1313  *			with it.
   1314  *
   1315  * Input:		sc	-- ptr to per ctlr structure
   1316  * Output:		None
   1317  * Return value:	0	-- success
   1318  *			non-zero-- failure
   1319  */
   1320 static int
   1321 twa_init_ctlr(struct twa_softc *sc)
   1322 {
   1323 	uint16_t	fw_on_ctlr_srl = 0;
   1324 	uint16_t	fw_on_ctlr_arch_id = 0;
   1325 	uint16_t	fw_on_ctlr_branch = 0;
   1326 	uint16_t	fw_on_ctlr_build = 0;
   1327 	uint32_t	init_connect_result = 0;
   1328 	int		error = 0;
   1329 #if 0
   1330 	int8_t		fw_flashed = FALSE;
   1331 	int8_t		fw_flash_failed = FALSE;
   1332 #endif
   1333 
   1334 	/* Wait for the controller to become ready. */
   1335 	if (twa_wait_status(sc, TWA_STATUS_MICROCONTROLLER_READY,
   1336 					TWA_REQUEST_TIMEOUT_PERIOD)) {
   1337 		return(ENXIO);
   1338 	}
   1339 	/* Drain the response queue. */
   1340 	if (twa_drain_response_queue(sc))
   1341 		return(1);
   1342 
   1343 	/* Establish a logical connection with the controller. */
   1344 	if ((error = twa_init_connection(sc, TWA_INIT_MESSAGE_CREDITS,
   1345 			TWA_EXTENDED_INIT_CONNECT, TWA_CURRENT_FW_SRL,
   1346 			TWA_9000_ARCH_ID, TWA_CURRENT_FW_BRANCH,
   1347 			TWA_CURRENT_FW_BUILD, &fw_on_ctlr_srl,
   1348 			&fw_on_ctlr_arch_id, &fw_on_ctlr_branch,
   1349 			&fw_on_ctlr_build, &init_connect_result))) {
   1350 		return(error);
   1351 	}
   1352 #if 0
   1353 	if ((init_connect_result & TWA_BUNDLED_FW_SAFE_TO_FLASH) &&
   1354 		(init_connect_result & TWA_CTLR_FW_RECOMMENDS_FLASH)) {
   1355 		/*
   1356 		 * The bundled firmware is safe to flash, and the firmware
   1357 		 * on the controller recommends a flash.  So, flash!
   1358 		 */
   1359 		printf("%s: flashing bundled firmware...\n",
   1360 		    sc->twa_dv.dv_xname);
   1361 
   1362 		if ((error = twa_flash_firmware(sc))) {
   1363 			fw_flash_failed = TRUE;
   1364 
   1365 			printf("%s: unable to flash bundled firmware.\n",
   1366 			    sc->twa_dv.dv_xname);
   1367 		} else {
   1368 			printf("%s: successfully flashed bundled firmware.\n",
   1369 				 sc->twa_dv.dv_xname);
   1370 			fw_flashed = TRUE;
   1371 		}
   1372 	}
   1373 	if (fw_flashed) {
   1374 		/* The firmware was flashed.  Have the new image loaded */
   1375 		error = twa_hard_reset(sc);
   1376 		if (error == 0)
   1377 			error = twa_init_ctlr(sc);
   1378 		/*
   1379 		 * If hard reset of controller failed, we need to return.
   1380 		 * Otherwise, the above recursive call to twa_init_ctlr will
   1381 		 * have completed the rest of the initialization (starting
   1382 		 * from twa_drain_aen_queue below).  Don't do it again.
   1383 		 * Just return.
   1384 		 */
   1385 		return(error);
   1386 	} else {
   1387 		/*
   1388 		 * Either we are not bundled with a firmware image, or
   1389 		 * the bundled firmware is not safe to flash,
   1390 		 * or flash failed for some reason.  See if we can at
   1391 		 * least work with the firmware on the controller in the
   1392 		 * current mode.
   1393 		 */
   1394 		if (init_connect_result & TWA_CTLR_FW_COMPATIBLE) {
   1395 			/* Yes, we can.  Make note of the operating mode. */
   1396 			sc->working_srl = TWA_CURRENT_FW_SRL;
   1397 			sc->working_branch = TWA_CURRENT_FW_BRANCH;
   1398 			sc->working_build = TWA_CURRENT_FW_BUILD;
   1399 		} else {
   1400 			/*
   1401 			 * No, we can't.  See if we can at least work with
   1402 			 * it in the base mode.  We should never come here
   1403 			 * if firmware has just been flashed.
   1404 			 */
   1405 			printf("%s: Driver/Firmware mismatch.  Negotiating "
   1406 			    "for base level.\n", sc->twa_dv.dv_xname);
   1407 			if ((error = twa_init_connection(sc,
   1408 			    TWA_INIT_MESSAGE_CREDITS,
   1409 			    TWA_EXTENDED_INIT_CONNECT, TWA_BASE_FW_SRL,
   1410 			    TWA_9000_ARCH_ID, TWA_BASE_FW_BRANCH,
   1411 			    TWA_BASE_FW_BUILD, &fw_on_ctlr_srl,
   1412 			    &fw_on_ctlr_arch_id, &fw_on_ctlr_branch,
   1413 			    &fw_on_ctlr_build, &init_connect_result))) {
   1414 				printf("%s: can't initialize connection in "
   1415 				    "base mode.\n", sc->twa_dv.dv_xname);
   1416 				return(error);
   1417 			}
   1418 			if (!(init_connect_result & TWA_CTLR_FW_COMPATIBLE)) {
   1419 				/*
   1420 				 * The firmware on the controller is not even
   1421 				 * compatible with our base mode.  We cannot
   1422 				 * work with it.  Bail...
   1423 				 */
   1424 				printf("Incompatible firmware on controller\n");
   1425 #ifdef TWA_FLASH_FIRMWARE
   1426 				if (fw_flash_failed)
   1427 					printf("...and could not flash bundled "
   1428 					    "firmware.\n");
   1429 				else
   1430 					printf("...and bundled firmware not "
   1431 					    "safe to flash.\n");
   1432 #endif /* TWA_FLASH_FIRMWARE */
   1433 				return(1);
   1434 			}
   1435 			/*
   1436 			 * We can work with this firmware, but only in
   1437 			 * base mode.
   1438 			 */
   1439 			sc->working_srl = TWA_BASE_FW_SRL;
   1440 			sc->working_branch = TWA_BASE_FW_BRANCH;
   1441 			sc->working_build = TWA_BASE_FW_BUILD;
   1442 			sc->twa_operating_mode = TWA_BASE_MODE;
   1443 		}
   1444 	}
   1445 #endif
   1446 	twa_drain_aen_queue(sc);
   1447 
   1448 	/* Set controller state to initialized. */
   1449 	sc->twa_state &= ~TWA_STATE_SHUTDOWN;
   1450 	return(0);
   1451 }
   1452 
   1453 static int
   1454 twa_setup(struct twa_softc *sc)
   1455 {
   1456 	struct tw_cl_event_packet *aen_queue;
   1457 	uint32_t		i = 0;
   1458 	int			error = 0;
   1459 
   1460 	/* Initialize request queues. */
   1461 	TAILQ_INIT(&sc->twa_free);
   1462 	TAILQ_INIT(&sc->twa_busy);
   1463 	TAILQ_INIT(&sc->twa_pending);
   1464 
   1465 	sc->sc_nunits = 0;
   1466 	sc->twa_sc_flags = 0;
   1467 
   1468 	if (twa_alloc_req_pkts(sc, TWA_Q_LENGTH)) {
   1469 
   1470 		return(ENOMEM);
   1471 	}
   1472 
   1473 	/* Allocate memory for the AEN queue. */
   1474 	if ((aen_queue = malloc(sizeof(struct tw_cl_event_packet) *
   1475 	    TWA_Q_LENGTH, M_DEVBUF, M_WAITOK)) == NULL) {
   1476 		/*
   1477 		 * This should not cause us to return error.  We will only be
   1478 		 * unable to support AEN's.  But then, we will have to check
   1479 		 * time and again to see if we can support AEN's, if we
   1480 		 * continue.  So, we will just return error.
   1481 		 */
   1482 		return (ENOMEM);
   1483 	}
   1484 	/* Initialize the aen queue. */
   1485 	memset(aen_queue, 0, sizeof(struct tw_cl_event_packet) * TWA_Q_LENGTH);
   1486 
   1487 	for (i = 0; i < TWA_Q_LENGTH; i++)
   1488 		sc->twa_aen_queue[i] = &(aen_queue[i]);
   1489 
   1490 	twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   1491 		TWA_CONTROL_DISABLE_INTERRUPTS);
   1492 
   1493 	/* Initialize the controller. */
   1494 	if ((error = twa_init_ctlr(sc))) {
   1495 		/* Soft reset the controller, and try one more time. */
   1496 
   1497 		printf("%s: controller initialization failed. "
   1498 		    "Retrying initialization\n", sc->twa_dv.dv_xname);
   1499 
   1500 		if ((error = twa_soft_reset(sc)) == 0)
   1501 			error = twa_init_ctlr(sc);
   1502 	}
   1503 
   1504 	twa_describe_controller(sc);
   1505 
   1506 	error = twa_request_bus_scan(sc);
   1507 
   1508 	twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   1509 		TWA_CONTROL_CLEAR_ATTENTION_INTERRUPT |
   1510 		TWA_CONTROL_UNMASK_RESPONSE_INTERRUPT |
   1511 		TWA_CONTROL_ENABLE_INTERRUPTS);
   1512 
   1513 	return (error);
   1514 }
   1515 
   1516 void *twa_sdh;
   1517 
   1518 static void
   1519 twa_attach(struct device *parent, struct device *self, void *aux)
   1520 {
   1521 	struct pci_attach_args *pa;
   1522 	struct twa_softc *sc;
   1523 	pci_chipset_tag_t pc;
   1524 	pcireg_t csr;
   1525 	pci_intr_handle_t ih;
   1526 	const char *intrstr;
   1527 
   1528 	sc = (struct twa_softc *)self;
   1529 
   1530 	pa = aux;
   1531 	pc = pa->pa_pc;
   1532 	sc->pc = pa->pa_pc;
   1533 	sc->tag = pa->pa_tag;
   1534 	sc->twa_dma_tag = pa->pa_dmat;
   1535 
   1536 	aprint_naive(": RAID controller\n");
   1537 	aprint_normal(": 3ware Apache\n");
   1538 
   1539 	if (PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_3WARE_9000) {
   1540 		if (pci_mapreg_map(pa, PCI_MAPREG_START, PCI_MAPREG_TYPE_IO, 0,
   1541 	    	    &sc->twa_bus_iot, &sc->twa_bus_ioh, NULL, NULL)) {
   1542 			aprint_error("%s: can't map i/o space\n",
   1543 			    sc->twa_dv.dv_xname);
   1544 			return;
   1545 		}
   1546 	} else if (PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_3WARE_9550) {
   1547 		if (pci_mapreg_map(pa, PCI_MAPREG_START + 0x08,
   1548 	    	    PCI_MAPREG_MEM_TYPE_64BIT, 0, &sc->twa_bus_iot,
   1549 		    &sc->twa_bus_ioh, NULL, NULL)) {
   1550 			aprint_error("%s: can't map mem space\n",
   1551 			    sc->twa_dv.dv_xname);
   1552 			return;
   1553 		}
   1554 	} else {
   1555 		aprint_error("%s: product id 0x%02x not recognized\n",
   1556 		    sc->twa_dv.dv_xname, PCI_PRODUCT(pa->pa_id));
   1557 		return;
   1558 	}
   1559 	/* Enable the device. */
   1560 	csr = pci_conf_read(pa->pa_pc, pa->pa_tag, PCI_COMMAND_STATUS_REG);
   1561 
   1562 	pci_conf_write(pa->pa_pc, pa->pa_tag, PCI_COMMAND_STATUS_REG,
   1563 	    csr | PCI_COMMAND_MASTER_ENABLE);
   1564 
   1565 	/* Map and establish the interrupt. */
   1566 	if (pci_intr_map(pa, &ih)) {
   1567 		aprint_error("%s: can't map interrupt\n", sc->twa_dv.dv_xname);
   1568 		return;
   1569 	}
   1570 	intrstr = pci_intr_string(pc, ih);
   1571 
   1572 	sc->twa_ih = pci_intr_establish(pc, ih, IPL_BIO, twa_intr, sc);
   1573 	if (sc->twa_ih == NULL) {
   1574 		aprint_error("%s: can't establish interrupt%s%s\n",
   1575 			sc->twa_dv.dv_xname,
   1576 			(intrstr) ? " at " : "",
   1577 			(intrstr) ? intrstr : "");
   1578 		return;
   1579 	}
   1580 
   1581 	if (intrstr != NULL)
   1582 		aprint_normal("%s: interrupting at %s\n",
   1583 			sc->twa_dv.dv_xname, intrstr);
   1584 
   1585 	twa_setup(sc);
   1586 
   1587 	if (twa_sdh == NULL)
   1588 		twa_sdh = shutdownhook_establish(twa_shutdown, NULL);
   1589 
   1590 	return;
   1591 }
   1592 
   1593 static void
   1594 twa_shutdown(void *arg)
   1595 {
   1596 	extern struct cfdriver twa_cd;
   1597 	struct twa_softc *sc;
   1598 	int i, rv, unit;
   1599 
   1600 	for (i = 0; i < twa_cd.cd_ndevs; i++) {
   1601 		if ((sc = device_lookup(&twa_cd, i)) == NULL)
   1602 			continue;
   1603 
   1604 		for (unit = 0; unit < TWA_MAX_UNITS; unit++)
   1605 			if (sc->sc_units[unit].td_dev != NULL)
   1606 				(void) config_detach(sc->sc_units[unit].td_dev,
   1607 					DETACH_FORCE | DETACH_QUIET);
   1608 
   1609 		twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   1610 			TWA_CONTROL_DISABLE_INTERRUPTS);
   1611 
   1612 		/* Let the controller know that we are going down. */
   1613 		rv = twa_init_connection(sc, TWA_SHUTDOWN_MESSAGE_CREDITS,
   1614 				0, 0, 0, 0, 0,
   1615 				NULL, NULL, NULL, NULL, NULL);
   1616 	}
   1617 }
   1618 
   1619 void
   1620 twa_register_callbacks(struct twa_softc *sc, int unit,
   1621     const struct twa_callbacks *tcb)
   1622 {
   1623 
   1624 	sc->sc_units[unit].td_callbacks = tcb;
   1625 }
   1626 
   1627 /*
   1628  * Print autoconfiguration message for a sub-device
   1629  */
   1630 static int
   1631 twa_print(void *aux, const char *pnp)
   1632 {
   1633 	struct twa_attach_args *twaa;
   1634 
   1635 	twaa = aux;
   1636 
   1637 	if (pnp !=NULL)
   1638 		aprint_normal("block device at %s\n", pnp);
   1639 	aprint_normal(" unit %d\n", twaa->twaa_unit);
   1640 	return (UNCONF);
   1641 }
   1642 
   1643 static void
   1644 twa_fillin_sgl(struct twa_sg *sgl, bus_dma_segment_t *segs, int nsegments)
   1645 {
   1646 	int	i;
   1647 	for (i = 0; i < nsegments; i++) {
   1648 		sgl[i].address = segs[i].ds_addr;
   1649 		sgl[i].length = (uint32_t)(segs[i].ds_len);
   1650 	}
   1651 }
   1652 
   1653 static int
   1654 twa_submit_io(struct twa_request *tr)
   1655 {
   1656 	int	error;
   1657 
   1658 	if ((error = twa_start(tr))) {
   1659 		if (error == EBUSY)
   1660 			error = 0; /* request is in the pending queue */
   1661 		else {
   1662 			tr->tr_error = error;
   1663 		}
   1664 	}
   1665 	return(error);
   1666 }
   1667 
   1668 /*
   1669  * Function name:	twa_setup_data_dmamap
   1670  * Description:		Callback of bus_dmamap_load for the buffer associated
   1671  *			with data.  Updates the cmd pkt (size/sgl_entries
   1672  *			fields, as applicable) to reflect the number of sg
   1673  *			elements.
   1674  *
   1675  * Input:		arg	-- ptr to request pkt
   1676  *			segs	-- ptr to a list of segment descriptors
   1677  *			nsegments--# of segments
   1678  *			error	-- 0 if no errors encountered before callback,
   1679  *				   non-zero if errors were encountered
   1680  * Output:		None
   1681  * Return value:	None
   1682  */
   1683 static int
   1684 twa_setup_data_dmamap(void *arg, bus_dma_segment_t *segs, int nsegments,
   1685     int error)
   1686 {
   1687 	struct twa_request		*tr = (struct twa_request *)arg;
   1688 	struct twa_command_packet	*cmdpkt = tr->tr_command;
   1689 	struct twa_command_9k		*cmd9k;
   1690 	union twa_command_7k		*cmd7k;
   1691 	uint8_t				sgl_offset;
   1692 
   1693 	if (error == EFBIG) {
   1694 		tr->tr_error = error;
   1695 		goto out;
   1696 	}
   1697 
   1698 	if (tr->tr_cmd_pkt_type & TWA_CMD_PKT_TYPE_9K) {
   1699 		cmd9k = &(cmdpkt->command.cmd_pkt_9k);
   1700 		twa_fillin_sgl(&(cmd9k->sg_list[0]), segs, nsegments);
   1701 		cmd9k->sgl_entries += nsegments - 1;
   1702 	} else {
   1703 		/* It's a 7000 command packet. */
   1704 		cmd7k = &(cmdpkt->command.cmd_pkt_7k);
   1705 		if ((sgl_offset = cmdpkt->command.cmd_pkt_7k.generic.sgl_offset))
   1706 			twa_fillin_sgl((struct twa_sg *)
   1707 					(((uint32_t *)cmd7k) + sgl_offset),
   1708 					segs, nsegments);
   1709 		/* Modify the size field, based on sg address size. */
   1710 		cmd7k->generic.size +=
   1711 			((TWA_64BIT_ADDRESSES ? 3 : 2) * nsegments);
   1712 	}
   1713 
   1714 	if (tr->tr_flags & TWA_CMD_DATA_IN)
   1715 		bus_dmamap_sync(tr->tr_sc->twa_dma_tag, tr->tr_dma_map, 0,
   1716 			tr->tr_length, BUS_DMASYNC_PREREAD);
   1717 	if (tr->tr_flags & TWA_CMD_DATA_OUT) {
   1718 		/*
   1719 		 * If we're using an alignment buffer, and we're
   1720 		 * writing data, copy the real data out.
   1721 		 */
   1722 		if (tr->tr_flags & TWA_CMD_DATA_COPY_NEEDED)
   1723 			memcpy(tr->tr_data, tr->tr_real_data,
   1724 				tr->tr_real_length);
   1725 		bus_dmamap_sync(tr->tr_sc->twa_dma_tag, tr->tr_dma_map, 0,
   1726 			tr->tr_length, BUS_DMASYNC_PREWRITE);
   1727 	}
   1728 	error = twa_submit_io(tr);
   1729 
   1730 out:
   1731 	if (error) {
   1732 		twa_unmap_request(tr);
   1733 		/*
   1734 		 * If the caller had been returned EINPROGRESS, and he has
   1735 		 * registered a callback for handling completion, the callback
   1736 		 * will never get called because we were unable to submit the
   1737 		 * request.  So, free up the request right here.
   1738 		 */
   1739 		if ((tr->tr_flags & TWA_CMD_IN_PROGRESS) && (tr->tr_callback))
   1740 			twa_release_request(tr);
   1741 	}
   1742 	return (error);
   1743 }
   1744 
   1745 /*
   1746  * Function name:	twa_map_request
   1747  * Description:		Maps a cmd pkt and data associated with it, into
   1748  *			DMA'able memory.
   1749  *
   1750  * Input:		tr	-- ptr to request pkt
   1751  * Output:		None
   1752  * Return value:	0	-- success
   1753  *			non-zero-- failure
   1754  */
   1755 int
   1756 twa_map_request(struct twa_request *tr)
   1757 {
   1758 	struct twa_softc	*sc = tr->tr_sc;
   1759 	int			 s, rv, error = 0;
   1760 
   1761 	/* If the command involves data, map that too. */
   1762 	if (tr->tr_data != NULL) {
   1763 
   1764 		if (((u_long)tr->tr_data & (511)) != 0) {
   1765 			tr->tr_flags |= TWA_CMD_DATA_COPY_NEEDED;
   1766 			tr->tr_real_data = tr->tr_data;
   1767 			tr->tr_real_length = tr->tr_length;
   1768 			s = splvm();
   1769 			tr->tr_data = (void *)uvm_km_alloc(kmem_map,
   1770 			    tr->tr_length, 512, UVM_KMF_NOWAIT|UVM_KMF_WIRED);
   1771 			splx(s);
   1772 
   1773 			if (tr->tr_data == NULL) {
   1774 				tr->tr_data = tr->tr_real_data;
   1775 				tr->tr_length = tr->tr_real_length;
   1776 				return(ENOMEM);
   1777 			}
   1778 			if ((tr->tr_flags & TWA_CMD_DATA_IN) != 0)
   1779 				memcpy(tr->tr_data, tr->tr_real_data,
   1780 					tr->tr_length);
   1781 		}
   1782 
   1783 		/*
   1784 		 * Map the data buffer into bus space and build the S/G list.
   1785 		 */
   1786 		rv = bus_dmamap_load(sc->twa_dma_tag, tr->tr_dma_map,
   1787 			tr->tr_data, tr->tr_length, NULL, BUS_DMA_NOWAIT |
   1788 			BUS_DMA_STREAMING | (tr->tr_flags & TWA_CMD_DATA_OUT) ?
   1789 			BUS_DMA_READ : BUS_DMA_WRITE);
   1790 
   1791 		if (rv != 0) {
   1792 			if ((tr->tr_flags & TWA_CMD_DATA_COPY_NEEDED) != 0) {
   1793 				s = splvm();
   1794 				uvm_km_free(kmem_map, (vaddr_t)tr->tr_data,
   1795 				    tr->tr_length, UVM_KMF_WIRED);
   1796 				splx(s);
   1797 			}
   1798 			return (rv);
   1799 		}
   1800 
   1801 		if ((rv = twa_setup_data_dmamap(tr,
   1802 				tr->tr_dma_map->dm_segs,
   1803 				tr->tr_dma_map->dm_nsegs, error))) {
   1804 
   1805 			if (tr->tr_flags & TWA_CMD_DATA_COPY_NEEDED) {
   1806 				uvm_km_free(kmem_map, (vaddr_t)tr->tr_data,
   1807 				    tr->tr_length, UVM_KMF_WIRED);
   1808 				tr->tr_data = tr->tr_real_data;
   1809 				tr->tr_length = tr->tr_real_length;
   1810 			}
   1811 		} else
   1812 			error = tr->tr_error;
   1813 
   1814 	} else
   1815 		if ((rv = twa_submit_io(tr)))
   1816 			twa_unmap_request(tr);
   1817 
   1818 	return (rv);
   1819 }
   1820 
   1821 #if 0
   1822 /*
   1823  * Function name:	twa_flash_firmware
   1824  * Description:		Flashes bundled firmware image onto controller.
   1825  *
   1826  * Input:		sc	-- ptr to per ctlr structure
   1827  * Output:		None
   1828  * Return value:	0	-- success
   1829  *			non-zero-- failure
   1830  */
   1831 static int
   1832 twa_flash_firmware(struct twa_softc *sc)
   1833 {
   1834 	struct twa_request			*tr;
   1835 	struct twa_command_download_firmware	*cmd;
   1836 	uint32_t				count;
   1837 	uint32_t				fw_img_chunk_size;
   1838 	uint32_t				this_chunk_size = 0;
   1839 	uint32_t				remaining_img_size = 0;
   1840 	int					s, error = 0;
   1841 	int					i;
   1842 
   1843 	if ((tr = twa_get_request(sc, 0)) == NULL) {
   1844 		/* No free request packets available.  Can't proceed. */
   1845 		error = EIO;
   1846 		goto out;
   1847 	}
   1848 
   1849 	count = (twa_fw_img_size / 65536);
   1850 
   1851 	count += ((twa_fw_img_size % 65536) != 0) ? 1 : 0;
   1852 
   1853 	tr->tr_cmd_pkt_type |= TWA_CMD_PKT_TYPE_INTERNAL;
   1854 	/* Allocate sufficient memory to hold a chunk of the firmware image. */
   1855 	fw_img_chunk_size = ((twa_fw_img_size / count) + 511) & ~511;
   1856 
   1857 	s = splvm();
   1858 	tr->tr_data = (void *)uvm_km_alloc(kmem_map, fw_img_chunk_size, 512,
   1859 				UVM_KMF_WIRED);
   1860 	splx(s);
   1861 
   1862 	if (tr->tr_data == NULL) {
   1863 		error = ENOMEM;
   1864 		goto out;
   1865 	}
   1866 
   1867 	remaining_img_size = twa_fw_img_size;
   1868 	cmd = &(tr->tr_command->command.cmd_pkt_7k.download_fw);
   1869 
   1870 	for (i = 0; i < count; i++) {
   1871 		/* Build a cmd pkt for downloading firmware. */
   1872 		memset(tr->tr_command, 0, sizeof(struct twa_command_packet));
   1873 
   1874 		tr->tr_command->cmd_hdr.header_desc.size_header = 128;
   1875 
   1876 		cmd->opcode = TWA_OP_DOWNLOAD_FIRMWARE;
   1877 		cmd->sgl_offset = 2;	/* offset in dwords, to the beginning
   1878 					   of sg list */
   1879 		cmd->size = 2;		/* this field will be updated at data
   1880 					   map time */
   1881 		cmd->request_id = tr->tr_request_id;
   1882 		cmd->unit = 0;
   1883 		cmd->status = 0;
   1884 		cmd->flags = 0;
   1885 		cmd->param = 8;	/* prom image */
   1886 
   1887 		if (i != (count - 1))
   1888 			this_chunk_size = fw_img_chunk_size;
   1889 		else	 /* last chunk */
   1890 			this_chunk_size = remaining_img_size;
   1891 
   1892 		remaining_img_size -= this_chunk_size;
   1893 
   1894 		memset(tr->tr_data, fw_img_chunk_size, 0);
   1895 
   1896 		memcpy(tr->tr_data, twa_fw_img + (i * fw_img_chunk_size),
   1897 			this_chunk_size);
   1898 		/*
   1899 		 * The next line will effect only the last chunk.
   1900 		 */
   1901 		tr->tr_length = (this_chunk_size + 511) & ~511;
   1902 
   1903 		tr->tr_flags |= TWA_CMD_DATA_OUT;
   1904 
   1905 		error = twa_immediate_request(tr, TWA_REQUEST_TIMEOUT_PERIOD);
   1906 
   1907 		if (error) {
   1908 			if (error == ETIMEDOUT)
   1909 				/* clean-up done by twa_immediate_request */
   1910 				return(error);
   1911 			break;
   1912 		}
   1913 		error = cmd->status;
   1914 
   1915 		if (i != (count - 1)) {
   1916 
   1917 			/*
   1918 			 * XXX FreeBSD code doesn't check for no error condition
   1919 			 * but based on observation, error seems to return 0
   1920 			 */
   1921 			if ((error =
   1922 			    tr->tr_command->cmd_hdr.status_block.error) == 0) {
   1923 				continue;
   1924 			} else if ((error =
   1925 			    tr->tr_command->cmd_hdr.status_block.error) ==
   1926 			    TWA_ERROR_MORE_DATA) {
   1927 				    continue;
   1928 			} else {
   1929 				twa_hard_reset(sc);
   1930 				break;
   1931 			}
   1932 		} else	 /* last chunk */
   1933 			if (error) {
   1934 				printf("%s: firmware flash request failed. "
   1935 				    "error = 0x%x\n", sc->twa_dv.dv_xname,
   1936 				    error);
   1937 				twa_hard_reset(sc);
   1938 			}
   1939 	}
   1940 
   1941 	if (tr->tr_data) {
   1942 		s = splvm();
   1943 		uvm_km_free(kmem_map, (vaddr_t)tr->tr_data,
   1944 			fw_img_chunk_size, UVM_KMF_WIRED);
   1945 		splx(s);
   1946 	}
   1947 out:
   1948 	if (tr)
   1949 		twa_release_request(tr);
   1950 	return(error);
   1951 }
   1952 
   1953 /*
   1954  * Function name:	twa_hard_reset
   1955  * Description:		Hard reset the controller.
   1956  *
   1957  * Input:		sc	-- ptr to per ctlr structure
   1958  * Output:		None
   1959  * Return value:	0	-- success
   1960  *			non-zero-- failure
   1961  */
   1962 static int
   1963 twa_hard_reset(struct twa_softc *sc)
   1964 {
   1965 	struct twa_request			*tr;
   1966 	struct twa_command_reset_firmware	*cmd;
   1967 	int					error;
   1968 
   1969 	if ((tr = twa_get_request(sc, 0)) == NULL)
   1970 		return(EIO);
   1971 	tr->tr_cmd_pkt_type |= TWA_CMD_PKT_TYPE_INTERNAL;
   1972 	/* Build a cmd pkt for sending down the hard reset command. */
   1973 	tr->tr_command->cmd_hdr.header_desc.size_header = 128;
   1974 
   1975 	cmd = &(tr->tr_command->command.cmd_pkt_7k.reset_fw);
   1976 	cmd->opcode = TWA_OP_RESET_FIRMWARE;
   1977 	cmd->size = 2;	/* this field will be updated at data map time */
   1978 	cmd->request_id = tr->tr_request_id;
   1979 	cmd->unit = 0;
   1980 	cmd->status = 0;
   1981 	cmd->flags = 0;
   1982 	cmd->param = 0;	/* don't reload FPGA logic */
   1983 
   1984 	tr->tr_data = NULL;
   1985 	tr->tr_length = 0;
   1986 
   1987 	error = twa_immediate_request(tr, TWA_REQUEST_TIMEOUT_PERIOD);
   1988 	if (error) {
   1989 		printf("%s: hard reset request could not be posted. "
   1990 		    "error = 0x%x\n", sc->twa_dv.dv_xname, error);
   1991 		if (error == ETIMEDOUT)
   1992 			/* clean-up done by twa_immediate_request */
   1993 			return(error);
   1994 		goto out;
   1995 	}
   1996 	if ((error = cmd->status)) {
   1997 		printf("%s: hard reset request failed. error = 0x%x\n",
   1998 			sc->twa_dv.dv_xname, error);
   1999 	}
   2000 
   2001 out:
   2002 	if (tr)
   2003 		twa_release_request(tr);
   2004 	return(error);
   2005 }
   2006 #endif
   2007 
   2008 /*
   2009  * Function name:	twa_intr
   2010  * Description:		Interrupt handler.  Determines the kind of interrupt,
   2011  *			and calls the appropriate handler.
   2012  *
   2013  * Input:		sc	-- ptr to per ctlr structure
   2014  * Output:		None
   2015  * Return value:	None
   2016  */
   2017 
   2018 static int
   2019 twa_intr(void *arg)
   2020 {
   2021 	int	caught, s, rv;
   2022 	struct twa_softc *sc;
   2023 	uint32_t	status_reg;
   2024 	sc = (struct twa_softc *)arg;
   2025 
   2026 	caught = 0;
   2027 	/* Collect current interrupt status. */
   2028 	status_reg = twa_inl(sc, TWA_STATUS_REGISTER_OFFSET);
   2029 	if (twa_check_ctlr_state(sc, status_reg)) {
   2030 		caught = 1;
   2031 		goto bail;
   2032 	}
   2033 	/* Dispatch based on the kind of interrupt. */
   2034 	if (status_reg & TWA_STATUS_HOST_INTERRUPT) {
   2035 		twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   2036 			TWA_CONTROL_CLEAR_HOST_INTERRUPT);
   2037 		caught = 1;
   2038 	}
   2039 	if ((status_reg & TWA_STATUS_ATTENTION_INTERRUPT) != 0) {
   2040 		twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   2041 			TWA_CONTROL_CLEAR_ATTENTION_INTERRUPT);
   2042 		rv = twa_fetch_aen(sc);
   2043 #ifdef DIAGNOSTIC
   2044 		if (rv != 0)
   2045 			printf("%s: unable to retrieve AEN (%d)\n",
   2046 				sc->twa_dv.dv_xname, rv);
   2047 #endif
   2048 		caught = 1;
   2049 	}
   2050 	if (status_reg & TWA_STATUS_COMMAND_INTERRUPT) {
   2051 		/* Start any requests that might be in the pending queue. */
   2052 		twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   2053 			TWA_CONTROL_MASK_COMMAND_INTERRUPT);
   2054 		(void)twa_drain_pending_queue(sc);
   2055 		caught = 1;
   2056 	}
   2057 	if (status_reg & TWA_STATUS_RESPONSE_INTERRUPT) {
   2058 		s = splbio();
   2059 		twa_done(sc);
   2060 		splx(s);
   2061 		caught = 1;
   2062 	}
   2063 bail:
   2064 	return (caught);
   2065 }
   2066 
   2067 /*
   2068  * Accept an open operation on the control device.
   2069  */
   2070 static int
   2071 twaopen(dev_t dev, int flag, int mode, struct lwp *l)
   2072 {
   2073 	struct twa_softc *twa;
   2074 
   2075 	if ((twa = device_lookup(&twa_cd, minor(dev))) == NULL)
   2076 		return (ENXIO);
   2077 	if ((twa->twa_sc_flags & TWA_STATE_OPEN) != 0)
   2078 		return (EBUSY);
   2079 
   2080 	twa->twa_sc_flags |= TWA_STATE_OPEN;
   2081 
   2082 	return (0);
   2083 }
   2084 
   2085 /*
   2086  * Accept the last close on the control device.
   2087  */
   2088 static int
   2089 twaclose(dev_t dev, int flag, int mode, struct lwp *l)
   2090 {
   2091 	struct twa_softc *twa;
   2092 
   2093 	twa = device_lookup(&twa_cd, minor(dev));
   2094 	twa->twa_sc_flags &= ~TWA_STATE_OPEN;
   2095 	return (0);
   2096 }
   2097 
   2098 /*
   2099  * Function name:	twaioctl
   2100  * Description:		ioctl handler.
   2101  *
   2102  * Input:		sc	-- ptr to per ctlr structure
   2103  *			cmd	-- ioctl cmd
   2104  *			buf	-- ptr to buffer in kernel memory, which is
   2105  *				   a copy of the input buffer in user-space
   2106  * Output:		buf	-- ptr to buffer in kernel memory, which will
   2107  *				   be copied of the output buffer in user-space
   2108  * Return value:	0	-- success
   2109  *			non-zero-- failure
   2110  */
   2111 static int
   2112 twaioctl(dev_t dev, u_long cmd, caddr_t data, int flag, struct lwp *l)
   2113 {
   2114 	struct twa_softc *sc;
   2115 	struct twa_ioctl_9k	*user_buf = (struct twa_ioctl_9k *)data;
   2116 	struct tw_cl_event_packet event_buf;
   2117 	struct twa_request 	*tr = 0;
   2118 	int32_t			event_index = 0;
   2119 	int32_t			start_index;
   2120 	int			s, error = 0;
   2121 
   2122 	sc = device_lookup(&twa_cd, minor(dev));
   2123 
   2124 	switch (cmd) {
   2125 	case TW_OSL_IOCTL_FIRMWARE_PASS_THROUGH:
   2126 	{
   2127 		struct twa_command_packet	*cmdpkt;
   2128 		uint32_t			data_buf_size_adjusted;
   2129 
   2130 		/* Get a request packet */
   2131 		tr = twa_get_request_wait(sc, 0);
   2132 		KASSERT(tr != NULL);
   2133 		/*
   2134 		 * Make sure that the data buffer sent to firmware is a
   2135 		 * 512 byte multiple in size.
   2136 		 */
   2137 		data_buf_size_adjusted =
   2138 			(user_buf->twa_drvr_pkt.buffer_length + 511) & ~511;
   2139 
   2140 		if ((tr->tr_length = data_buf_size_adjusted)) {
   2141 			if ((tr->tr_data = malloc(data_buf_size_adjusted,
   2142 			    M_DEVBUF, M_WAITOK)) == NULL) {
   2143 				error = ENOMEM;
   2144 				goto fw_passthru_done;
   2145 			}
   2146 			/* Copy the payload. */
   2147 			if ((error = copyin((void *) (user_buf->pdata),
   2148 				(void *) (tr->tr_data),
   2149 				user_buf->twa_drvr_pkt.buffer_length)) != 0) {
   2150 					goto fw_passthru_done;
   2151 			}
   2152 			tr->tr_flags |= TWA_CMD_DATA_IN | TWA_CMD_DATA_OUT;
   2153 		}
   2154 		tr->tr_cmd_pkt_type |= TWA_CMD_PKT_TYPE_IOCTL;
   2155 		cmdpkt = tr->tr_command;
   2156 
   2157 		/* Copy the command packet. */
   2158 		memcpy(cmdpkt, &(user_buf->twa_cmd_pkt),
   2159 			sizeof(struct twa_command_packet));
   2160 		cmdpkt->command.cmd_pkt_7k.generic.request_id =
   2161 			tr->tr_request_id;
   2162 
   2163 		/* Send down the request, and wait for it to complete. */
   2164 		if ((error = twa_wait_request(tr, TWA_REQUEST_TIMEOUT_PERIOD))) 		{
   2165 			if (error == ETIMEDOUT)
   2166 				break; /* clean-up done by twa_wait_request */
   2167 			goto fw_passthru_done;
   2168 		}
   2169 
   2170 		/* Copy the command packet back into user space. */
   2171 		memcpy(&user_buf->twa_cmd_pkt, cmdpkt,
   2172 			sizeof(struct twa_command_packet));
   2173 
   2174 		/* If there was a payload, copy it back too. */
   2175 		if (tr->tr_length)
   2176 			error = copyout(tr->tr_data, user_buf->pdata,
   2177 					user_buf->twa_drvr_pkt.buffer_length);
   2178 fw_passthru_done:
   2179 		/* Free resources. */
   2180 		if (tr->tr_data)
   2181 			free(tr->tr_data, M_DEVBUF);
   2182 
   2183 		if (tr)
   2184 			twa_release_request(tr);
   2185 		break;
   2186 	}
   2187 
   2188 	case TW_OSL_IOCTL_SCAN_BUS:
   2189 		twa_request_bus_scan(sc);
   2190 		break;
   2191 
   2192 	case TW_CL_IOCTL_GET_FIRST_EVENT:
   2193 		if (sc->twa_aen_queue_wrapped) {
   2194 			if (sc->twa_aen_queue_overflow) {
   2195 				/*
   2196 				 * The aen queue has wrapped, even before some
   2197 				 * events have been retrieved.  Let the caller
   2198 				 * know that he missed out on some AEN's.
   2199 				 */
   2200 				user_buf->twa_drvr_pkt.status =
   2201 					TWA_ERROR_AEN_OVERFLOW;
   2202 				sc->twa_aen_queue_overflow = FALSE;
   2203 			} else
   2204 				user_buf->twa_drvr_pkt.status = 0;
   2205 			event_index = sc->twa_aen_head;
   2206 		} else {
   2207 			if (sc->twa_aen_head == sc->twa_aen_tail) {
   2208 				user_buf->twa_drvr_pkt.status =
   2209 					TWA_ERROR_AEN_NO_EVENTS;
   2210 				break;
   2211 			}
   2212 			user_buf->twa_drvr_pkt.status = 0;
   2213 			event_index = sc->twa_aen_tail;	/* = 0 */
   2214 		}
   2215 		if ((error = copyout(sc->twa_aen_queue[event_index],
   2216 		    user_buf->pdata, sizeof(struct tw_cl_event_packet))) != 0)
   2217 			(sc->twa_aen_queue[event_index])->retrieved =
   2218 			    TWA_AEN_RETRIEVED;
   2219 		break;
   2220 
   2221 	case TW_CL_IOCTL_GET_LAST_EVENT:
   2222 		if (sc->twa_aen_queue_wrapped) {
   2223 			if (sc->twa_aen_queue_overflow) {
   2224 				/*
   2225 				 * The aen queue has wrapped, even before some
   2226 				 * events have been retrieved.  Let the caller
   2227 				 * know that he missed out on some AEN's.
   2228 				 */
   2229 				user_buf->twa_drvr_pkt.status =
   2230 					TWA_ERROR_AEN_OVERFLOW;
   2231 				sc->twa_aen_queue_overflow = FALSE;
   2232 			} else
   2233 				user_buf->twa_drvr_pkt.status = 0;
   2234 		} else {
   2235 			if (sc->twa_aen_head == sc->twa_aen_tail) {
   2236 				user_buf->twa_drvr_pkt.status =
   2237 					TWA_ERROR_AEN_NO_EVENTS;
   2238 				break;
   2239 			}
   2240 			user_buf->twa_drvr_pkt.status = 0;
   2241 		}
   2242 		event_index =
   2243 		    (sc->twa_aen_head - 1 + TWA_Q_LENGTH) % TWA_Q_LENGTH;
   2244 		if ((error = copyout(sc->twa_aen_queue[event_index],
   2245 		    user_buf->pdata, sizeof(struct tw_cl_event_packet))) != 0)
   2246 			(sc->twa_aen_queue[event_index])->retrieved =
   2247 			    TWA_AEN_RETRIEVED;
   2248 		break;
   2249 
   2250 	case TW_CL_IOCTL_GET_NEXT_EVENT:
   2251 		user_buf->twa_drvr_pkt.status = 0;
   2252 		if (sc->twa_aen_queue_wrapped) {
   2253 
   2254 			if (sc->twa_aen_queue_overflow) {
   2255 				/*
   2256 				 * The aen queue has wrapped, even before some
   2257 				 * events have been retrieved.  Let the caller
   2258 				 * know that he missed out on some AEN's.
   2259 				 */
   2260 				user_buf->twa_drvr_pkt.status =
   2261 					TWA_ERROR_AEN_OVERFLOW;
   2262 				sc->twa_aen_queue_overflow = FALSE;
   2263 			}
   2264 			start_index = sc->twa_aen_head;
   2265 		} else {
   2266 			if (sc->twa_aen_head == sc->twa_aen_tail) {
   2267 				user_buf->twa_drvr_pkt.status =
   2268 					TWA_ERROR_AEN_NO_EVENTS;
   2269 				break;
   2270 			}
   2271 			start_index = sc->twa_aen_tail;	/* = 0 */
   2272 		}
   2273 		error = copyin(user_buf->pdata, &event_buf,
   2274 				sizeof(struct tw_cl_event_packet));
   2275 
   2276 		event_index = (start_index + event_buf.sequence_id -
   2277 		    (sc->twa_aen_queue[start_index])->sequence_id + 1)
   2278 		    % TWA_Q_LENGTH;
   2279 
   2280 		if (!((sc->twa_aen_queue[event_index])->sequence_id >
   2281 		    event_buf.sequence_id)) {
   2282 			if (user_buf->twa_drvr_pkt.status ==
   2283 			    TWA_ERROR_AEN_OVERFLOW)
   2284 				/* so we report the overflow next time */
   2285 				sc->twa_aen_queue_overflow = TRUE;
   2286 			user_buf->twa_drvr_pkt.status = TWA_ERROR_AEN_NO_EVENTS;
   2287 			break;
   2288 		}
   2289 		if ((error = copyout(sc->twa_aen_queue[event_index],
   2290 		    user_buf->pdata, sizeof(struct tw_cl_event_packet))) != 0)
   2291 			(sc->twa_aen_queue[event_index])->retrieved =
   2292 			    TWA_AEN_RETRIEVED;
   2293 		break;
   2294 
   2295 	case TW_CL_IOCTL_GET_PREVIOUS_EVENT:
   2296 		user_buf->twa_drvr_pkt.status = 0;
   2297 		if (sc->twa_aen_queue_wrapped) {
   2298 			if (sc->twa_aen_queue_overflow) {
   2299 				/*
   2300 				 * The aen queue has wrapped, even before some
   2301 				 * events have been retrieved.  Let the caller
   2302 				 * know that he missed out on some AEN's.
   2303 				 */
   2304 				user_buf->twa_drvr_pkt.status =
   2305 					TWA_ERROR_AEN_OVERFLOW;
   2306 				sc->twa_aen_queue_overflow = FALSE;
   2307 			}
   2308 			start_index = sc->twa_aen_head;
   2309 		} else {
   2310 			if (sc->twa_aen_head == sc->twa_aen_tail) {
   2311 				user_buf->twa_drvr_pkt.status =
   2312 					TWA_ERROR_AEN_NO_EVENTS;
   2313 				break;
   2314 			}
   2315 			start_index = sc->twa_aen_tail;	/* = 0 */
   2316 		}
   2317 		if ((error = copyin(user_buf->pdata, &event_buf,
   2318 				sizeof(struct tw_cl_event_packet))) != 0)
   2319 
   2320 		event_index = (start_index + event_buf.sequence_id -
   2321 		    (sc->twa_aen_queue[start_index])->sequence_id - 1)
   2322 		    % TWA_Q_LENGTH;
   2323 		if (!((sc->twa_aen_queue[event_index])->sequence_id <
   2324 		    event_buf.sequence_id)) {
   2325 			if (user_buf->twa_drvr_pkt.status ==
   2326 			    TWA_ERROR_AEN_OVERFLOW)
   2327 				/* so we report the overflow next time */
   2328 				sc->twa_aen_queue_overflow = TRUE;
   2329 			user_buf->twa_drvr_pkt.status =
   2330 				TWA_ERROR_AEN_NO_EVENTS;
   2331 			break;
   2332 		}
   2333 		if ((error = copyout(sc->twa_aen_queue [event_index],
   2334 		    user_buf->pdata, sizeof(struct tw_cl_event_packet))) != 0)
   2335 			aprint_error("%s: get_previous: Could not copyout to "
   2336 			    "event_buf. error = %x\n", sc->twa_dv.dv_xname,
   2337 			    error);
   2338 		(sc->twa_aen_queue[event_index])->retrieved = TWA_AEN_RETRIEVED;
   2339 		break;
   2340 
   2341 	case TW_CL_IOCTL_GET_LOCK:
   2342 	{
   2343 		struct tw_cl_lock_packet	twa_lock;
   2344 
   2345 		copyin(user_buf->pdata, &twa_lock,
   2346 				sizeof(struct tw_cl_lock_packet));
   2347 		s = splbio();
   2348 		if ((sc->twa_ioctl_lock.lock == TWA_LOCK_FREE) ||
   2349 			(twa_lock.force_flag) ||
   2350 			(time_second >= sc->twa_ioctl_lock.timeout)) {
   2351 
   2352 			sc->twa_ioctl_lock.lock = TWA_LOCK_HELD;
   2353 			sc->twa_ioctl_lock.timeout = time_second +
   2354 				(twa_lock.timeout_msec / 1000);
   2355 			twa_lock.time_remaining_msec = twa_lock.timeout_msec;
   2356 			user_buf->twa_drvr_pkt.status = 0;
   2357 		} else {
   2358 			twa_lock.time_remaining_msec =
   2359 				(sc->twa_ioctl_lock.timeout - time_second) *
   2360 				1000;
   2361 			user_buf->twa_drvr_pkt.status =
   2362 					TWA_ERROR_IOCTL_LOCK_ALREADY_HELD;
   2363 		}
   2364 		splx(s);
   2365 		copyout(&twa_lock, user_buf->pdata,
   2366 				sizeof(struct tw_cl_lock_packet));
   2367 		break;
   2368 	}
   2369 
   2370 	case TW_CL_IOCTL_RELEASE_LOCK:
   2371 		s = splbio();
   2372 		if (sc->twa_ioctl_lock.lock == TWA_LOCK_FREE) {
   2373 			user_buf->twa_drvr_pkt.status =
   2374 				TWA_ERROR_IOCTL_LOCK_NOT_HELD;
   2375 		} else {
   2376 			sc->twa_ioctl_lock.lock = TWA_LOCK_FREE;
   2377 			user_buf->twa_drvr_pkt.status = 0;
   2378 		}
   2379 		splx(s);
   2380 		break;
   2381 
   2382 	case TW_CL_IOCTL_GET_COMPATIBILITY_INFO:
   2383 	{
   2384 		struct tw_cl_compatibility_packet	comp_pkt;
   2385 
   2386 		memcpy(comp_pkt.driver_version, TWA_DRIVER_VERSION_STRING,
   2387 					sizeof(TWA_DRIVER_VERSION_STRING));
   2388 		comp_pkt.working_srl = sc->working_srl;
   2389 		comp_pkt.working_branch = sc->working_branch;
   2390 		comp_pkt.working_build = sc->working_build;
   2391 		user_buf->twa_drvr_pkt.status = 0;
   2392 
   2393 		/* Copy compatibility information to user space. */
   2394 		copyout(&comp_pkt, user_buf->pdata,
   2395 				min(sizeof(struct tw_cl_compatibility_packet),
   2396 					user_buf->twa_drvr_pkt.buffer_length));
   2397 		break;
   2398 	}
   2399 
   2400 	case TWA_IOCTL_GET_UNITNAME:	/* WASABI EXTENSION */
   2401 	{
   2402 		struct twa_unitname	*tn;
   2403 		struct twa_drive	*tdr;
   2404 
   2405 		tn = (struct twa_unitname *)data;
   2406 			/* XXX mutex */
   2407 		if (tn->tn_unit < 0 || tn->tn_unit >= TWA_MAX_UNITS)
   2408 			return (EINVAL);
   2409 		tdr = &sc->sc_units[tn->tn_unit];
   2410 		if (tdr->td_dev == NULL)
   2411 			tn->tn_name[0] = '\0';
   2412 		else
   2413 			strlcpy(tn->tn_name, tdr->td_dev->dv_xname,
   2414 			    sizeof(tn->tn_name));
   2415 		return (0);
   2416 	}
   2417 
   2418 	default:
   2419 		/* Unknown opcode. */
   2420 		error = ENOTTY;
   2421 	}
   2422 
   2423 	return(error);
   2424 }
   2425 
   2426 const struct cdevsw twa_cdevsw = {
   2427 	twaopen, twaclose, noread, nowrite, twaioctl,
   2428 	nostop, notty, nopoll, nommap,
   2429 };
   2430 
   2431 /*
   2432  * Function name:	twa_get_param
   2433  * Description:		Get a firmware parameter.
   2434  *
   2435  * Input:		sc		-- ptr to per ctlr structure
   2436  *			table_id	-- parameter table #
   2437  *			param_id	-- index of the parameter in the table
   2438  *			param_size	-- size of the parameter in bytes
   2439  *			callback	-- ptr to function, if any, to be called
   2440  *					back on completion; NULL if no callback.
   2441  * Output:		None
   2442  * Return value:	ptr to param structure	-- success
   2443  *			NULL			-- failure
   2444  */
   2445 static int
   2446 twa_get_param(struct twa_softc *sc, int table_id, int param_id,
   2447     size_t param_size, void (* callback)(struct twa_request *tr),
   2448     struct twa_param_9k **param)
   2449 {
   2450 	int			rv = 0;
   2451 	struct twa_request	*tr;
   2452 	union twa_command_7k	*cmd;
   2453 
   2454 	/* Get a request packet. */
   2455 	if ((tr = twa_get_request(sc, 0)) == NULL) {
   2456 		rv = EAGAIN;
   2457 		goto out;
   2458 	}
   2459 
   2460 	tr->tr_cmd_pkt_type |= TWA_CMD_PKT_TYPE_INTERNAL;
   2461 
   2462 	/* Allocate memory to read data into. */
   2463 	if ((*param = (struct twa_param_9k *)
   2464 		malloc(TWA_SECTOR_SIZE, M_DEVBUF, M_NOWAIT)) == NULL) {
   2465 		rv = ENOMEM;
   2466 		goto out;
   2467 	}
   2468 
   2469 	memset(*param, 0, sizeof(struct twa_param_9k) - 1 + param_size);
   2470 	tr->tr_data = *param;
   2471 	tr->tr_length = TWA_SECTOR_SIZE;
   2472 	tr->tr_flags = TWA_CMD_DATA_IN | TWA_CMD_DATA_OUT;
   2473 
   2474 	/* Build the cmd pkt. */
   2475 	cmd = &(tr->tr_command->command.cmd_pkt_7k);
   2476 
   2477 	tr->tr_command->cmd_hdr.header_desc.size_header = 128;
   2478 
   2479 	cmd->param.opcode = TWA_OP_GET_PARAM;
   2480 	cmd->param.sgl_offset = 2;
   2481 	cmd->param.size = 2;
   2482 	cmd->param.request_id = tr->tr_request_id;
   2483 	cmd->param.unit = 0;
   2484 	cmd->param.param_count = 1;
   2485 
   2486 	/* Specify which parameter we need. */
   2487 	(*param)->table_id = table_id | TWA_9K_PARAM_DESCRIPTOR;
   2488 	(*param)->parameter_id = param_id;
   2489 	(*param)->parameter_size_bytes = param_size;
   2490 
   2491 	/* Submit the command. */
   2492 	if (callback == NULL) {
   2493 		/* There's no call back; wait till the command completes. */
   2494 		rv = twa_immediate_request(tr, TWA_REQUEST_TIMEOUT_PERIOD);
   2495 
   2496 		if (rv != 0)
   2497 			goto out;
   2498 
   2499 		if ((rv = cmd->param.status) != 0) {
   2500 		     /* twa_drain_complete_queue will have done the unmapping */
   2501 		     goto out;
   2502 		}
   2503 		twa_release_request(tr);
   2504 		return (rv);
   2505 	} else {
   2506 		/* There's a call back.  Simply submit the command. */
   2507 		tr->tr_callback = callback;
   2508 		rv = twa_map_request(tr);
   2509 		return (rv);
   2510 	}
   2511 out:
   2512 	if (tr)
   2513 		twa_release_request(tr);
   2514 	return(rv);
   2515 }
   2516 
   2517 /*
   2518  * Function name:	twa_set_param
   2519  * Description:		Set a firmware parameter.
   2520  *
   2521  * Input:		sc		-- ptr to per ctlr structure
   2522  *			table_id	-- parameter table #
   2523  *			param_id	-- index of the parameter in the table
   2524  *			param_size	-- size of the parameter in bytes
   2525  *			callback	-- ptr to function, if any, to be called
   2526  *					back on completion; NULL if no callback.
   2527  * Output:		None
   2528  * Return value:	0	-- success
   2529  *			non-zero-- failure
   2530  */
   2531 static int
   2532 twa_set_param(struct twa_softc *sc, int table_id, int param_id, int param_size,
   2533     void *data, void (* callback)(struct twa_request *tr))
   2534 {
   2535 	struct twa_request	*tr;
   2536 	union twa_command_7k	*cmd;
   2537 	struct twa_param_9k	*param = NULL;
   2538 	int			error = ENOMEM;
   2539 
   2540 	tr = twa_get_request(sc, 0);
   2541 	if (tr == NULL)
   2542 		return (EAGAIN);
   2543 
   2544 	tr->tr_cmd_pkt_type |= TWA_CMD_PKT_TYPE_INTERNAL;
   2545 
   2546 	/* Allocate memory to send data using. */
   2547 	if ((param = (struct twa_param_9k *)
   2548 			malloc(TWA_SECTOR_SIZE, M_DEVBUF, M_NOWAIT)) == NULL)
   2549 		goto out;
   2550 	memset(param, 0, sizeof(struct twa_param_9k) - 1 + param_size);
   2551 	tr->tr_data = param;
   2552 	tr->tr_length = TWA_SECTOR_SIZE;
   2553 	tr->tr_flags = TWA_CMD_DATA_IN | TWA_CMD_DATA_OUT;
   2554 
   2555 	/* Build the cmd pkt. */
   2556 	cmd = &(tr->tr_command->command.cmd_pkt_7k);
   2557 
   2558 	tr->tr_command->cmd_hdr.header_desc.size_header = 128;
   2559 
   2560 	cmd->param.opcode = TWA_OP_SET_PARAM;
   2561 	cmd->param.sgl_offset = 2;
   2562 	cmd->param.size = 2;
   2563 	cmd->param.request_id = tr->tr_request_id;
   2564 	cmd->param.unit = 0;
   2565 	cmd->param.param_count = 1;
   2566 
   2567 	/* Specify which parameter we want to set. */
   2568 	param->table_id = table_id | TWA_9K_PARAM_DESCRIPTOR;
   2569 	param->parameter_id = param_id;
   2570 	param->parameter_size_bytes = param_size;
   2571 	memcpy(param->data, data, param_size);
   2572 
   2573 	/* Submit the command. */
   2574 	if (callback == NULL) {
   2575 		/* There's no call back;  wait till the command completes. */
   2576 		error = twa_immediate_request(tr, TWA_REQUEST_TIMEOUT_PERIOD);
   2577 		if (error == ETIMEDOUT)
   2578 			/* clean-up done by twa_immediate_request */
   2579 			return(error);
   2580 		if (error)
   2581 			goto out;
   2582 		if ((error = cmd->param.status)) {
   2583 			/*
   2584 			 * twa_drain_complete_queue will have done the
   2585 			 * unmapping.
   2586 			 */
   2587 			goto out;
   2588 		}
   2589 		free(param, M_DEVBUF);
   2590 		twa_release_request(tr);
   2591 		return(error);
   2592 	} else {
   2593 		/* There's a call back.  Simply submit the command. */
   2594 		tr->tr_callback = callback;
   2595 		if ((error = twa_map_request(tr)))
   2596 			goto out;
   2597 
   2598 		return (0);
   2599 	}
   2600 out:
   2601 	if (param)
   2602 		free(param, M_DEVBUF);
   2603 	if (tr)
   2604 		twa_release_request(tr);
   2605 	return(error);
   2606 }
   2607 
   2608 /*
   2609  * Function name:	twa_init_connection
   2610  * Description:		Send init_connection cmd to firmware
   2611  *
   2612  * Input:		sc		-- ptr to per ctlr structure
   2613  *			message_credits	-- max # of requests that we might send
   2614  *					 down simultaneously.  This will be
   2615  *					 typically set to 256 at init-time or
   2616  *					after a reset, and to 1 at shutdown-time
   2617  *			set_features	-- indicates if we intend to use 64-bit
   2618  *					sg, also indicates if we want to do a
   2619  *					basic or an extended init_connection;
   2620  *
   2621  * Note: The following input/output parameters are valid, only in case of an
   2622  *		extended init_connection:
   2623  *
   2624  *			current_fw_srl		-- srl of fw we are bundled
   2625  *						with, if any; 0 otherwise
   2626  *			current_fw_arch_id	-- arch_id of fw we are bundled
   2627  *						with, if any; 0 otherwise
   2628  *			current_fw_branch	-- branch # of fw we are bundled
   2629  *						with, if any; 0 otherwise
   2630  *			current_fw_build	-- build # of fw we are bundled
   2631  *						with, if any; 0 otherwise
   2632  * Output:		fw_on_ctlr_srl		-- srl of fw on ctlr
   2633  *			fw_on_ctlr_arch_id	-- arch_id of fw on ctlr
   2634  *			fw_on_ctlr_branch	-- branch # of fw on ctlr
   2635  *			fw_on_ctlr_build	-- build # of fw on ctlr
   2636  *			init_connect_result	-- result bitmap of fw response
   2637  * Return value:	0	-- success
   2638  *			non-zero-- failure
   2639  */
   2640 static int
   2641 twa_init_connection(struct twa_softc *sc, uint16_t message_credits,
   2642     uint32_t set_features, uint16_t current_fw_srl,
   2643     uint16_t current_fw_arch_id, uint16_t current_fw_branch,
   2644     uint16_t current_fw_build, uint16_t *fw_on_ctlr_srl,
   2645     uint16_t *fw_on_ctlr_arch_id, uint16_t *fw_on_ctlr_branch,
   2646     uint16_t *fw_on_ctlr_build, uint32_t *init_connect_result)
   2647 {
   2648 	struct twa_request		*tr;
   2649 	struct twa_command_init_connect	*init_connect;
   2650 	int				error = 1;
   2651 
   2652 	/* Get a request packet. */
   2653 	if ((tr = twa_get_request(sc, 0)) == NULL)
   2654 		goto out;
   2655 	tr->tr_cmd_pkt_type |= TWA_CMD_PKT_TYPE_INTERNAL;
   2656 	/* Build the cmd pkt. */
   2657 	init_connect = &(tr->tr_command->command.cmd_pkt_7k.init_connect);
   2658 
   2659 	tr->tr_command->cmd_hdr.header_desc.size_header = 128;
   2660 
   2661 	init_connect->opcode = TWA_OP_INIT_CONNECTION;
   2662    	init_connect->request_id = tr->tr_request_id;
   2663 	init_connect->message_credits = message_credits;
   2664 	init_connect->features = set_features;
   2665 	if (TWA_64BIT_ADDRESSES) {
   2666 		printf("64 bit addressing supported for scatter/gather list\n");
   2667 		init_connect->features |= TWA_64BIT_SG_ADDRESSES;
   2668 	}
   2669 	if (set_features & TWA_EXTENDED_INIT_CONNECT) {
   2670 		/*
   2671 		 * Fill in the extra fields needed for
   2672 		 * an extended init_connect.
   2673 		 */
   2674 		init_connect->size = 6;
   2675 		init_connect->fw_srl = current_fw_srl;
   2676 		init_connect->fw_arch_id = current_fw_arch_id;
   2677 		init_connect->fw_branch = current_fw_branch;
   2678 	} else
   2679 		init_connect->size = 3;
   2680 
   2681 	/* Submit the command, and wait for it to complete. */
   2682 	error = twa_immediate_request(tr, TWA_REQUEST_TIMEOUT_PERIOD);
   2683 	if (error == ETIMEDOUT)
   2684 		return(error); /* clean-up done by twa_immediate_request */
   2685 	if (error)
   2686 		goto out;
   2687 	if ((error = init_connect->status)) {
   2688 		/* twa_drain_complete_queue will have done the unmapping */
   2689 		goto out;
   2690 	}
   2691 	if (set_features & TWA_EXTENDED_INIT_CONNECT) {
   2692 		*fw_on_ctlr_srl = init_connect->fw_srl;
   2693 		*fw_on_ctlr_arch_id = init_connect->fw_arch_id;
   2694 		*fw_on_ctlr_branch = init_connect->fw_branch;
   2695 		*fw_on_ctlr_build = init_connect->fw_build;
   2696 		*init_connect_result = init_connect->result;
   2697 	}
   2698 	twa_release_request(tr);
   2699 	return(error);
   2700 
   2701 out:
   2702 	if (tr)
   2703 		twa_release_request(tr);
   2704 	return(error);
   2705 }
   2706 
   2707 static int
   2708 twa_reset(struct twa_softc *sc)
   2709 {
   2710 	int	s;
   2711 	int	error = 0;
   2712 
   2713 	/*
   2714 	 * Disable interrupts from the controller, and mask any
   2715 	 * accidental entry into our interrupt handler.
   2716 	 */
   2717 	twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   2718 		TWA_CONTROL_DISABLE_INTERRUPTS);
   2719 
   2720 	s = splbio();
   2721 
   2722 	/* Soft reset the controller. */
   2723 	if ((error = twa_soft_reset(sc)))
   2724 		goto out;
   2725 
   2726 	/* Re-establish logical connection with the controller. */
   2727 	if ((error = twa_init_connection(sc, TWA_INIT_MESSAGE_CREDITS,
   2728 					0, 0, 0, 0, 0,
   2729 					NULL, NULL, NULL, NULL, NULL))) {
   2730 		goto out;
   2731 	}
   2732 	/*
   2733 	 * Complete all requests in the complete queue; error back all requests
   2734 	 * in the busy queue.  Any internal requests will be simply freed.
   2735 	 * Re-submit any requests in the pending queue.
   2736 	 */
   2737 	twa_drain_busy_queue(sc);
   2738 
   2739 out:
   2740 	splx(s);
   2741 	/*
   2742 	 * Enable interrupts, and also clear attention and response interrupts.
   2743 	 */
   2744 	twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   2745 		TWA_CONTROL_CLEAR_ATTENTION_INTERRUPT |
   2746 		TWA_CONTROL_UNMASK_RESPONSE_INTERRUPT |
   2747 		TWA_CONTROL_ENABLE_INTERRUPTS);
   2748 	return(error);
   2749 }
   2750 
   2751 static int
   2752 twa_soft_reset(struct twa_softc *sc)
   2753 {
   2754 	uint32_t	status_reg;
   2755 
   2756 	twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   2757 			TWA_CONTROL_ISSUE_SOFT_RESET |
   2758 			TWA_CONTROL_CLEAR_HOST_INTERRUPT |
   2759 			TWA_CONTROL_CLEAR_ATTENTION_INTERRUPT |
   2760 			TWA_CONTROL_MASK_COMMAND_INTERRUPT |
   2761 			TWA_CONTROL_MASK_RESPONSE_INTERRUPT |
   2762 			TWA_CONTROL_DISABLE_INTERRUPTS);
   2763 
   2764 	if (twa_wait_status(sc, TWA_STATUS_MICROCONTROLLER_READY |
   2765 				TWA_STATUS_ATTENTION_INTERRUPT, 30)) {
   2766 		aprint_error("%s: no attention interrupt after reset.\n",
   2767 			sc->twa_dv.dv_xname);
   2768 		return(1);
   2769 	}
   2770 	twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   2771 		TWA_CONTROL_CLEAR_ATTENTION_INTERRUPT);
   2772 
   2773 	if (twa_drain_response_queue(sc)) {
   2774 		aprint_error("%s: cannot drain response queue.\n",
   2775 		    sc->twa_dv.dv_xname);
   2776 		return(1);
   2777 	}
   2778 	if (twa_drain_aen_queue(sc)) {
   2779 		aprint_error("%s: cannot drain AEN queue.\n",
   2780 		    sc->twa_dv.dv_xname);
   2781 		return(1);
   2782 	}
   2783 	if (twa_find_aen(sc, TWA_AEN_SOFT_RESET)) {
   2784 		aprint_error("%s: reset not reported by controller.\n",
   2785 			 sc->twa_dv.dv_xname);
   2786 		return(1);
   2787 	}
   2788 	status_reg = twa_inl(sc, TWA_STATUS_REGISTER_OFFSET);
   2789 	if (TWA_STATUS_ERRORS(status_reg) ||
   2790 	    twa_check_ctlr_state(sc, status_reg)) {
   2791 		aprint_error("%s: controller errors detected.\n",
   2792 		    sc->twa_dv.dv_xname);
   2793 		return(1);
   2794 	}
   2795 	return(0);
   2796 }
   2797 
   2798 static int
   2799 twa_wait_status(struct twa_softc *sc, uint32_t status, uint32_t timeout)
   2800 {
   2801 	struct timeval		t1;
   2802 	time_t		end_time;
   2803 	uint32_t	status_reg;
   2804 
   2805 	timeout = (timeout * 1000 * 100);
   2806 
   2807 	microtime(&t1);
   2808 
   2809 	end_time = t1.tv_usec + timeout;
   2810 
   2811 	do {
   2812 		status_reg = twa_inl(sc, TWA_STATUS_REGISTER_OFFSET);
   2813 		/* got the required bit(s)? */
   2814 		if ((status_reg & status) == status)
   2815 			return(0);
   2816 		DELAY(100000);
   2817 		microtime(&t1);
   2818 	} while (t1.tv_usec <= end_time);
   2819 
   2820 	return(1);
   2821 }
   2822 
   2823 static int
   2824 twa_fetch_aen(struct twa_softc *sc)
   2825 {
   2826 	struct twa_request	*tr;
   2827 	int			s, error = 0;
   2828 
   2829 	s = splbio();
   2830 
   2831 	if ((tr = twa_get_request(sc, TWA_CMD_AEN)) == NULL) {
   2832 		splx(s);
   2833 		return(EIO);
   2834 	}
   2835 	tr->tr_cmd_pkt_type |= TWA_CMD_PKT_TYPE_INTERNAL;
   2836 	tr->tr_callback = twa_aen_callback;
   2837 	tr->tr_data = malloc(TWA_SECTOR_SIZE, M_DEVBUF, M_NOWAIT);
   2838 	if (twa_request_sense(tr, 0) != 0) {
   2839 		if (tr->tr_data)
   2840 			free(tr->tr_data, M_DEVBUF);
   2841 		twa_release_request(tr);
   2842 		error = 1;
   2843 	}
   2844 	splx(s);
   2845 
   2846 	return(error);
   2847 }
   2848 
   2849 /*
   2850  * Function name:	twa_aen_callback
   2851  * Description:		Callback for requests to fetch AEN's.
   2852  *
   2853  * Input:		tr	-- ptr to completed request pkt
   2854  * Output:		None
   2855  * Return value:	None
   2856  */
   2857 static void
   2858 twa_aen_callback(struct twa_request *tr)
   2859 {
   2860 	int i;
   2861 	int fetch_more_aens = 0;
   2862 	struct twa_softc		*sc = tr->tr_sc;
   2863 	struct twa_command_header	*cmd_hdr =
   2864 		(struct twa_command_header *)(tr->tr_data);
   2865 	struct twa_command_9k		*cmd =
   2866 		&(tr->tr_command->command.cmd_pkt_9k);
   2867 
   2868 	if (! cmd->status) {
   2869 		if ((tr->tr_cmd_pkt_type & TWA_CMD_PKT_TYPE_9K) &&
   2870 			(cmd->cdb[0] == 0x3 /* REQUEST_SENSE */))
   2871 			if (twa_enqueue_aen(sc, cmd_hdr)
   2872 				!= TWA_AEN_QUEUE_EMPTY)
   2873 				fetch_more_aens = 1;
   2874 	} else {
   2875 		cmd_hdr->err_specific_desc[sizeof(cmd_hdr->err_specific_desc) - 1] = '\0';
   2876 		for (i = 0; i < 18; i++)
   2877 			printf("%x\t", tr->tr_command->cmd_hdr.sense_data[i]);
   2878 
   2879 		printf(""); /* print new line */
   2880 
   2881 		for (i = 0; i < 128; i++)
   2882 			printf("%x\t", ((int8_t *)(tr->tr_data))[i]);
   2883 	}
   2884 	if (tr->tr_data)
   2885 		free(tr->tr_data, M_DEVBUF);
   2886 	twa_release_request(tr);
   2887 
   2888 	if (fetch_more_aens)
   2889 		twa_fetch_aen(sc);
   2890 }
   2891 
   2892 /*
   2893  * Function name:	twa_enqueue_aen
   2894  * Description:		Queues AEN's to be supplied to user-space tools on request.
   2895  *
   2896  * Input:		sc	-- ptr to per ctlr structure
   2897  *			cmd_hdr	-- ptr to hdr of fw cmd pkt, from where the AEN
   2898  *				   details can be retrieved.
   2899  * Output:		None
   2900  * Return value:	None
   2901  */
   2902 static uint16_t
   2903 twa_enqueue_aen(struct twa_softc *sc, struct twa_command_header *cmd_hdr)
   2904 {
   2905 	int			rv, s;
   2906 	struct tw_cl_event_packet *event;
   2907 	uint16_t		aen_code;
   2908 	unsigned long		sync_time;
   2909 
   2910 	s = splbio();
   2911 	aen_code = cmd_hdr->status_block.error;
   2912 
   2913 	switch (aen_code) {
   2914 	case TWA_AEN_SYNC_TIME_WITH_HOST:
   2915 
   2916 		sync_time = (time_second - (3 * 86400)) % 604800;
   2917 		rv = twa_set_param(sc, TWA_PARAM_TIME_TABLE,
   2918 				TWA_PARAM_TIME_SchedulerTime, 4,
   2919 				&sync_time, twa_aen_callback);
   2920 #ifdef DIAGNOSTIC
   2921 		if (rv != 0)
   2922 			printf("%s: unable to sync time with ctlr\n",
   2923 				sc->twa_dv.dv_xname);
   2924 #endif
   2925 		break;
   2926 
   2927 	case TWA_AEN_QUEUE_EMPTY:
   2928 		break;
   2929 
   2930 	default:
   2931 		/* Queue the event. */
   2932 		event = sc->twa_aen_queue[sc->twa_aen_head];
   2933 		if (event->retrieved == TWA_AEN_NOT_RETRIEVED)
   2934 			sc->twa_aen_queue_overflow = TRUE;
   2935 		event->severity =
   2936 			cmd_hdr->status_block.substatus_block.severity;
   2937 		event->time_stamp_sec = time_second;
   2938 		event->aen_code = aen_code;
   2939 		event->retrieved = TWA_AEN_NOT_RETRIEVED;
   2940 		event->sequence_id = ++(sc->twa_current_sequence_id);
   2941 		cmd_hdr->err_specific_desc[sizeof(cmd_hdr->err_specific_desc) - 1] = '\0';
   2942 		event->parameter_len = strlen(cmd_hdr->err_specific_desc);
   2943 		memcpy(event->parameter_data, cmd_hdr->err_specific_desc,
   2944 			event->parameter_len);
   2945 
   2946 		if (event->severity < TWA_AEN_SEVERITY_DEBUG) {
   2947 			printf("%s: AEN 0x%04X: %s: %s: %s\n",
   2948 				sc->twa_dv.dv_xname,
   2949 				aen_code,
   2950 				twa_aen_severity_table[event->severity],
   2951 				twa_find_msg_string(twa_aen_table, aen_code),
   2952 				event->parameter_data);
   2953 		}
   2954 
   2955 		if ((sc->twa_aen_head + 1) == TWA_Q_LENGTH)
   2956 			sc->twa_aen_queue_wrapped = TRUE;
   2957 		sc->twa_aen_head = (sc->twa_aen_head + 1) % TWA_Q_LENGTH;
   2958 		break;
   2959 	} /* switch */
   2960 	splx(s);
   2961 
   2962 	return (aen_code);
   2963 }
   2964 
   2965 /*
   2966  * Function name:	twa_find_aen
   2967  * Description:		Reports whether a given AEN ever occurred.
   2968  *
   2969  * Input:		sc	-- ptr to per ctlr structure
   2970  *			aen_code-- AEN to look for
   2971  * Output:		None
   2972  * Return value:	0	-- success
   2973  *			non-zero-- failure
   2974  */
   2975 static int
   2976 twa_find_aen(struct twa_softc *sc, uint16_t aen_code)
   2977 {
   2978 	uint32_t	last_index;
   2979 	int		s;
   2980 	int		i;
   2981 
   2982 	s = splbio();
   2983 
   2984 	if (sc->twa_aen_queue_wrapped)
   2985 		last_index = sc->twa_aen_head;
   2986 	else
   2987 		last_index = 0;
   2988 
   2989 	i = sc->twa_aen_head;
   2990 	do {
   2991 		i = (i + TWA_Q_LENGTH - 1) % TWA_Q_LENGTH;
   2992 		if ((sc->twa_aen_queue[i])->aen_code == aen_code) {
   2993 			splx(s);
   2994 			return(0);
   2995 		}
   2996 	} while (i != last_index);
   2997 
   2998 	splx(s);
   2999 	return(1);
   3000 }
   3001 
   3002 static void inline
   3003 twa_request_init(struct twa_request *tr, int flags)
   3004 {
   3005 	tr->tr_data = NULL;
   3006 	tr->tr_real_data = NULL;
   3007 	tr->tr_length = 0;
   3008 	tr->tr_real_length = 0;
   3009 	tr->tr_status = TWA_CMD_SETUP;/* command is in setup phase */
   3010 	tr->tr_flags = flags;
   3011 	tr->tr_error = 0;
   3012 	tr->tr_callback = NULL;
   3013 	tr->tr_cmd_pkt_type = 0;
   3014 	tr->bp = 0;
   3015 
   3016 	/*
   3017 	 * Look at the status field in the command packet to see how
   3018 	 * it completed the last time it was used, and zero out only
   3019 	 * the portions that might have changed.  Note that we don't
   3020 	 * care to zero out the sglist.
   3021 	 */
   3022 	if (tr->tr_command->command.cmd_pkt_9k.status)
   3023 		memset(tr->tr_command, 0,
   3024 			sizeof(struct twa_command_header) + 28);
   3025 	else
   3026 		memset(&(tr->tr_command->command), 0, 28);
   3027 }
   3028 
   3029 struct twa_request *
   3030 twa_get_request_wait(struct twa_softc *sc, int flags)
   3031 {
   3032 	struct twa_request *tr;
   3033 	int s;
   3034 
   3035 	KASSERT((flags & TWA_CMD_AEN) == 0);
   3036 
   3037 	s = splbio();
   3038 	while ((tr = TAILQ_FIRST(&sc->twa_free)) == NULL) {
   3039 		sc->twa_sc_flags |= TWA_STATE_REQUEST_WAIT;
   3040 		(void) tsleep(&sc->twa_free, PRIBIO, "twaccb", hz);
   3041 	}
   3042 	TAILQ_REMOVE(&sc->twa_free, tr, tr_link);
   3043 
   3044 	splx(s);
   3045 
   3046 	twa_request_init(tr, flags);
   3047 
   3048 	return(tr);
   3049 }
   3050 
   3051 struct twa_request *
   3052 twa_get_request(struct twa_softc *sc, int flags)
   3053 {
   3054 	int s;
   3055 	struct twa_request *tr;
   3056 
   3057 	/* Get a free request packet. */
   3058 	s = splbio();
   3059 	if (__predict_false((flags & TWA_CMD_AEN) != 0)) {
   3060 
   3061 		if ((sc->sc_twa_request->tr_flags & TWA_CMD_AEN_BUSY) == 0) {
   3062 			tr = sc->sc_twa_request;
   3063 			flags |= TWA_CMD_AEN_BUSY;
   3064 		} else {
   3065 			splx(s);
   3066 			return (NULL);
   3067 		}
   3068 	} else {
   3069 		if (__predict_false((tr =
   3070 				TAILQ_FIRST(&sc->twa_free)) == NULL)) {
   3071 			splx(s);
   3072 			return (NULL);
   3073 		}
   3074 		TAILQ_REMOVE(&sc->twa_free, tr, tr_link);
   3075 	}
   3076 	splx(s);
   3077 
   3078 	twa_request_init(tr, flags);
   3079 
   3080 	return(tr);
   3081 }
   3082 
   3083 /*
   3084  * Print some information about the controller
   3085  */
   3086 static void
   3087 twa_describe_controller(struct twa_softc *sc)
   3088 {
   3089 	struct twa_param_9k	*p[10];
   3090 	int			i, rv = 0;
   3091 	uint32_t		dsize;
   3092 	uint8_t			ports;
   3093 
   3094 	memset(p, sizeof(struct twa_param_9k *), 10);
   3095 
   3096 	/* Get the port count. */
   3097 	rv |= twa_get_param(sc, TWA_PARAM_CONTROLLER,
   3098 		TWA_PARAM_CONTROLLER_PortCount, 1, NULL, &p[0]);
   3099 
   3100 	/* get version strings */
   3101 	rv |= twa_get_param(sc, TWA_PARAM_VERSION, TWA_PARAM_VERSION_FW,
   3102 		16, NULL, &p[1]);
   3103 	rv |= twa_get_param(sc, TWA_PARAM_VERSION, TWA_PARAM_VERSION_BIOS,
   3104 		16, NULL, &p[2]);
   3105 	rv |= twa_get_param(sc, TWA_PARAM_VERSION, TWA_PARAM_VERSION_Mon,
   3106 		16, NULL, &p[3]);
   3107 	rv |= twa_get_param(sc, TWA_PARAM_VERSION, TWA_PARAM_VERSION_PCBA,
   3108 		8, NULL, &p[4]);
   3109 	rv |= twa_get_param(sc, TWA_PARAM_VERSION, TWA_PARAM_VERSION_ATA,
   3110 		8, NULL, &p[5]);
   3111 	rv |= twa_get_param(sc, TWA_PARAM_VERSION, TWA_PARAM_VERSION_PCI,
   3112 		8, NULL, &p[6]);
   3113 	rv |= twa_get_param(sc, TWA_PARAM_DRIVESUMMARY, TWA_PARAM_DRIVESTATUS,
   3114 		16, NULL, &p[7]);
   3115 
   3116 	if (rv) {
   3117 		/* some error occurred */
   3118 		aprint_error("%s: failed to fetch version information\n",
   3119 			sc->twa_dv.dv_xname);
   3120 		goto bail;
   3121 	}
   3122 
   3123 	ports = *(uint8_t *)(p[0]->data);
   3124 
   3125 	aprint_normal("%s: %d ports, Firmware %.16s, BIOS %.16s\n",
   3126 		sc->twa_dv.dv_xname, ports,
   3127 		p[1]->data, p[2]->data);
   3128 
   3129 	aprint_verbose("%s: Monitor %.16s, PCB %.8s, Achip %.8s, Pchip %.8s\n",
   3130 		sc->twa_dv.dv_xname,
   3131 		p[3]->data, p[4]->data,
   3132 		p[5]->data, p[6]->data);
   3133 
   3134 	for (i = 0; i < ports; i++) {
   3135 
   3136 		if ((*((char *)(p[7]->data + i)) & TWA_DRIVE_DETECTED) == 0)
   3137 			continue;
   3138 
   3139 		rv = twa_get_param(sc, TWA_PARAM_DRIVE_TABLE,
   3140 			TWA_PARAM_DRIVEMODELINDEX,
   3141 			TWA_PARAM_DRIVEMODEL_LENGTH, NULL, &p[8]);
   3142 
   3143 		if (rv != 0) {
   3144 			aprint_error("%s: unable to get drive model for port"
   3145 				" %d\n", sc->twa_dv.dv_xname, i);
   3146 			continue;
   3147 		}
   3148 
   3149 		rv = twa_get_param(sc, TWA_PARAM_DRIVE_TABLE,
   3150 			TWA_PARAM_DRIVESIZEINDEX,
   3151 			TWA_PARAM_DRIVESIZE_LENGTH, NULL, &p[9]);
   3152 
   3153 		if (rv != 0) {
   3154 			aprint_error("%s: unable to get drive size"
   3155 				" for port %d\n", sc->twa_dv.dv_xname,
   3156 					i);
   3157 			free(p[8], M_DEVBUF);
   3158 			continue;
   3159 		}
   3160 
   3161 		dsize = *(uint32_t *)(p[9]->data);
   3162 
   3163 		aprint_verbose("%s: port %d: %.40s %d MB\n",
   3164 		    sc->twa_dv.dv_xname, i, p[8]->data, dsize / 2048);
   3165 
   3166 		if (p[8])
   3167 			free(p[8], M_DEVBUF);
   3168 		if (p[9])
   3169 			free(p[9], M_DEVBUF);
   3170 	}
   3171 bail:
   3172 	if (p[0])
   3173 		free(p[0], M_DEVBUF);
   3174 	if (p[1])
   3175 		free(p[1], M_DEVBUF);
   3176 	if (p[2])
   3177 		free(p[2], M_DEVBUF);
   3178 	if (p[3])
   3179 		free(p[3], M_DEVBUF);
   3180 	if (p[4])
   3181 		free(p[4], M_DEVBUF);
   3182 	if (p[5])
   3183 		free(p[5], M_DEVBUF);
   3184 	if (p[6])
   3185 		free(p[6], M_DEVBUF);
   3186 }
   3187 
   3188 /*
   3189  * Function name:	twa_check_ctlr_state
   3190  * Description:		Makes sure that the fw status register reports a
   3191  *			proper status.
   3192  *
   3193  * Input:		sc		-- ptr to per ctlr structure
   3194  *			status_reg	-- value in the status register
   3195  * Output:		None
   3196  * Return value:	0	-- no errors
   3197  *			non-zero-- errors
   3198  */
   3199 static int
   3200 twa_check_ctlr_state(struct twa_softc *sc, uint32_t status_reg)
   3201 {
   3202 	int		result = 0;
   3203 	struct timeval	t1;
   3204 	static time_t	last_warning[2] = {0, 0};
   3205 
   3206 	/* Check if the 'micro-controller ready' bit is not set. */
   3207 	if ((status_reg & TWA_STATUS_EXPECTED_BITS) !=
   3208 				TWA_STATUS_EXPECTED_BITS) {
   3209 
   3210 		microtime(&t1);
   3211 
   3212 		last_warning[0] += (5 * 1000 * 100);
   3213 
   3214 		if (t1.tv_usec > last_warning[0]) {
   3215 			microtime(&t1);
   3216 			last_warning[0] = t1.tv_usec;
   3217 		}
   3218 		result = 1;
   3219 	}
   3220 
   3221 	/* Check if any error bits are set. */
   3222 	if ((status_reg & TWA_STATUS_UNEXPECTED_BITS) != 0) {
   3223 
   3224 		microtime(&t1);
   3225 		last_warning[1] += (5 * 1000 * 100);
   3226 		if (t1.tv_usec > last_warning[1]) {
   3227 		     	microtime(&t1);
   3228 			last_warning[1] = t1.tv_usec;
   3229 		}
   3230 		if (status_reg & TWA_STATUS_PCI_PARITY_ERROR_INTERRUPT) {
   3231 			aprint_error("%s: clearing PCI parity error "
   3232 				"re-seat/move/replace card.\n",
   3233 				 sc->twa_dv.dv_xname);
   3234 			twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   3235 				TWA_CONTROL_CLEAR_PARITY_ERROR);
   3236 			pci_conf_write(sc->pc, sc->tag,
   3237 				PCI_COMMAND_STATUS_REG,
   3238 				TWA_PCI_CONFIG_CLEAR_PARITY_ERROR);
   3239 			result = 1;
   3240 		}
   3241 		if (status_reg & TWA_STATUS_PCI_ABORT_INTERRUPT) {
   3242 			aprint_error("%s: clearing PCI abort\n",
   3243 				sc->twa_dv.dv_xname);
   3244 			twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   3245 				TWA_CONTROL_CLEAR_PCI_ABORT);
   3246 			pci_conf_write(sc->pc, sc->tag,
   3247 				PCI_COMMAND_STATUS_REG,
   3248 				TWA_PCI_CONFIG_CLEAR_PCI_ABORT);
   3249 			result = 1;
   3250 		}
   3251 		if (status_reg & TWA_STATUS_QUEUE_ERROR_INTERRUPT) {
   3252 			aprint_error("%s: clearing controller queue error\n",
   3253 				sc->twa_dv.dv_xname);
   3254 			twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   3255 				TWA_CONTROL_CLEAR_PCI_ABORT);
   3256 			result = 1;
   3257 		}
   3258 		if (status_reg & TWA_STATUS_SBUF_WRITE_ERROR) {
   3259 			aprint_error("%s: clearing SBUF write error\n",
   3260 				sc->twa_dv.dv_xname);
   3261 			twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   3262 				TWA_CONTROL_CLEAR_SBUF_WRITE_ERROR);
   3263 			result = 1;
   3264 		}
   3265 		if (status_reg & TWA_STATUS_MICROCONTROLLER_ERROR) {
   3266 			aprint_error("%s: micro-controller error\n",
   3267 				sc->twa_dv.dv_xname);
   3268 			result = 1;
   3269 		}
   3270 	}
   3271 	return(result);
   3272 }
   3273