Home | History | Annotate | Line # | Download | only in pci
twa.c revision 1.7
      1 /*	$NetBSD: twa.c,v 1.7 2006/07/11 00:25:42 simonb Exp $ */
      2 /*	$wasabi: twa.c,v 1.25 2006/05/01 15:16:59 simonb 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.7 2006/07/11 00:25:42 simonb 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, error;
    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 	if ((error = twa_map_request(tr)))
    552 		return (error);
    553 
    554 	microtime(&t1);
    555 	end_time = t1.tv_usec +
    556 		(timeout * 1000 * 100);
    557 
    558 	while (tr->tr_status != TWA_CMD_COMPLETE) {
    559 		if ((error = tr->tr_error))
    560 			return(error);
    561 		if ((error = tsleep(tr, PRIBIO, "twawait", timeout * hz)) == 0)
    562 		{
    563 			error = (tr->tr_status != TWA_CMD_COMPLETE);
    564 			break;
    565 		}
    566 		if (error == EWOULDBLOCK) {
    567 			/*
    568 			 * We will reset the controller only if the request has
    569 			 * already been submitted, so as to not lose the
    570 			 * request packet.  If a busy request timed out, the
    571 			 * reset will take care of freeing resources.  If a
    572 			 * pending request timed out, we will free resources
    573 			 * for that request, right here.  So, the caller is
    574 			 * expected to NOT cleanup when ETIMEDOUT is returned.
    575 			 */
    576 			if (tr->tr_status != TWA_CMD_PENDING &&
    577 			    tr->tr_status != TWA_CMD_COMPLETE)
    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 	twa_unmap_request(tr);
    604 	return(error);
    605 }
    606 
    607 /*
    608  * Function name:	twa_immediate_request
    609  * Description:		Sends down a firmware cmd, and waits for the completion
    610  *			in a tight loop.
    611  *
    612  * Input:		tr	-- ptr to request pkt
    613  *			timeout -- max # of seconds to wait before giving up
    614  * Output:		None
    615  * Return value:	0	-- success
    616  *			non-zero-- failure
    617  */
    618 static int
    619 twa_immediate_request(struct twa_request *tr, uint32_t timeout)
    620 {
    621 	struct timeval t1;
    622 	int	s = 0, error = 0;
    623 
    624 	if ((error = twa_map_request(tr))) {
    625 		return(error);
    626 	}
    627 
    628 	timeout = (timeout * 10000 * 10);
    629 
    630 	microtime(&t1);
    631 
    632 	timeout += t1.tv_usec;
    633 
    634 	do {
    635 		if ((error = tr->tr_error))
    636 			return(error);
    637 		twa_done(tr->tr_sc);
    638 		if ((tr->tr_status != TWA_CMD_BUSY) &&
    639 			(tr->tr_status != TWA_CMD_PENDING)) {
    640 			twa_unmap_request(tr);
    641 			return(tr->tr_status != TWA_CMD_COMPLETE);
    642 		}
    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 	if (tr->tr_status != TWA_CMD_PENDING)
    656 		twa_reset(tr->tr_sc);
    657 	else {
    658 		/* Request was never submitted.  Clean up. */
    659 		s = splbio();
    660 		TAILQ_REMOVE(&tr->tr_sc->twa_pending, tr, tr_link);
    661 		splx(s);
    662 		twa_unmap_request(tr);
    663 		if (tr->tr_data)
    664 			free(tr->tr_data, M_DEVBUF);
    665 
    666 		twa_release_request(tr);
    667 	}
    668 	return(ETIMEDOUT);
    669 }
    670 
    671 static int
    672 twa_inquiry(struct twa_request *tr, int lunid)
    673 {
    674 	int error;
    675 	struct twa_command_9k *tr_9k_cmd;
    676 
    677 	if (tr->tr_data == NULL)
    678 		return (ENOMEM);
    679 
    680 	memset(tr->tr_data, 0, TWA_SECTOR_SIZE);
    681 
    682 	tr->tr_length = TWA_SECTOR_SIZE;
    683 	tr->tr_cmd_pkt_type = TWA_CMD_PKT_TYPE_9K;
    684 	tr->tr_flags |= TWA_CMD_DATA_IN;
    685 
    686 	tr_9k_cmd = &tr->tr_command->command.cmd_pkt_9k;
    687 
    688 	tr_9k_cmd->command.opcode = TWA_OP_EXECUTE_SCSI_COMMAND;
    689 	tr_9k_cmd->unit = lunid;
    690 	tr_9k_cmd->request_id = tr->tr_request_id;
    691 	tr_9k_cmd->status = 0;
    692 	tr_9k_cmd->sgl_offset = 16;
    693 	tr_9k_cmd->sgl_entries = 1;
    694 	/* create the CDB here */
    695 	tr_9k_cmd->cdb[0] = INQUIRY;
    696 	tr_9k_cmd->cdb[1] = ((lunid << 5) & 0x0e);
    697 	tr_9k_cmd->cdb[4] = 255;
    698 
    699 	/* XXXX setup page data no lun device
    700 	 * it seems 9000 series does not indicate
    701 	 * NOTPRESENT - need more investigation
    702 	 */
    703 	((struct scsipi_inquiry_data *)tr->tr_data)->device =
    704 		SID_QUAL_LU_NOTPRESENT;
    705 
    706 	error = twa_immediate_request(tr, TWA_REQUEST_TIMEOUT_PERIOD);
    707 
    708 	if (((struct scsipi_inquiry_data *)tr->tr_data)->device ==
    709 		SID_QUAL_LU_NOTPRESENT)
    710 		error = 1;
    711 
    712 	return (error);
    713 }
    714 
    715 static int
    716 twa_print_inquiry_data(struct twa_softc *sc, struct scsipi_inquiry_data *scsipi)
    717 {
    718 
    719     printf("%s: %s\n", sc->twa_dv.dv_xname, scsipi->vendor);
    720 
    721     return (1);
    722 }
    723 
    724 
    725 static uint64_t
    726 twa_read_capacity(struct twa_request *tr, int lunid)
    727 {
    728 	int error;
    729 	struct twa_command_9k *tr_9k_cmd;
    730 	uint64_t array_size = 0LL;
    731 
    732 	if (tr->tr_data == NULL)
    733 		return (ENOMEM);
    734 
    735 	memset(tr->tr_data, 0, TWA_SECTOR_SIZE);
    736 
    737 	tr->tr_length = TWA_SECTOR_SIZE;
    738 	tr->tr_cmd_pkt_type = TWA_CMD_PKT_TYPE_9K;
    739 	tr->tr_flags |= TWA_CMD_DATA_OUT;
    740 
    741 	tr_9k_cmd = &tr->tr_command->command.cmd_pkt_9k;
    742 
    743 	tr_9k_cmd->command.opcode = TWA_OP_EXECUTE_SCSI_COMMAND;
    744 	tr_9k_cmd->unit = lunid;
    745 	tr_9k_cmd->request_id = tr->tr_request_id;
    746 	tr_9k_cmd->status = 0;
    747 	tr_9k_cmd->sgl_offset = 16;
    748 	tr_9k_cmd->sgl_entries = 1;
    749 	/* create the CDB here */
    750 	tr_9k_cmd->cdb[0] = READ_CAPACITY_16;
    751 	tr_9k_cmd->cdb[1] = ((lunid << 5) & 0x0e) | SRC16_SERVICE_ACTION;
    752 
    753 	error = twa_immediate_request(tr, TWA_REQUEST_TIMEOUT_PERIOD);
    754 #if BYTE_ORDER == BIG_ENDIAN
    755 	array_size = bswap64(_8btol(((struct scsipi_read_capacity_16_data *)
    756 				tr->tr_data)->addr) + 1);
    757 #else
    758 	array_size = _8btol(((struct scsipi_read_capacity_16_data *)
    759 				tr->tr_data)->addr) + 1;
    760 #endif
    761 	return (array_size);
    762 }
    763 
    764 static int
    765 twa_request_sense(struct twa_request *tr, int lunid)
    766 {
    767 	int error = 1;
    768 	struct twa_command_9k *tr_9k_cmd;
    769 
    770 	if (tr->tr_data == NULL)
    771 		return (error);
    772 
    773 	memset(tr->tr_data, 0, TWA_SECTOR_SIZE);
    774 
    775 	tr->tr_length = TWA_SECTOR_SIZE;
    776 	tr->tr_cmd_pkt_type = TWA_CMD_PKT_TYPE_9K;
    777 	tr->tr_flags |= TWA_CMD_DATA_OUT;
    778 
    779 	tr_9k_cmd = &tr->tr_command->command.cmd_pkt_9k;
    780 
    781 	tr_9k_cmd->command.opcode = TWA_OP_EXECUTE_SCSI_COMMAND;
    782 	tr_9k_cmd->unit = lunid;
    783 	tr_9k_cmd->request_id = tr->tr_request_id;
    784 	tr_9k_cmd->status = 0;
    785 	tr_9k_cmd->sgl_offset = 16;
    786 	tr_9k_cmd->sgl_entries = 1;
    787 	/* create the CDB here */
    788 	tr_9k_cmd->cdb[0] = SCSI_REQUEST_SENSE;
    789 	tr_9k_cmd->cdb[1] = ((lunid << 5) & 0x0e);
    790 	tr_9k_cmd->cdb[4] = 255;
    791 
    792 	/*XXX AEN notification called in interrupt context
    793 	 * so just queue the request. Return as quickly
    794 	 * as possible from interrupt
    795 	 */
    796 	if ((tr->tr_flags & TWA_CMD_AEN) != 0)
    797 		error = twa_map_request(tr);
    798  	else
    799 		error = twa_immediate_request(tr, TWA_REQUEST_TIMEOUT_PERIOD);
    800 
    801 	return (error);
    802 }
    803 
    804 static int
    805 twa_alloc_req_pkts(struct twa_softc *sc, int num_reqs)
    806 {
    807 	struct twa_request	*tr;
    808 	struct twa_command_packet *tc;
    809 	bus_dma_segment_t	seg;
    810 	size_t max_segs, max_xfer;
    811 	int	i, rv, rseg, size;
    812 
    813 	if ((sc->twa_req_buf = malloc(num_reqs * sizeof(struct twa_request),
    814 					M_DEVBUF, M_NOWAIT)) == NULL)
    815 		return(ENOMEM);
    816 
    817 	size = num_reqs * sizeof(struct twa_command_packet);
    818 
    819 	/* Allocate memory for cmd pkts. */
    820 	if ((rv = bus_dmamem_alloc(sc->twa_dma_tag,
    821 		size, PAGE_SIZE, 0, &seg,
    822 		1, &rseg, BUS_DMA_NOWAIT)) != 0){
    823 			aprint_error("%s: unable to allocate "
    824 				"command packets, rv = %d\n",
    825 				sc->twa_dv.dv_xname, rv);
    826 			return (ENOMEM);
    827 	}
    828 
    829 	if ((rv = bus_dmamem_map(sc->twa_dma_tag,
    830 		&seg, rseg, size, (caddr_t *)&sc->twa_cmds,
    831 		BUS_DMA_NOWAIT | BUS_DMA_COHERENT)) != 0) {
    832 			aprint_error("%s: unable to map commands, rv = %d\n",
    833 				sc->twa_dv.dv_xname, rv);
    834 			return (1);
    835 	}
    836 
    837 	if ((rv = bus_dmamap_create(sc->twa_dma_tag,
    838 		size, num_reqs, size,
    839 		0, BUS_DMA_NOWAIT, &sc->twa_cmd_map)) != 0) {
    840 			aprint_error("%s: unable to create command DMA map, "
    841 				"rv = %d\n", sc->twa_dv.dv_xname, rv);
    842 			return (ENOMEM);
    843 	}
    844 
    845 	if ((rv = bus_dmamap_load(sc->twa_dma_tag, sc->twa_cmd_map,
    846 		sc->twa_cmds, size, NULL,
    847 		BUS_DMA_NOWAIT)) != 0) {
    848 			aprint_error("%s: unable to load command DMA map, "
    849 				"rv = %d\n", sc->twa_dv.dv_xname, rv);
    850 			return (1);
    851 	}
    852 
    853 	if ((uintptr_t)sc->twa_cmds % TWA_ALIGNMENT) {
    854 		aprint_error("%s: DMA map memory not aligned on %d boundary\n",
    855 			sc->twa_dv.dv_xname, TWA_ALIGNMENT);
    856 
    857 		return (1);
    858 	}
    859 	tc = sc->twa_cmd_pkt_buf = (struct twa_command_packet *)sc->twa_cmds;
    860 	sc->twa_cmd_pkt_phys = sc->twa_cmd_map->dm_segs[0].ds_addr;
    861 
    862 	memset(sc->twa_req_buf, 0, num_reqs * sizeof(struct twa_request));
    863 	memset(sc->twa_cmd_pkt_buf, 0,
    864 		num_reqs * sizeof(struct twa_command_packet));
    865 
    866 	sc->sc_twa_request = sc->twa_req_buf;
    867 	max_segs = twa_get_maxsegs();
    868 	max_xfer = twa_get_maxxfer(max_segs);
    869 
    870 	for (i = 0; i < num_reqs; i++, tc++) {
    871 		tr = &(sc->twa_req_buf[i]);
    872 		tr->tr_command = tc;
    873 		tr->tr_cmd_phys = sc->twa_cmd_pkt_phys +
    874 				(i * sizeof(struct twa_command_packet));
    875 		tr->tr_request_id = i;
    876 		tr->tr_sc = sc;
    877 
    878 		/*
    879 		 * Create a map for data buffers.  maxsize (256 * 1024) used in
    880 		 * bus_dma_tag_create above should suffice the bounce page needs
    881 		 * for data buffers, since the max I/O size we support is 128KB.
    882 		 * If we supported I/O's bigger than 256KB, we would have to
    883 		 * create a second dma_tag, with the appropriate maxsize.
    884 		 */
    885 		if ((rv = bus_dmamap_create(sc->twa_dma_tag,
    886 			max_xfer, max_segs, 1, 0, BUS_DMA_NOWAIT,
    887 			&tr->tr_dma_map)) != 0) {
    888 				aprint_error("%s: unable to create command "
    889 					"DMA map, rv = %d\n",
    890 					sc->twa_dv.dv_xname, rv);
    891 				return (ENOMEM);
    892 		}
    893 		/* Insert request into the free queue. */
    894 		if (i != 0) {
    895 			sc->twa_lookup[i] = tr;
    896 			twa_release_request(tr);
    897 		} else
    898 			tr->tr_flags |= TWA_CMD_AEN;
    899 	}
    900 	return(0);
    901 }
    902 
    903 static void
    904 twa_recompute_openings(struct twa_softc *sc)
    905 {
    906 	struct twa_drive *td;
    907 	int unit;
    908 	int openings;
    909 
    910 	if (sc->sc_nunits != 0)
    911 		openings = ((TWA_Q_LENGTH / 2) / sc->sc_nunits);
    912 	else
    913 		openings = 0;
    914 	if (openings == sc->sc_openings)
    915 		return;
    916 	sc->sc_openings = openings;
    917 
    918 #ifdef TWA_DEBUG
    919 	printf("%s: %d array%s, %d openings per array\n",
    920 	    sc->sc_twa.dv_xname, sc->sc_nunits,
    921 	    sc->sc_nunits == 1 ? "" : "s", sc->sc_openings);
    922 #endif
    923 	for (unit = 0; unit < TWA_MAX_UNITS; unit++) {
    924 		td = &sc->sc_units[unit];
    925 		if (td->td_dev != NULL)
    926 			(*td->td_callbacks->tcb_openings)(td->td_dev,
    927 				sc->sc_openings);
    928 	}
    929 }
    930 
    931 static int
    932 twa_request_bus_scan(struct twa_softc *sc)
    933 {
    934 	struct twa_drive *td;
    935 	struct twa_request *tr;
    936 	struct twa_attach_args twaa;
    937 	int locs[TWACF_NLOCS];
    938 	int s, unit;
    939 
    940 	s = splbio();
    941 	for (unit = 0; unit < TWA_MAX_UNITS; unit++) {
    942 
    943 		if ((tr = twa_get_request(sc, 0)) == NULL) {
    944 			splx(s);
    945 			return (EIO);
    946 		}
    947 
    948 		tr->tr_cmd_pkt_type |= TWA_CMD_PKT_TYPE_INTERNAL;
    949 
    950 		tr->tr_data = malloc(TWA_SECTOR_SIZE, M_DEVBUF, M_NOWAIT);
    951 
    952 		if (tr->tr_data == NULL) {
    953 			twa_release_request(tr);
    954 			splx(s);
    955 			return (ENOMEM);
    956 		}
    957 		td = &sc->sc_units[unit];
    958 
    959 		if (twa_inquiry(tr, unit) == 0) {
    960 			if (td->td_dev == NULL) {
    961             			twa_print_inquiry_data(sc,
    962 				   ((struct scsipi_inquiry_data *)tr->tr_data));
    963 
    964 				sc->sc_nunits++;
    965 
    966 				sc->sc_units[unit].td_size =
    967 					twa_read_capacity(tr, unit);
    968 
    969 				twaa.twaa_unit = unit;
    970 
    971 				twa_recompute_openings(sc);
    972 
    973 				locs[TWACF_UNIT] = unit;
    974 
    975 				sc->sc_units[unit].td_dev =
    976 				    config_found_sm_loc(&sc->twa_dv, "twa",
    977 				    locs, &twaa, twa_print, config_stdsubmatch);
    978 			}
    979 		} else {
    980 			if (td->td_dev != NULL) {
    981 				sc->sc_nunits--;
    982 
    983 				(void) config_detach(td->td_dev, DETACH_FORCE);
    984 				td->td_dev = NULL;
    985 				td->td_size = 0;
    986 
    987 				twa_recompute_openings(sc);
    988 			}
    989 		}
    990 		free(tr->tr_data, M_DEVBUF);
    991 
    992 		twa_release_request(tr);
    993 	}
    994 	splx(s);
    995 
    996 	return (0);
    997 }
    998 
    999 static int
   1000 twa_start(struct twa_request *tr)
   1001 {
   1002 	struct twa_softc	*sc = tr->tr_sc;
   1003 	uint32_t		status_reg;
   1004 	int			s;
   1005 	int			error;
   1006 
   1007 	s = splbio();
   1008 	/* Check to see if we can post a command. */
   1009 	status_reg = twa_inl(sc, TWA_STATUS_REGISTER_OFFSET);
   1010 	if ((error = twa_check_ctlr_state(sc, status_reg)))
   1011 		goto out;
   1012 
   1013 	if (status_reg & TWA_STATUS_COMMAND_QUEUE_FULL) {
   1014 			if (tr->tr_status != TWA_CMD_PENDING) {
   1015 				tr->tr_status = TWA_CMD_PENDING;
   1016 				TAILQ_INSERT_TAIL(&tr->tr_sc->twa_pending,
   1017 					tr, tr_link);
   1018 			}
   1019 			twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   1020 					TWA_CONTROL_UNMASK_COMMAND_INTERRUPT);
   1021 			error = EBUSY;
   1022 	} else {
   1023 	   	bus_dmamap_sync(sc->twa_dma_tag, sc->twa_cmd_map,
   1024 			(caddr_t)tr->tr_command - sc->twa_cmds,
   1025 			sizeof(struct twa_command_packet),
   1026 			BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
   1027 
   1028 		/* Cmd queue is not full.  Post the command. */
   1029 		TWA_WRITE_COMMAND_QUEUE(sc, tr->tr_cmd_phys +
   1030 			sizeof(struct twa_command_header));
   1031 
   1032 		/* Mark the request as currently being processed. */
   1033 		tr->tr_status = TWA_CMD_BUSY;
   1034 		/* Move the request into the busy queue. */
   1035 		TAILQ_INSERT_TAIL(&tr->tr_sc->twa_busy, tr, tr_link);
   1036 	}
   1037 out:
   1038 	splx(s);
   1039 	return(error);
   1040 }
   1041 
   1042 static int
   1043 twa_drain_response_queue(struct twa_softc *sc)
   1044 {
   1045 	union twa_response_queue	rq;
   1046 	uint32_t			status_reg;
   1047 
   1048 	for (;;) {
   1049 		status_reg = twa_inl(sc, TWA_STATUS_REGISTER_OFFSET);
   1050 		if (twa_check_ctlr_state(sc, status_reg))
   1051 			return(1);
   1052 		if (status_reg & TWA_STATUS_RESPONSE_QUEUE_EMPTY)
   1053 			return(0); /* no more response queue entries */
   1054 		rq = (union twa_response_queue)twa_inl(sc,
   1055 		    TWA_RESPONSE_QUEUE_OFFSET);
   1056 	}
   1057 }
   1058 
   1059 static void
   1060 twa_drain_busy_queue(struct twa_softc *sc)
   1061 {
   1062 	struct twa_request	*tr;
   1063 
   1064 	/* Walk the busy queue. */
   1065 
   1066 	while ((tr = TAILQ_FIRST(&sc->twa_busy)) != NULL) {
   1067 		TAILQ_REMOVE(&sc->twa_busy, tr, tr_link);
   1068 
   1069 		twa_unmap_request(tr);
   1070 		if ((tr->tr_cmd_pkt_type & TWA_CMD_PKT_TYPE_INTERNAL) ||
   1071 			(tr->tr_cmd_pkt_type & TWA_CMD_PKT_TYPE_IOCTL)) {
   1072 			/* It's an internal/ioctl request.  Simply free it. */
   1073 			if (tr->tr_data)
   1074 				free(tr->tr_data, M_DEVBUF);
   1075 			twa_release_request(tr);
   1076 		} else {
   1077 			/* It's a SCSI request.  Complete it. */
   1078 			tr->tr_command->command.cmd_pkt_9k.status = EIO;
   1079 			if (tr->tr_callback)
   1080 				tr->tr_callback(tr);
   1081 		}
   1082 	}
   1083 }
   1084 
   1085 static int
   1086 twa_drain_pending_queue(struct twa_softc *sc)
   1087 {
   1088 	struct twa_request	*tr;
   1089 	int			s, error = 0;
   1090 
   1091 	/*
   1092 	 * Pull requests off the pending queue, and submit them.
   1093 	 */
   1094 	s = splbio();
   1095 	while ((tr = TAILQ_FIRST(&sc->twa_pending)) != NULL) {
   1096 		TAILQ_REMOVE(&sc->twa_pending, tr, tr_link);
   1097 
   1098 		if ((error = twa_start(tr))) {
   1099 			if (error == EBUSY) {
   1100 				tr->tr_status = TWA_CMD_PENDING;
   1101 
   1102 				/* queue at the head */
   1103 				TAILQ_INSERT_HEAD(&tr->tr_sc->twa_pending,
   1104 					tr, tr_link);
   1105 				error = 0;
   1106 				break;
   1107 			} else {
   1108 				if (tr->tr_flags & TWA_CMD_SLEEP_ON_REQUEST) {
   1109 					tr->tr_error = error;
   1110 					tr->tr_callback(tr);
   1111 					error = EIO;
   1112 				}
   1113 			}
   1114 		}
   1115 	}
   1116 	splx(s);
   1117 
   1118 	return(error);
   1119 }
   1120 
   1121 static int
   1122 twa_drain_aen_queue(struct twa_softc *sc)
   1123 {
   1124 	int				error = 0;
   1125 	struct twa_request		*tr;
   1126 	struct twa_command_header	*cmd_hdr;
   1127 	struct timeval	t1;
   1128 	uint32_t		timeout;
   1129 
   1130 	for (;;) {
   1131 		if ((tr = twa_get_request(sc, 0)) == NULL) {
   1132 			error = EIO;
   1133 			break;
   1134 		}
   1135 		tr->tr_cmd_pkt_type |= TWA_CMD_PKT_TYPE_INTERNAL;
   1136 		tr->tr_callback = NULL;
   1137 
   1138 		tr->tr_data = malloc(TWA_SECTOR_SIZE, M_DEVBUF, M_NOWAIT);
   1139 
   1140 		if (tr->tr_data == NULL) {
   1141 			error = 1;
   1142 			goto out;
   1143 		}
   1144 
   1145 		if (twa_request_sense(tr, 0) != 0) {
   1146 			error = 1;
   1147 			break;
   1148 		}
   1149 
   1150 		timeout = (1000/*ms*/ * 100/*us*/ * TWA_REQUEST_TIMEOUT_PERIOD);
   1151 
   1152 		microtime(&t1);
   1153 
   1154 		timeout += t1.tv_usec;
   1155 
   1156 		do {
   1157 			twa_done(tr->tr_sc);
   1158 			if (tr->tr_status != TWA_CMD_BUSY)
   1159 				break;
   1160 			microtime(&t1);
   1161 		} while (t1.tv_usec <= timeout);
   1162 
   1163 		if (tr->tr_status != TWA_CMD_COMPLETE) {
   1164 			error = ETIMEDOUT;
   1165 			break;
   1166 		}
   1167 
   1168 		if ((error = tr->tr_command->command.cmd_pkt_9k.status))
   1169 			break;
   1170 
   1171 		cmd_hdr = (struct twa_command_header *)(tr->tr_data);
   1172 		if ((cmd_hdr->status_block.error) /* aen_code */
   1173 				== TWA_AEN_QUEUE_EMPTY)
   1174 			break;
   1175 		(void)twa_enqueue_aen(sc, cmd_hdr);
   1176 
   1177 		free(tr->tr_data, M_DEVBUF);
   1178 		twa_release_request(tr);
   1179 	}
   1180 out:
   1181 	if (tr) {
   1182 		if (tr->tr_data)
   1183 			free(tr->tr_data, M_DEVBUF);
   1184 
   1185 		twa_release_request(tr);
   1186 	}
   1187 	return(error);
   1188 }
   1189 
   1190 static int
   1191 twa_done(struct twa_softc *sc)
   1192 {
   1193 	union twa_response_queue	rq;
   1194 	struct twa_request		*tr;
   1195 	int				s, error = 0;
   1196 	uint32_t			status_reg;
   1197 
   1198 	for (;;) {
   1199 		status_reg = twa_inl(sc, TWA_STATUS_REGISTER_OFFSET);
   1200 		if ((error = twa_check_ctlr_state(sc, status_reg)))
   1201 			break;
   1202 		if (status_reg & TWA_STATUS_RESPONSE_QUEUE_EMPTY)
   1203 			break;
   1204 		/* Response queue is not empty. */
   1205 		rq = (union twa_response_queue)twa_inl(sc,
   1206 			TWA_RESPONSE_QUEUE_OFFSET);
   1207 		tr = sc->sc_twa_request + rq.u.response_id;
   1208 
   1209 		/* Unmap the command packet, and any associated data buffer. */
   1210 		twa_unmap_request(tr);
   1211 
   1212 		s = splbio();
   1213 		tr->tr_status = TWA_CMD_COMPLETE;
   1214 		TAILQ_REMOVE(&tr->tr_sc->twa_busy, tr, tr_link);
   1215 		splx(s);
   1216 
   1217 		if (tr->tr_callback)
   1218 			tr->tr_callback(tr);
   1219 	}
   1220 	(void)twa_drain_pending_queue(sc);
   1221 
   1222 	return(error);
   1223 }
   1224 
   1225 /*
   1226  * Function name:	twa_init_ctlr
   1227  * Description:		Establishes a logical connection with the controller.
   1228  *			If bundled with firmware, determines whether or not
   1229  *			to flash firmware, based on arch_id, fw SRL (Spec.
   1230  *			Revision Level), branch & build #'s.  Also determines
   1231  *			whether or not the driver is compatible with the
   1232  *			firmware on the controller, before proceeding to work
   1233  *			with it.
   1234  *
   1235  * Input:		sc	-- ptr to per ctlr structure
   1236  * Output:		None
   1237  * Return value:	0	-- success
   1238  *			non-zero-- failure
   1239  */
   1240 static int
   1241 twa_init_ctlr(struct twa_softc *sc)
   1242 {
   1243 	uint16_t	fw_on_ctlr_srl = 0;
   1244 	uint16_t	fw_on_ctlr_arch_id = 0;
   1245 	uint16_t	fw_on_ctlr_branch = 0;
   1246 	uint16_t	fw_on_ctlr_build = 0;
   1247 	uint32_t	init_connect_result = 0;
   1248 	int		error = 0;
   1249 #if 0
   1250 	int8_t		fw_flashed = FALSE;
   1251 	int8_t		fw_flash_failed = FALSE;
   1252 #endif
   1253 
   1254 	/* Wait for the controller to become ready. */
   1255 	if (twa_wait_status(sc, TWA_STATUS_MICROCONTROLLER_READY,
   1256 					TWA_REQUEST_TIMEOUT_PERIOD)) {
   1257 		return(ENXIO);
   1258 	}
   1259 	/* Drain the response queue. */
   1260 	if (twa_drain_response_queue(sc))
   1261 		return(1);
   1262 
   1263 	/* Establish a logical connection with the controller. */
   1264 	if ((error = twa_init_connection(sc, TWA_INIT_MESSAGE_CREDITS,
   1265 			TWA_EXTENDED_INIT_CONNECT, TWA_CURRENT_FW_SRL,
   1266 			TWA_9000_ARCH_ID, TWA_CURRENT_FW_BRANCH,
   1267 			TWA_CURRENT_FW_BUILD, &fw_on_ctlr_srl,
   1268 			&fw_on_ctlr_arch_id, &fw_on_ctlr_branch,
   1269 			&fw_on_ctlr_build, &init_connect_result))) {
   1270 		return(error);
   1271 	}
   1272 #if 0
   1273 	if ((init_connect_result & TWA_BUNDLED_FW_SAFE_TO_FLASH) &&
   1274 		(init_connect_result & TWA_CTLR_FW_RECOMMENDS_FLASH)) {
   1275 		/*
   1276 		 * The bundled firmware is safe to flash, and the firmware
   1277 		 * on the controller recommends a flash.  So, flash!
   1278 		 */
   1279 		printf("%s: flashing bundled firmware...\n",
   1280 		    sc->twa_dv.dv_xname);
   1281 
   1282 		if ((error = twa_flash_firmware(sc))) {
   1283 			fw_flash_failed = TRUE;
   1284 
   1285 			printf("%s: unable to flash bundled firmware.\n",
   1286 			    sc->twa_dv.dv_xname);
   1287 		} else {
   1288 			printf("%s: successfully flashed bundled firmware.\n",
   1289 				 sc->twa_dv.dv_xname);
   1290 			fw_flashed = TRUE;
   1291 		}
   1292 	}
   1293 	if (fw_flashed) {
   1294 		/* The firmware was flashed.  Have the new image loaded */
   1295 		error = twa_hard_reset(sc);
   1296 		if (error == 0)
   1297 			error = twa_init_ctlr(sc);
   1298 		/*
   1299 		 * If hard reset of controller failed, we need to return.
   1300 		 * Otherwise, the above recursive call to twa_init_ctlr will
   1301 		 * have completed the rest of the initialization (starting
   1302 		 * from twa_drain_aen_queue below).  Don't do it again.
   1303 		 * Just return.
   1304 		 */
   1305 		return(error);
   1306 	} else {
   1307 		/*
   1308 		 * Either we are not bundled with a firmware image, or
   1309 		 * the bundled firmware is not safe to flash,
   1310 		 * or flash failed for some reason.  See if we can at
   1311 		 * least work with the firmware on the controller in the
   1312 		 * current mode.
   1313 		 */
   1314 		if (init_connect_result & TWA_CTLR_FW_COMPATIBLE) {
   1315 			/* Yes, we can.  Make note of the operating mode. */
   1316 			sc->working_srl = TWA_CURRENT_FW_SRL;
   1317 			sc->working_branch = TWA_CURRENT_FW_BRANCH;
   1318 			sc->working_build = TWA_CURRENT_FW_BUILD;
   1319 		} else {
   1320 			/*
   1321 			 * No, we can't.  See if we can at least work with
   1322 			 * it in the base mode.  We should never come here
   1323 			 * if firmware has just been flashed.
   1324 			 */
   1325 			printf("%s: Driver/Firmware mismatch.  Negotiating "
   1326 			    "for base level.\n", sc->twa_dv.dv_xname);
   1327 			if ((error = twa_init_connection(sc,
   1328 			    TWA_INIT_MESSAGE_CREDITS,
   1329 			    TWA_EXTENDED_INIT_CONNECT, TWA_BASE_FW_SRL,
   1330 			    TWA_9000_ARCH_ID, TWA_BASE_FW_BRANCH,
   1331 			    TWA_BASE_FW_BUILD, &fw_on_ctlr_srl,
   1332 			    &fw_on_ctlr_arch_id, &fw_on_ctlr_branch,
   1333 			    &fw_on_ctlr_build, &init_connect_result))) {
   1334 				printf("%s: can't initialize connection in "
   1335 				    "base mode.\n", sc->twa_dv.dv_xname);
   1336 				return(error);
   1337 			}
   1338 			if (!(init_connect_result & TWA_CTLR_FW_COMPATIBLE)) {
   1339 				/*
   1340 				 * The firmware on the controller is not even
   1341 				 * compatible with our base mode.  We cannot
   1342 				 * work with it.  Bail...
   1343 				 */
   1344 				printf("Incompatible firmware on controller\n");
   1345 #ifdef TWA_FLASH_FIRMWARE
   1346 				if (fw_flash_failed)
   1347 					printf("...and could not flash bundled "
   1348 					    "firmware.\n");
   1349 				else
   1350 					printf("...and bundled firmware not "
   1351 					    "safe to flash.\n");
   1352 #endif /* TWA_FLASH_FIRMWARE */
   1353 				return(1);
   1354 			}
   1355 			/*
   1356 			 * We can work with this firmware, but only in
   1357 			 * base mode.
   1358 			 */
   1359 			sc->working_srl = TWA_BASE_FW_SRL;
   1360 			sc->working_branch = TWA_BASE_FW_BRANCH;
   1361 			sc->working_build = TWA_BASE_FW_BUILD;
   1362 			sc->twa_operating_mode = TWA_BASE_MODE;
   1363 		}
   1364 	}
   1365 #endif
   1366 	twa_drain_aen_queue(sc);
   1367 
   1368 	/* Set controller state to initialized. */
   1369 	sc->twa_state &= ~TWA_STATE_SHUTDOWN;
   1370 	return(0);
   1371 }
   1372 
   1373 static int
   1374 twa_setup(struct twa_softc *sc)
   1375 {
   1376 	struct tw_cl_event_packet *aen_queue;
   1377 	uint32_t		i = 0;
   1378 	int			error = 0;
   1379 
   1380 	/* Initialize request queues. */
   1381 	TAILQ_INIT(&sc->twa_free);
   1382 	TAILQ_INIT(&sc->twa_busy);
   1383 	TAILQ_INIT(&sc->twa_pending);
   1384 
   1385 	sc->sc_nunits = 0;
   1386 	sc->twa_sc_flags = 0;
   1387 
   1388 	if (twa_alloc_req_pkts(sc, TWA_Q_LENGTH)) {
   1389 
   1390 		return(ENOMEM);
   1391 	}
   1392 
   1393 	/* Allocate memory for the AEN queue. */
   1394 	if ((aen_queue = malloc(sizeof(struct tw_cl_event_packet) *
   1395 	    TWA_Q_LENGTH, M_DEVBUF, M_WAITOK)) == NULL) {
   1396 		/*
   1397 		 * This should not cause us to return error.  We will only be
   1398 		 * unable to support AEN's.  But then, we will have to check
   1399 		 * time and again to see if we can support AEN's, if we
   1400 		 * continue.  So, we will just return error.
   1401 		 */
   1402 		return (ENOMEM);
   1403 	}
   1404 	/* Initialize the aen queue. */
   1405 	memset(aen_queue, 0, sizeof(struct tw_cl_event_packet) * TWA_Q_LENGTH);
   1406 
   1407 	for (i = 0; i < TWA_Q_LENGTH; i++)
   1408 		sc->twa_aen_queue[i] = &(aen_queue[i]);
   1409 
   1410 	twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   1411 		TWA_CONTROL_DISABLE_INTERRUPTS);
   1412 
   1413 	/* Initialize the controller. */
   1414 	if ((error = twa_init_ctlr(sc))) {
   1415 		/* Soft reset the controller, and try one more time. */
   1416 
   1417 		printf("%s: controller initialization failed. "
   1418 		    "Retrying initialization\n", sc->twa_dv.dv_xname);
   1419 
   1420 		if ((error = twa_soft_reset(sc)) == 0)
   1421 			error = twa_init_ctlr(sc);
   1422 	}
   1423 
   1424 	twa_describe_controller(sc);
   1425 
   1426 	error = twa_request_bus_scan(sc);
   1427 
   1428 	twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   1429 		TWA_CONTROL_CLEAR_ATTENTION_INTERRUPT |
   1430 		TWA_CONTROL_UNMASK_RESPONSE_INTERRUPT |
   1431 		TWA_CONTROL_ENABLE_INTERRUPTS);
   1432 
   1433 	return (error);
   1434 }
   1435 
   1436 void *twa_sdh;
   1437 
   1438 static void
   1439 twa_attach(struct device *parent, struct device *self, void *aux)
   1440 {
   1441 	struct pci_attach_args *pa;
   1442 	struct twa_softc *sc;
   1443 	pci_chipset_tag_t pc;
   1444 	pcireg_t csr;
   1445 	pci_intr_handle_t ih;
   1446 	const char *intrstr;
   1447 
   1448 	sc = (struct twa_softc *)self;
   1449 
   1450 	pa = aux;
   1451 	pc = pa->pa_pc;
   1452 	sc->pc = pa->pa_pc;
   1453 	sc->tag = pa->pa_tag;
   1454 	sc->twa_dma_tag = pa->pa_dmat;
   1455 
   1456 	aprint_naive(": RAID controller\n");
   1457 	aprint_normal(": 3ware Apache\n");
   1458 
   1459 	if (PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_3WARE_9000) {
   1460 		if (pci_mapreg_map(pa, PCI_MAPREG_START, PCI_MAPREG_TYPE_IO, 0,
   1461 	    	    &sc->twa_bus_iot, &sc->twa_bus_ioh, NULL, NULL)) {
   1462 			aprint_error("%s: can't map i/o space\n",
   1463 			    sc->twa_dv.dv_xname);
   1464 			return;
   1465 		}
   1466 	} else if (PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_3WARE_9550) {
   1467 		if (pci_mapreg_map(pa, PCI_MAPREG_START + 0x08,
   1468 	    	    PCI_MAPREG_MEM_TYPE_64BIT, 0, &sc->twa_bus_iot,
   1469 		    &sc->twa_bus_ioh, NULL, NULL)) {
   1470 			aprint_error("%s: can't map mem space\n",
   1471 			    sc->twa_dv.dv_xname);
   1472 			return;
   1473 		}
   1474 	} else {
   1475 		aprint_error("%s: product id 0x%02x not recognized\n",
   1476 		    sc->twa_dv.dv_xname, PCI_PRODUCT(pa->pa_id));
   1477 		return;
   1478 	}
   1479 	/* Enable the device. */
   1480 	csr = pci_conf_read(pa->pa_pc, pa->pa_tag, PCI_COMMAND_STATUS_REG);
   1481 
   1482 	pci_conf_write(pa->pa_pc, pa->pa_tag, PCI_COMMAND_STATUS_REG,
   1483 	    csr | PCI_COMMAND_MASTER_ENABLE);
   1484 
   1485 	/* Map and establish the interrupt. */
   1486 	if (pci_intr_map(pa, &ih)) {
   1487 		aprint_error("%s: can't map interrupt\n", sc->twa_dv.dv_xname);
   1488 		return;
   1489 	}
   1490 	intrstr = pci_intr_string(pc, ih);
   1491 
   1492 	sc->twa_ih = pci_intr_establish(pc, ih, IPL_BIO, twa_intr, sc);
   1493 	if (sc->twa_ih == NULL) {
   1494 		aprint_error("%s: can't establish interrupt%s%s\n",
   1495 			sc->twa_dv.dv_xname,
   1496 			(intrstr) ? " at " : "",
   1497 			(intrstr) ? intrstr : "");
   1498 		return;
   1499 	}
   1500 
   1501 	if (intrstr != NULL)
   1502 		aprint_normal("%s: interrupting at %s\n",
   1503 			sc->twa_dv.dv_xname, intrstr);
   1504 
   1505 	twa_setup(sc);
   1506 
   1507 	if (twa_sdh == NULL)
   1508 		twa_sdh = shutdownhook_establish(twa_shutdown, NULL);
   1509 
   1510 	return;
   1511 }
   1512 
   1513 static void
   1514 twa_shutdown(void *arg)
   1515 {
   1516 	extern struct cfdriver twa_cd;
   1517 	struct twa_softc *sc;
   1518 	int i, rv, unit;
   1519 
   1520 	for (i = 0; i < twa_cd.cd_ndevs; i++) {
   1521 		if ((sc = device_lookup(&twa_cd, i)) == NULL)
   1522 			continue;
   1523 
   1524 		for (unit = 0; unit < TWA_MAX_UNITS; unit++)
   1525 			if (sc->sc_units[unit].td_dev != NULL)
   1526 				(void) config_detach(sc->sc_units[unit].td_dev,
   1527 					DETACH_FORCE | DETACH_QUIET);
   1528 
   1529 		twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   1530 			TWA_CONTROL_DISABLE_INTERRUPTS);
   1531 
   1532 		/* Let the controller know that we are going down. */
   1533 		rv = twa_init_connection(sc, TWA_SHUTDOWN_MESSAGE_CREDITS,
   1534 				0, 0, 0, 0, 0,
   1535 				NULL, NULL, NULL, NULL, NULL);
   1536 	}
   1537 }
   1538 
   1539 void
   1540 twa_register_callbacks(struct twa_softc *sc, int unit,
   1541     const struct twa_callbacks *tcb)
   1542 {
   1543 
   1544 	sc->sc_units[unit].td_callbacks = tcb;
   1545 }
   1546 
   1547 /*
   1548  * Print autoconfiguration message for a sub-device
   1549  */
   1550 static int
   1551 twa_print(void *aux, const char *pnp)
   1552 {
   1553 	struct twa_attach_args *twaa;
   1554 
   1555 	twaa = aux;
   1556 
   1557 	if (pnp !=NULL)
   1558 		aprint_normal("block device at %s\n", pnp);
   1559 	aprint_normal(" unit %d\n", twaa->twaa_unit);
   1560 	return (UNCONF);
   1561 }
   1562 
   1563 static void
   1564 twa_fillin_sgl(struct twa_sg *sgl, bus_dma_segment_t *segs, int nsegments)
   1565 {
   1566 	int	i;
   1567 	for (i = 0; i < nsegments; i++) {
   1568 		sgl[i].address = segs[i].ds_addr;
   1569 		sgl[i].length = (uint32_t)(segs[i].ds_len);
   1570 	}
   1571 }
   1572 
   1573 static int
   1574 twa_submit_io(struct twa_request *tr)
   1575 {
   1576 	int	error;
   1577 
   1578 	if ((error = twa_start(tr))) {
   1579 		if (error == EBUSY)
   1580 			error = 0; /* request is in the pending queue */
   1581 		else {
   1582 			tr->tr_error = error;
   1583 		}
   1584 	}
   1585 	return(error);
   1586 }
   1587 
   1588 /*
   1589  * Function name:	twa_setup_data_dmamap
   1590  * Description:		Callback of bus_dmamap_load for the buffer associated
   1591  *			with data.  Updates the cmd pkt (size/sgl_entries
   1592  *			fields, as applicable) to reflect the number of sg
   1593  *			elements.
   1594  *
   1595  * Input:		arg	-- ptr to request pkt
   1596  *			segs	-- ptr to a list of segment descriptors
   1597  *			nsegments--# of segments
   1598  *			error	-- 0 if no errors encountered before callback,
   1599  *				   non-zero if errors were encountered
   1600  * Output:		None
   1601  * Return value:	None
   1602  */
   1603 static int
   1604 twa_setup_data_dmamap(void *arg, bus_dma_segment_t *segs, int nsegments,
   1605     int error)
   1606 {
   1607 	struct twa_request		*tr = (struct twa_request *)arg;
   1608 	struct twa_command_packet	*cmdpkt = tr->tr_command;
   1609 	struct twa_command_9k		*cmd9k;
   1610 	union twa_command_7k		*cmd7k;
   1611 	uint8_t				sgl_offset;
   1612 
   1613 	if (error == EFBIG) {
   1614 		tr->tr_error = error;
   1615 		goto out;
   1616 	}
   1617 
   1618 	if (tr->tr_cmd_pkt_type & TWA_CMD_PKT_TYPE_9K) {
   1619 		cmd9k = &(cmdpkt->command.cmd_pkt_9k);
   1620 		twa_fillin_sgl(&(cmd9k->sg_list[0]), segs, nsegments);
   1621 		cmd9k->sgl_entries += nsegments - 1;
   1622 	} else {
   1623 		/* It's a 7000 command packet. */
   1624 		cmd7k = &(cmdpkt->command.cmd_pkt_7k);
   1625 		if ((sgl_offset = cmdpkt->command.cmd_pkt_7k.generic.sgl_offset))
   1626 			twa_fillin_sgl((struct twa_sg *)
   1627 					(((uint32_t *)cmd7k) + sgl_offset),
   1628 					segs, nsegments);
   1629 		/* Modify the size field, based on sg address size. */
   1630 		cmd7k->generic.size +=
   1631 			((TWA_64BIT_ADDRESSES ? 3 : 2) * nsegments);
   1632 	}
   1633 
   1634 	if (tr->tr_flags & TWA_CMD_DATA_IN)
   1635 		bus_dmamap_sync(tr->tr_sc->twa_dma_tag, tr->tr_dma_map, 0,
   1636 			tr->tr_length, BUS_DMASYNC_PREREAD);
   1637 	if (tr->tr_flags & TWA_CMD_DATA_OUT) {
   1638 		/*
   1639 		 * If we're using an alignment buffer, and we're
   1640 		 * writing data, copy the real data out.
   1641 		 */
   1642 		if (tr->tr_flags & TWA_CMD_DATA_COPY_NEEDED)
   1643 			memcpy(tr->tr_data, tr->tr_real_data,
   1644 				tr->tr_real_length);
   1645 		bus_dmamap_sync(tr->tr_sc->twa_dma_tag, tr->tr_dma_map, 0,
   1646 			tr->tr_length, BUS_DMASYNC_PREWRITE);
   1647 	}
   1648 	error = twa_submit_io(tr);
   1649 
   1650 out:
   1651 	if (error) {
   1652 		twa_unmap_request(tr);
   1653 		/*
   1654 		 * If the caller had been returned EINPROGRESS, and he has
   1655 		 * registered a callback for handling completion, the callback
   1656 		 * will never get called because we were unable to submit the
   1657 		 * request.  So, free up the request right here.
   1658 		 */
   1659 		if ((tr->tr_flags & TWA_CMD_IN_PROGRESS) && (tr->tr_callback))
   1660 			twa_release_request(tr);
   1661 	}
   1662 	return (error);
   1663 }
   1664 
   1665 /*
   1666  * Function name:	twa_map_request
   1667  * Description:		Maps a cmd pkt and data associated with it, into
   1668  *			DMA'able memory.
   1669  *
   1670  * Input:		tr	-- ptr to request pkt
   1671  * Output:		None
   1672  * Return value:	0	-- success
   1673  *			non-zero-- failure
   1674  */
   1675 int
   1676 twa_map_request(struct twa_request *tr)
   1677 {
   1678 	struct twa_softc	*sc = tr->tr_sc;
   1679 	int			 s, rv, error = 0;
   1680 
   1681 	/* If the command involves data, map that too. */
   1682 	if (tr->tr_data != NULL) {
   1683 
   1684 		if (((u_long)tr->tr_data & (511)) != 0) {
   1685 			tr->tr_flags |= TWA_CMD_DATA_COPY_NEEDED;
   1686 			tr->tr_real_data = tr->tr_data;
   1687 			tr->tr_real_length = tr->tr_length;
   1688 			s = splvm();
   1689 			tr->tr_data = (void *)uvm_km_alloc(kmem_map,
   1690 			    tr->tr_length, 512, UVM_KMF_NOWAIT|UVM_KMF_WIRED);
   1691 			splx(s);
   1692 
   1693 			if (tr->tr_data == NULL) {
   1694 				tr->tr_data = tr->tr_real_data;
   1695 				tr->tr_length = tr->tr_real_length;
   1696 				return(ENOMEM);
   1697 			}
   1698 			if ((tr->tr_flags & TWA_CMD_DATA_IN) != 0)
   1699 				memcpy(tr->tr_data, tr->tr_real_data,
   1700 					tr->tr_length);
   1701 		}
   1702 
   1703 		/*
   1704 		 * Map the data buffer into bus space and build the S/G list.
   1705 		 */
   1706 		rv = bus_dmamap_load(sc->twa_dma_tag, tr->tr_dma_map,
   1707 			tr->tr_data, tr->tr_length, NULL, BUS_DMA_NOWAIT |
   1708 			BUS_DMA_STREAMING | (tr->tr_flags & TWA_CMD_DATA_OUT) ?
   1709 			BUS_DMA_READ : BUS_DMA_WRITE);
   1710 
   1711 		if (rv != 0) {
   1712 			if ((tr->tr_flags & TWA_CMD_DATA_COPY_NEEDED) != 0) {
   1713 				s = splvm();
   1714 				uvm_km_free(kmem_map, (vaddr_t)tr->tr_data,
   1715 				    tr->tr_length, UVM_KMF_WIRED);
   1716 				splx(s);
   1717 			}
   1718 			return (rv);
   1719 		}
   1720 
   1721 		if ((rv = twa_setup_data_dmamap(tr,
   1722 				tr->tr_dma_map->dm_segs,
   1723 				tr->tr_dma_map->dm_nsegs, error))) {
   1724 
   1725 			if (tr->tr_flags & TWA_CMD_DATA_COPY_NEEDED) {
   1726 				uvm_km_free(kmem_map, (vaddr_t)tr->tr_data,
   1727 				    tr->tr_length, UVM_KMF_WIRED);
   1728 				tr->tr_data = tr->tr_real_data;
   1729 				tr->tr_length = tr->tr_real_length;
   1730 			}
   1731 		} else
   1732 			error = tr->tr_error;
   1733 
   1734 	} else
   1735 		if ((rv = twa_submit_io(tr)))
   1736 			twa_unmap_request(tr);
   1737 
   1738 	return (rv);
   1739 }
   1740 
   1741 #if 0
   1742 /*
   1743  * Function name:	twa_flash_firmware
   1744  * Description:		Flashes bundled firmware image onto controller.
   1745  *
   1746  * Input:		sc	-- ptr to per ctlr structure
   1747  * Output:		None
   1748  * Return value:	0	-- success
   1749  *			non-zero-- failure
   1750  */
   1751 static int
   1752 twa_flash_firmware(struct twa_softc *sc)
   1753 {
   1754 	struct twa_request			*tr;
   1755 	struct twa_command_download_firmware	*cmd;
   1756 	uint32_t				count;
   1757 	uint32_t				fw_img_chunk_size;
   1758 	uint32_t				this_chunk_size = 0;
   1759 	uint32_t				remaining_img_size = 0;
   1760 	int					s, error = 0;
   1761 	int					i;
   1762 
   1763 	if ((tr = twa_get_request(sc, 0)) == NULL) {
   1764 		/* No free request packets available.  Can't proceed. */
   1765 		error = EIO;
   1766 		goto out;
   1767 	}
   1768 
   1769 	count = (twa_fw_img_size / 65536);
   1770 
   1771 	count += ((twa_fw_img_size % 65536) != 0) ? 1 : 0;
   1772 
   1773 	tr->tr_cmd_pkt_type |= TWA_CMD_PKT_TYPE_INTERNAL;
   1774 	/* Allocate sufficient memory to hold a chunk of the firmware image. */
   1775 	fw_img_chunk_size = ((twa_fw_img_size / count) + 511) & ~511;
   1776 
   1777 	s = splvm();
   1778 	tr->tr_data = (void *)uvm_km_alloc(kmem_map, fw_img_chunk_size, 512,
   1779 				UVM_KMF_WIRED);
   1780 	splx(s);
   1781 
   1782 	if (tr->tr_data == NULL) {
   1783 		error = ENOMEM;
   1784 		goto out;
   1785 	}
   1786 
   1787 	remaining_img_size = twa_fw_img_size;
   1788 	cmd = &(tr->tr_command->command.cmd_pkt_7k.download_fw);
   1789 
   1790 	for (i = 0; i < count; i++) {
   1791 		/* Build a cmd pkt for downloading firmware. */
   1792 		memset(tr->tr_command, 0, sizeof(struct twa_command_packet));
   1793 
   1794 		tr->tr_command->cmd_hdr.header_desc.size_header = 128;
   1795 
   1796 		cmd->opcode = TWA_OP_DOWNLOAD_FIRMWARE;
   1797 		cmd->sgl_offset = 2;	/* offset in dwords, to the beginning
   1798 					   of sg list */
   1799 		cmd->size = 2;		/* this field will be updated at data
   1800 					   map time */
   1801 		cmd->request_id = tr->tr_request_id;
   1802 		cmd->unit = 0;
   1803 		cmd->status = 0;
   1804 		cmd->flags = 0;
   1805 		cmd->param = 8;	/* prom image */
   1806 
   1807 		if (i != (count - 1))
   1808 			this_chunk_size = fw_img_chunk_size;
   1809 		else	 /* last chunk */
   1810 			this_chunk_size = remaining_img_size;
   1811 
   1812 		remaining_img_size -= this_chunk_size;
   1813 
   1814 		memset(tr->tr_data, fw_img_chunk_size, 0);
   1815 
   1816 		memcpy(tr->tr_data, twa_fw_img + (i * fw_img_chunk_size),
   1817 			this_chunk_size);
   1818 		/*
   1819 		 * The next line will effect only the last chunk.
   1820 		 */
   1821 		tr->tr_length = (this_chunk_size + 511) & ~511;
   1822 
   1823 		tr->tr_flags |= TWA_CMD_DATA_OUT;
   1824 
   1825 		error = twa_immediate_request(tr, TWA_REQUEST_TIMEOUT_PERIOD);
   1826 
   1827 		if (error) {
   1828 			if (error == ETIMEDOUT)
   1829 				/* clean-up done by twa_immediate_request */
   1830 				return(error);
   1831 			break;
   1832 		}
   1833 		error = cmd->status;
   1834 
   1835 		if (i != (count - 1)) {
   1836 
   1837 			/*
   1838 			 * XXX FreeBSD code doesn't check for no error condition
   1839 			 * but based on observation, error seems to return 0
   1840 			 */
   1841 			if ((error =
   1842 			    tr->tr_command->cmd_hdr.status_block.error) == 0) {
   1843 				continue;
   1844 			} else if ((error =
   1845 			    tr->tr_command->cmd_hdr.status_block.error) ==
   1846 			    TWA_ERROR_MORE_DATA) {
   1847 				    continue;
   1848 			} else {
   1849 				twa_hard_reset(sc);
   1850 				break;
   1851 			}
   1852 		} else	 /* last chunk */
   1853 			if (error) {
   1854 				printf("%s: firmware flash request failed. "
   1855 				    "error = 0x%x\n", sc->twa_dv.dv_xname,
   1856 				    error);
   1857 				twa_hard_reset(sc);
   1858 			}
   1859 	}
   1860 
   1861 	if (tr->tr_data) {
   1862 		s = splvm();
   1863 		uvm_km_free(kmem_map, (vaddr_t)tr->tr_data,
   1864 			fw_img_chunk_size, UVM_KMF_WIRED);
   1865 		splx(s);
   1866 	}
   1867 out:
   1868 	if (tr)
   1869 		twa_release_request(tr);
   1870 	return(error);
   1871 }
   1872 
   1873 /*
   1874  * Function name:	twa_hard_reset
   1875  * Description:		Hard reset the controller.
   1876  *
   1877  * Input:		sc	-- ptr to per ctlr structure
   1878  * Output:		None
   1879  * Return value:	0	-- success
   1880  *			non-zero-- failure
   1881  */
   1882 static int
   1883 twa_hard_reset(struct twa_softc *sc)
   1884 {
   1885 	struct twa_request			*tr;
   1886 	struct twa_command_reset_firmware	*cmd;
   1887 	int					error;
   1888 
   1889 	if ((tr = twa_get_request(sc, 0)) == NULL)
   1890 		return(EIO);
   1891 	tr->tr_cmd_pkt_type |= TWA_CMD_PKT_TYPE_INTERNAL;
   1892 	/* Build a cmd pkt for sending down the hard reset command. */
   1893 	tr->tr_command->cmd_hdr.header_desc.size_header = 128;
   1894 
   1895 	cmd = &(tr->tr_command->command.cmd_pkt_7k.reset_fw);
   1896 	cmd->opcode = TWA_OP_RESET_FIRMWARE;
   1897 	cmd->size = 2;	/* this field will be updated at data map time */
   1898 	cmd->request_id = tr->tr_request_id;
   1899 	cmd->unit = 0;
   1900 	cmd->status = 0;
   1901 	cmd->flags = 0;
   1902 	cmd->param = 0;	/* don't reload FPGA logic */
   1903 
   1904 	tr->tr_data = NULL;
   1905 	tr->tr_length = 0;
   1906 
   1907 	error = twa_immediate_request(tr, TWA_REQUEST_TIMEOUT_PERIOD);
   1908 	if (error) {
   1909 		printf("%s: hard reset request could not be posted. "
   1910 		    "error = 0x%x\n", sc->twa_dv.dv_xname, error);
   1911 		if (error == ETIMEDOUT)
   1912 			/* clean-up done by twa_immediate_request */
   1913 			return(error);
   1914 		goto out;
   1915 	}
   1916 	if ((error = cmd->status)) {
   1917 		printf("%s: hard reset request failed. error = 0x%x\n",
   1918 			sc->twa_dv.dv_xname, error);
   1919 	}
   1920 
   1921 out:
   1922 	if (tr)
   1923 		twa_release_request(tr);
   1924 	return(error);
   1925 }
   1926 #endif
   1927 
   1928 /*
   1929  * Function name:	twa_intr
   1930  * Description:		Interrupt handler.  Determines the kind of interrupt,
   1931  *			and calls the appropriate handler.
   1932  *
   1933  * Input:		sc	-- ptr to per ctlr structure
   1934  * Output:		None
   1935  * Return value:	None
   1936  */
   1937 
   1938 static int
   1939 twa_intr(void *arg)
   1940 {
   1941 	int	caught, rv;
   1942 	struct twa_softc *sc;
   1943 	uint32_t	status_reg;
   1944 	sc = (struct twa_softc *)arg;
   1945 
   1946 	caught = 0;
   1947 	/* Collect current interrupt status. */
   1948 	status_reg = twa_inl(sc, TWA_STATUS_REGISTER_OFFSET);
   1949 	if (twa_check_ctlr_state(sc, status_reg)) {
   1950 		caught = 1;
   1951 		goto bail;
   1952 	}
   1953 	/* Dispatch based on the kind of interrupt. */
   1954 	if (status_reg & TWA_STATUS_HOST_INTERRUPT) {
   1955 		twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   1956 			TWA_CONTROL_CLEAR_HOST_INTERRUPT);
   1957 		caught = 1;
   1958 	}
   1959 	if ((status_reg & TWA_STATUS_ATTENTION_INTERRUPT) != 0) {
   1960 		twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   1961 			TWA_CONTROL_CLEAR_ATTENTION_INTERRUPT);
   1962 		rv = twa_fetch_aen(sc);
   1963 #ifdef DIAGNOSTIC
   1964 		if (rv != 0)
   1965 			printf("%s: unable to retrieve AEN (%d)\n",
   1966 				sc->twa_dv.dv_xname, rv);
   1967 #endif
   1968 		caught = 1;
   1969 	}
   1970 	if (status_reg & TWA_STATUS_COMMAND_INTERRUPT) {
   1971 		/* Start any requests that might be in the pending queue. */
   1972 		twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   1973 			TWA_CONTROL_MASK_COMMAND_INTERRUPT);
   1974 		(void)twa_drain_pending_queue(sc);
   1975 		caught = 1;
   1976 	}
   1977 	if (status_reg & TWA_STATUS_RESPONSE_INTERRUPT) {
   1978 		twa_done(sc);
   1979 		caught = 1;
   1980 	}
   1981 bail:
   1982 	return (caught);
   1983 }
   1984 
   1985 /*
   1986  * Accept an open operation on the control device.
   1987  */
   1988 static int
   1989 twaopen(dev_t dev, int flag, int mode, struct lwp *l)
   1990 {
   1991 	struct twa_softc *twa;
   1992 
   1993 	if ((twa = device_lookup(&twa_cd, minor(dev))) == NULL)
   1994 		return (ENXIO);
   1995 	if ((twa->twa_sc_flags & TWA_STATE_OPEN) != 0)
   1996 		return (EBUSY);
   1997 
   1998 	twa->twa_sc_flags |= TWA_STATE_OPEN;
   1999 
   2000 	return (0);
   2001 }
   2002 
   2003 /*
   2004  * Accept the last close on the control device.
   2005  */
   2006 static int
   2007 twaclose(dev_t dev, int flag, int mode, struct lwp *l)
   2008 {
   2009 	struct twa_softc *twa;
   2010 
   2011 	twa = device_lookup(&twa_cd, minor(dev));
   2012 	twa->twa_sc_flags &= ~TWA_STATE_OPEN;
   2013 	return (0);
   2014 }
   2015 
   2016 /*
   2017  * Function name:	twaioctl
   2018  * Description:		ioctl handler.
   2019  *
   2020  * Input:		sc	-- ptr to per ctlr structure
   2021  *			cmd	-- ioctl cmd
   2022  *			buf	-- ptr to buffer in kernel memory, which is
   2023  *				   a copy of the input buffer in user-space
   2024  * Output:		buf	-- ptr to buffer in kernel memory, which will
   2025  *				   be copied of the output buffer in user-space
   2026  * Return value:	0	-- success
   2027  *			non-zero-- failure
   2028  */
   2029 static int
   2030 twaioctl(dev_t dev, u_long cmd, caddr_t data, int flag, struct lwp *l)
   2031 {
   2032 	struct twa_softc *sc;
   2033 	struct twa_ioctl_9k	*user_buf = (struct twa_ioctl_9k *)data;
   2034 	struct tw_cl_event_packet event_buf;
   2035 	struct twa_request 	*tr = 0;
   2036 	int32_t			event_index = 0;
   2037 	int32_t			start_index;
   2038 	int			s, error = 0;
   2039 
   2040 	sc = device_lookup(&twa_cd, minor(dev));
   2041 
   2042 	switch (cmd) {
   2043 	case TW_OSL_IOCTL_FIRMWARE_PASS_THROUGH:
   2044 	{
   2045 		struct twa_command_packet	*cmdpkt;
   2046 		uint32_t			data_buf_size_adjusted;
   2047 
   2048 		/* Get a request packet */
   2049 		tr = twa_get_request_wait(sc, 0);
   2050 		KASSERT(tr != NULL);
   2051 		/*
   2052 		 * Make sure that the data buffer sent to firmware is a
   2053 		 * 512 byte multiple in size.
   2054 		 */
   2055 		data_buf_size_adjusted =
   2056 			(user_buf->twa_drvr_pkt.buffer_length + 511) & ~511;
   2057 
   2058 		if ((tr->tr_length = data_buf_size_adjusted)) {
   2059 			if ((tr->tr_data = malloc(data_buf_size_adjusted,
   2060 			    M_DEVBUF, M_WAITOK)) == NULL) {
   2061 				error = ENOMEM;
   2062 				goto fw_passthru_done;
   2063 			}
   2064 			/* Copy the payload. */
   2065 			if ((error = copyin((void *) (user_buf->pdata),
   2066 				(void *) (tr->tr_data),
   2067 				user_buf->twa_drvr_pkt.buffer_length)) != 0) {
   2068 					goto fw_passthru_done;
   2069 			}
   2070 			tr->tr_flags |= TWA_CMD_DATA_IN | TWA_CMD_DATA_OUT;
   2071 		}
   2072 		tr->tr_cmd_pkt_type |= TWA_CMD_PKT_TYPE_IOCTL;
   2073 		cmdpkt = tr->tr_command;
   2074 
   2075 		/* Copy the command packet. */
   2076 		memcpy(cmdpkt, &(user_buf->twa_cmd_pkt),
   2077 			sizeof(struct twa_command_packet));
   2078 		cmdpkt->command.cmd_pkt_7k.generic.request_id =
   2079 			tr->tr_request_id;
   2080 
   2081 		/* Send down the request, and wait for it to complete. */
   2082 		if ((error = twa_wait_request(tr, TWA_REQUEST_TIMEOUT_PERIOD))) 		{
   2083 			if (error == ETIMEDOUT)
   2084 				break; /* clean-up done by twa_wait_request */
   2085 			goto fw_passthru_done;
   2086 		}
   2087 
   2088 		/* Copy the command packet back into user space. */
   2089 		memcpy(&user_buf->twa_cmd_pkt, cmdpkt,
   2090 			sizeof(struct twa_command_packet));
   2091 
   2092 		/* If there was a payload, copy it back too. */
   2093 		if (tr->tr_length)
   2094 			error = copyout(tr->tr_data, user_buf->pdata,
   2095 					user_buf->twa_drvr_pkt.buffer_length);
   2096 fw_passthru_done:
   2097 		/* Free resources. */
   2098 		if (tr->tr_data)
   2099 			free(tr->tr_data, M_DEVBUF);
   2100 
   2101 		if (tr)
   2102 			twa_release_request(tr);
   2103 		break;
   2104 	}
   2105 
   2106 	case TW_OSL_IOCTL_SCAN_BUS:
   2107 		twa_request_bus_scan(sc);
   2108 		break;
   2109 
   2110 	case TW_CL_IOCTL_GET_FIRST_EVENT:
   2111 		if (sc->twa_aen_queue_wrapped) {
   2112 			if (sc->twa_aen_queue_overflow) {
   2113 				/*
   2114 				 * The aen queue has wrapped, even before some
   2115 				 * events have been retrieved.  Let the caller
   2116 				 * know that he missed out on some AEN's.
   2117 				 */
   2118 				user_buf->twa_drvr_pkt.status =
   2119 					TWA_ERROR_AEN_OVERFLOW;
   2120 				sc->twa_aen_queue_overflow = FALSE;
   2121 			} else
   2122 				user_buf->twa_drvr_pkt.status = 0;
   2123 			event_index = sc->twa_aen_head;
   2124 		} else {
   2125 			if (sc->twa_aen_head == sc->twa_aen_tail) {
   2126 				user_buf->twa_drvr_pkt.status =
   2127 					TWA_ERROR_AEN_NO_EVENTS;
   2128 				break;
   2129 			}
   2130 			user_buf->twa_drvr_pkt.status = 0;
   2131 			event_index = sc->twa_aen_tail;	/* = 0 */
   2132 		}
   2133 		if ((error = copyout(sc->twa_aen_queue[event_index],
   2134 		    user_buf->pdata, sizeof(struct tw_cl_event_packet))) != 0)
   2135 			(sc->twa_aen_queue[event_index])->retrieved =
   2136 			    TWA_AEN_RETRIEVED;
   2137 		break;
   2138 
   2139 	case TW_CL_IOCTL_GET_LAST_EVENT:
   2140 		if (sc->twa_aen_queue_wrapped) {
   2141 			if (sc->twa_aen_queue_overflow) {
   2142 				/*
   2143 				 * The aen queue has wrapped, even before some
   2144 				 * events have been retrieved.  Let the caller
   2145 				 * know that he missed out on some AEN's.
   2146 				 */
   2147 				user_buf->twa_drvr_pkt.status =
   2148 					TWA_ERROR_AEN_OVERFLOW;
   2149 				sc->twa_aen_queue_overflow = FALSE;
   2150 			} else
   2151 				user_buf->twa_drvr_pkt.status = 0;
   2152 		} else {
   2153 			if (sc->twa_aen_head == sc->twa_aen_tail) {
   2154 				user_buf->twa_drvr_pkt.status =
   2155 					TWA_ERROR_AEN_NO_EVENTS;
   2156 				break;
   2157 			}
   2158 			user_buf->twa_drvr_pkt.status = 0;
   2159 		}
   2160 		event_index =
   2161 		    (sc->twa_aen_head - 1 + TWA_Q_LENGTH) % TWA_Q_LENGTH;
   2162 		if ((error = copyout(sc->twa_aen_queue[event_index],
   2163 		    user_buf->pdata, sizeof(struct tw_cl_event_packet))) != 0)
   2164 			(sc->twa_aen_queue[event_index])->retrieved =
   2165 			    TWA_AEN_RETRIEVED;
   2166 		break;
   2167 
   2168 	case TW_CL_IOCTL_GET_NEXT_EVENT:
   2169 		user_buf->twa_drvr_pkt.status = 0;
   2170 		if (sc->twa_aen_queue_wrapped) {
   2171 
   2172 			if (sc->twa_aen_queue_overflow) {
   2173 				/*
   2174 				 * The aen queue has wrapped, even before some
   2175 				 * events have been retrieved.  Let the caller
   2176 				 * know that he missed out on some AEN's.
   2177 				 */
   2178 				user_buf->twa_drvr_pkt.status =
   2179 					TWA_ERROR_AEN_OVERFLOW;
   2180 				sc->twa_aen_queue_overflow = FALSE;
   2181 			}
   2182 			start_index = sc->twa_aen_head;
   2183 		} else {
   2184 			if (sc->twa_aen_head == sc->twa_aen_tail) {
   2185 				user_buf->twa_drvr_pkt.status =
   2186 					TWA_ERROR_AEN_NO_EVENTS;
   2187 				break;
   2188 			}
   2189 			start_index = sc->twa_aen_tail;	/* = 0 */
   2190 		}
   2191 		error = copyin(user_buf->pdata, &event_buf,
   2192 				sizeof(struct tw_cl_event_packet));
   2193 
   2194 		event_index = (start_index + event_buf.sequence_id -
   2195 		    (sc->twa_aen_queue[start_index])->sequence_id + 1)
   2196 		    % TWA_Q_LENGTH;
   2197 
   2198 		if (!((sc->twa_aen_queue[event_index])->sequence_id >
   2199 		    event_buf.sequence_id)) {
   2200 			if (user_buf->twa_drvr_pkt.status ==
   2201 			    TWA_ERROR_AEN_OVERFLOW)
   2202 				/* so we report the overflow next time */
   2203 				sc->twa_aen_queue_overflow = TRUE;
   2204 			user_buf->twa_drvr_pkt.status = TWA_ERROR_AEN_NO_EVENTS;
   2205 			break;
   2206 		}
   2207 		if ((error = copyout(sc->twa_aen_queue[event_index],
   2208 		    user_buf->pdata, sizeof(struct tw_cl_event_packet))) != 0)
   2209 			(sc->twa_aen_queue[event_index])->retrieved =
   2210 			    TWA_AEN_RETRIEVED;
   2211 		break;
   2212 
   2213 	case TW_CL_IOCTL_GET_PREVIOUS_EVENT:
   2214 		user_buf->twa_drvr_pkt.status = 0;
   2215 		if (sc->twa_aen_queue_wrapped) {
   2216 			if (sc->twa_aen_queue_overflow) {
   2217 				/*
   2218 				 * The aen queue has wrapped, even before some
   2219 				 * events have been retrieved.  Let the caller
   2220 				 * know that he missed out on some AEN's.
   2221 				 */
   2222 				user_buf->twa_drvr_pkt.status =
   2223 					TWA_ERROR_AEN_OVERFLOW;
   2224 				sc->twa_aen_queue_overflow = FALSE;
   2225 			}
   2226 			start_index = sc->twa_aen_head;
   2227 		} else {
   2228 			if (sc->twa_aen_head == sc->twa_aen_tail) {
   2229 				user_buf->twa_drvr_pkt.status =
   2230 					TWA_ERROR_AEN_NO_EVENTS;
   2231 				break;
   2232 			}
   2233 			start_index = sc->twa_aen_tail;	/* = 0 */
   2234 		}
   2235 		if ((error = copyin(user_buf->pdata, &event_buf,
   2236 				sizeof(struct tw_cl_event_packet))) != 0)
   2237 
   2238 		event_index = (start_index + event_buf.sequence_id -
   2239 		    (sc->twa_aen_queue[start_index])->sequence_id - 1)
   2240 		    % TWA_Q_LENGTH;
   2241 		if (!((sc->twa_aen_queue[event_index])->sequence_id <
   2242 		    event_buf.sequence_id)) {
   2243 			if (user_buf->twa_drvr_pkt.status ==
   2244 			    TWA_ERROR_AEN_OVERFLOW)
   2245 				/* so we report the overflow next time */
   2246 				sc->twa_aen_queue_overflow = TRUE;
   2247 			user_buf->twa_drvr_pkt.status =
   2248 				TWA_ERROR_AEN_NO_EVENTS;
   2249 			break;
   2250 		}
   2251 		if ((error = copyout(sc->twa_aen_queue [event_index],
   2252 		    user_buf->pdata, sizeof(struct tw_cl_event_packet))) != 0)
   2253 			aprint_error("%s: get_previous: Could not copyout to "
   2254 			    "event_buf. error = %x\n", sc->twa_dv.dv_xname,
   2255 			    error);
   2256 		(sc->twa_aen_queue[event_index])->retrieved = TWA_AEN_RETRIEVED;
   2257 		break;
   2258 
   2259 	case TW_CL_IOCTL_GET_LOCK:
   2260 	{
   2261 		struct tw_cl_lock_packet	twa_lock;
   2262 
   2263 		copyin(user_buf->pdata, &twa_lock,
   2264 				sizeof(struct tw_cl_lock_packet));
   2265 		s = splbio();
   2266 		if ((sc->twa_ioctl_lock.lock == TWA_LOCK_FREE) ||
   2267 			(twa_lock.force_flag) ||
   2268 			(time_second >= sc->twa_ioctl_lock.timeout)) {
   2269 
   2270 			sc->twa_ioctl_lock.lock = TWA_LOCK_HELD;
   2271 			sc->twa_ioctl_lock.timeout = time_second +
   2272 				(twa_lock.timeout_msec / 1000);
   2273 			twa_lock.time_remaining_msec = twa_lock.timeout_msec;
   2274 			user_buf->twa_drvr_pkt.status = 0;
   2275 		} else {
   2276 			twa_lock.time_remaining_msec =
   2277 				(sc->twa_ioctl_lock.timeout - time_second) *
   2278 				1000;
   2279 			user_buf->twa_drvr_pkt.status =
   2280 					TWA_ERROR_IOCTL_LOCK_ALREADY_HELD;
   2281 		}
   2282 		splx(s);
   2283 		copyout(&twa_lock, user_buf->pdata,
   2284 				sizeof(struct tw_cl_lock_packet));
   2285 		break;
   2286 	}
   2287 
   2288 	case TW_CL_IOCTL_RELEASE_LOCK:
   2289 		s = splbio();
   2290 		if (sc->twa_ioctl_lock.lock == TWA_LOCK_FREE) {
   2291 			user_buf->twa_drvr_pkt.status =
   2292 				TWA_ERROR_IOCTL_LOCK_NOT_HELD;
   2293 		} else {
   2294 			sc->twa_ioctl_lock.lock = TWA_LOCK_FREE;
   2295 			user_buf->twa_drvr_pkt.status = 0;
   2296 		}
   2297 		splx(s);
   2298 		break;
   2299 
   2300 	case TW_CL_IOCTL_GET_COMPATIBILITY_INFO:
   2301 	{
   2302 		struct tw_cl_compatibility_packet	comp_pkt;
   2303 
   2304 		memcpy(comp_pkt.driver_version, TWA_DRIVER_VERSION_STRING,
   2305 					sizeof(TWA_DRIVER_VERSION_STRING));
   2306 		comp_pkt.working_srl = sc->working_srl;
   2307 		comp_pkt.working_branch = sc->working_branch;
   2308 		comp_pkt.working_build = sc->working_build;
   2309 		user_buf->twa_drvr_pkt.status = 0;
   2310 
   2311 		/* Copy compatibility information to user space. */
   2312 		copyout(&comp_pkt, user_buf->pdata,
   2313 				min(sizeof(struct tw_cl_compatibility_packet),
   2314 					user_buf->twa_drvr_pkt.buffer_length));
   2315 		break;
   2316 	}
   2317 
   2318 	case TWA_IOCTL_GET_UNITNAME:	/* WASABI EXTENSION */
   2319 	{
   2320 		struct twa_unitname	*tn;
   2321 		struct twa_drive	*tdr;
   2322 
   2323 		tn = (struct twa_unitname *)data;
   2324 			/* XXX mutex */
   2325 		if (tn->tn_unit < 0 || tn->tn_unit >= TWA_MAX_UNITS)
   2326 			return (EINVAL);
   2327 		tdr = &sc->sc_units[tn->tn_unit];
   2328 		if (tdr->td_dev == NULL)
   2329 			tn->tn_name[0] = '\0';
   2330 		else
   2331 			strlcpy(tn->tn_name, tdr->td_dev->dv_xname,
   2332 			    sizeof(tn->tn_name));
   2333 		return (0);
   2334 	}
   2335 
   2336 	default:
   2337 		/* Unknown opcode. */
   2338 		error = ENOTTY;
   2339 	}
   2340 
   2341 	return(error);
   2342 }
   2343 
   2344 const struct cdevsw twa_cdevsw = {
   2345 	twaopen, twaclose, noread, nowrite, twaioctl,
   2346 	nostop, notty, nopoll, nommap,
   2347 };
   2348 
   2349 /*
   2350  * Function name:	twa_get_param
   2351  * Description:		Get a firmware parameter.
   2352  *
   2353  * Input:		sc		-- ptr to per ctlr structure
   2354  *			table_id	-- parameter table #
   2355  *			param_id	-- index of the parameter in the table
   2356  *			param_size	-- size of the parameter in bytes
   2357  *			callback	-- ptr to function, if any, to be called
   2358  *					back on completion; NULL if no callback.
   2359  * Output:		None
   2360  * Return value:	ptr to param structure	-- success
   2361  *			NULL			-- failure
   2362  */
   2363 static int
   2364 twa_get_param(struct twa_softc *sc, int table_id, int param_id,
   2365     size_t param_size, void (* callback)(struct twa_request *tr),
   2366     struct twa_param_9k **param)
   2367 {
   2368 	int			rv = 0;
   2369 	struct twa_request	*tr;
   2370 	union twa_command_7k	*cmd;
   2371 
   2372 	/* Get a request packet. */
   2373 	if ((tr = twa_get_request(sc, 0)) == NULL) {
   2374 		rv = EAGAIN;
   2375 		goto out;
   2376 	}
   2377 
   2378 	tr->tr_cmd_pkt_type |= TWA_CMD_PKT_TYPE_INTERNAL;
   2379 
   2380 	/* Allocate memory to read data into. */
   2381 	if ((*param = (struct twa_param_9k *)
   2382 		malloc(TWA_SECTOR_SIZE, M_DEVBUF, M_NOWAIT)) == NULL) {
   2383 		rv = ENOMEM;
   2384 		goto out;
   2385 	}
   2386 
   2387 	memset(*param, 0, sizeof(struct twa_param_9k) - 1 + param_size);
   2388 	tr->tr_data = *param;
   2389 	tr->tr_length = TWA_SECTOR_SIZE;
   2390 	tr->tr_flags = TWA_CMD_DATA_IN | TWA_CMD_DATA_OUT;
   2391 
   2392 	/* Build the cmd pkt. */
   2393 	cmd = &(tr->tr_command->command.cmd_pkt_7k);
   2394 
   2395 	tr->tr_command->cmd_hdr.header_desc.size_header = 128;
   2396 
   2397 	cmd->param.opcode = TWA_OP_GET_PARAM;
   2398 	cmd->param.sgl_offset = 2;
   2399 	cmd->param.size = 2;
   2400 	cmd->param.request_id = tr->tr_request_id;
   2401 	cmd->param.unit = 0;
   2402 	cmd->param.param_count = 1;
   2403 
   2404 	/* Specify which parameter we need. */
   2405 	(*param)->table_id = table_id | TWA_9K_PARAM_DESCRIPTOR;
   2406 	(*param)->parameter_id = param_id;
   2407 	(*param)->parameter_size_bytes = param_size;
   2408 
   2409 	/* Submit the command. */
   2410 	if (callback == NULL) {
   2411 		/* There's no call back; wait till the command completes. */
   2412 		rv = twa_immediate_request(tr, TWA_REQUEST_TIMEOUT_PERIOD);
   2413 
   2414 		if (rv != 0)
   2415 			goto out;
   2416 
   2417 		if ((rv = cmd->param.status) != 0) {
   2418 		     /* twa_drain_complete_queue will have done the unmapping */
   2419 		     goto out;
   2420 		}
   2421 		twa_release_request(tr);
   2422 		return (rv);
   2423 	} else {
   2424 		/* There's a call back.  Simply submit the command. */
   2425 		tr->tr_callback = callback;
   2426 		rv = twa_map_request(tr);
   2427 		return (rv);
   2428 	}
   2429 out:
   2430 	if (tr)
   2431 		twa_release_request(tr);
   2432 	return(rv);
   2433 }
   2434 
   2435 /*
   2436  * Function name:	twa_set_param
   2437  * Description:		Set a firmware parameter.
   2438  *
   2439  * Input:		sc		-- ptr to per ctlr structure
   2440  *			table_id	-- parameter table #
   2441  *			param_id	-- index of the parameter in the table
   2442  *			param_size	-- size of the parameter in bytes
   2443  *			callback	-- ptr to function, if any, to be called
   2444  *					back on completion; NULL if no callback.
   2445  * Output:		None
   2446  * Return value:	0	-- success
   2447  *			non-zero-- failure
   2448  */
   2449 static int
   2450 twa_set_param(struct twa_softc *sc, int table_id, int param_id, int param_size,
   2451     void *data, void (* callback)(struct twa_request *tr))
   2452 {
   2453 	struct twa_request	*tr;
   2454 	union twa_command_7k	*cmd;
   2455 	struct twa_param_9k	*param = NULL;
   2456 	int			error = ENOMEM;
   2457 
   2458 	tr = twa_get_request(sc, 0);
   2459 	if (tr == NULL)
   2460 		return (EAGAIN);
   2461 
   2462 	tr->tr_cmd_pkt_type |= TWA_CMD_PKT_TYPE_INTERNAL;
   2463 
   2464 	/* Allocate memory to send data using. */
   2465 	if ((param = (struct twa_param_9k *)
   2466 			malloc(TWA_SECTOR_SIZE, M_DEVBUF, M_NOWAIT)) == NULL)
   2467 		goto out;
   2468 	memset(param, 0, sizeof(struct twa_param_9k) - 1 + param_size);
   2469 	tr->tr_data = param;
   2470 	tr->tr_length = TWA_SECTOR_SIZE;
   2471 	tr->tr_flags = TWA_CMD_DATA_IN | TWA_CMD_DATA_OUT;
   2472 
   2473 	/* Build the cmd pkt. */
   2474 	cmd = &(tr->tr_command->command.cmd_pkt_7k);
   2475 
   2476 	tr->tr_command->cmd_hdr.header_desc.size_header = 128;
   2477 
   2478 	cmd->param.opcode = TWA_OP_SET_PARAM;
   2479 	cmd->param.sgl_offset = 2;
   2480 	cmd->param.size = 2;
   2481 	cmd->param.request_id = tr->tr_request_id;
   2482 	cmd->param.unit = 0;
   2483 	cmd->param.param_count = 1;
   2484 
   2485 	/* Specify which parameter we want to set. */
   2486 	param->table_id = table_id | TWA_9K_PARAM_DESCRIPTOR;
   2487 	param->parameter_id = param_id;
   2488 	param->parameter_size_bytes = param_size;
   2489 	memcpy(param->data, data, param_size);
   2490 
   2491 	/* Submit the command. */
   2492 	if (callback == NULL) {
   2493 		/* There's no call back;  wait till the command completes. */
   2494 		error = twa_immediate_request(tr, TWA_REQUEST_TIMEOUT_PERIOD);
   2495 		if (error == ETIMEDOUT)
   2496 			/* clean-up done by twa_immediate_request */
   2497 			return(error);
   2498 		if (error)
   2499 			goto out;
   2500 		if ((error = cmd->param.status)) {
   2501 			/*
   2502 			 * twa_drain_complete_queue will have done the
   2503 			 * unmapping.
   2504 			 */
   2505 			goto out;
   2506 		}
   2507 		free(param, M_DEVBUF);
   2508 		twa_release_request(tr);
   2509 		return(error);
   2510 	} else {
   2511 		/* There's a call back.  Simply submit the command. */
   2512 		tr->tr_callback = callback;
   2513 		if ((error = twa_map_request(tr)))
   2514 			goto out;
   2515 
   2516 		return (0);
   2517 	}
   2518 out:
   2519 	if (param)
   2520 		free(param, M_DEVBUF);
   2521 	if (tr)
   2522 		twa_release_request(tr);
   2523 	return(error);
   2524 }
   2525 
   2526 /*
   2527  * Function name:	twa_init_connection
   2528  * Description:		Send init_connection cmd to firmware
   2529  *
   2530  * Input:		sc		-- ptr to per ctlr structure
   2531  *			message_credits	-- max # of requests that we might send
   2532  *					 down simultaneously.  This will be
   2533  *					 typically set to 256 at init-time or
   2534  *					after a reset, and to 1 at shutdown-time
   2535  *			set_features	-- indicates if we intend to use 64-bit
   2536  *					sg, also indicates if we want to do a
   2537  *					basic or an extended init_connection;
   2538  *
   2539  * Note: The following input/output parameters are valid, only in case of an
   2540  *		extended init_connection:
   2541  *
   2542  *			current_fw_srl		-- srl of fw we are bundled
   2543  *						with, if any; 0 otherwise
   2544  *			current_fw_arch_id	-- arch_id of fw we are bundled
   2545  *						with, if any; 0 otherwise
   2546  *			current_fw_branch	-- branch # of fw we are bundled
   2547  *						with, if any; 0 otherwise
   2548  *			current_fw_build	-- build # of fw we are bundled
   2549  *						with, if any; 0 otherwise
   2550  * Output:		fw_on_ctlr_srl		-- srl of fw on ctlr
   2551  *			fw_on_ctlr_arch_id	-- arch_id of fw on ctlr
   2552  *			fw_on_ctlr_branch	-- branch # of fw on ctlr
   2553  *			fw_on_ctlr_build	-- build # of fw on ctlr
   2554  *			init_connect_result	-- result bitmap of fw response
   2555  * Return value:	0	-- success
   2556  *			non-zero-- failure
   2557  */
   2558 static int
   2559 twa_init_connection(struct twa_softc *sc, uint16_t message_credits,
   2560     uint32_t set_features, uint16_t current_fw_srl,
   2561     uint16_t current_fw_arch_id, uint16_t current_fw_branch,
   2562     uint16_t current_fw_build, uint16_t *fw_on_ctlr_srl,
   2563     uint16_t *fw_on_ctlr_arch_id, uint16_t *fw_on_ctlr_branch,
   2564     uint16_t *fw_on_ctlr_build, uint32_t *init_connect_result)
   2565 {
   2566 	struct twa_request		*tr;
   2567 	struct twa_command_init_connect	*init_connect;
   2568 	int				error = 1;
   2569 
   2570 	/* Get a request packet. */
   2571 	if ((tr = twa_get_request(sc, 0)) == NULL)
   2572 		goto out;
   2573 	tr->tr_cmd_pkt_type |= TWA_CMD_PKT_TYPE_INTERNAL;
   2574 	/* Build the cmd pkt. */
   2575 	init_connect = &(tr->tr_command->command.cmd_pkt_7k.init_connect);
   2576 
   2577 	tr->tr_command->cmd_hdr.header_desc.size_header = 128;
   2578 
   2579 	init_connect->opcode = TWA_OP_INIT_CONNECTION;
   2580    	init_connect->request_id = tr->tr_request_id;
   2581 	init_connect->message_credits = message_credits;
   2582 	init_connect->features = set_features;
   2583 	if (TWA_64BIT_ADDRESSES) {
   2584 		printf("64 bit addressing supported for scatter/gather list\n");
   2585 		init_connect->features |= TWA_64BIT_SG_ADDRESSES;
   2586 	}
   2587 	if (set_features & TWA_EXTENDED_INIT_CONNECT) {
   2588 		/*
   2589 		 * Fill in the extra fields needed for
   2590 		 * an extended init_connect.
   2591 		 */
   2592 		init_connect->size = 6;
   2593 		init_connect->fw_srl = current_fw_srl;
   2594 		init_connect->fw_arch_id = current_fw_arch_id;
   2595 		init_connect->fw_branch = current_fw_branch;
   2596 	} else
   2597 		init_connect->size = 3;
   2598 
   2599 	/* Submit the command, and wait for it to complete. */
   2600 	error = twa_immediate_request(tr, TWA_REQUEST_TIMEOUT_PERIOD);
   2601 	if (error == ETIMEDOUT)
   2602 		return(error); /* clean-up done by twa_immediate_request */
   2603 	if (error)
   2604 		goto out;
   2605 	if ((error = init_connect->status)) {
   2606 		/* twa_drain_complete_queue will have done the unmapping */
   2607 		goto out;
   2608 	}
   2609 	if (set_features & TWA_EXTENDED_INIT_CONNECT) {
   2610 		*fw_on_ctlr_srl = init_connect->fw_srl;
   2611 		*fw_on_ctlr_arch_id = init_connect->fw_arch_id;
   2612 		*fw_on_ctlr_branch = init_connect->fw_branch;
   2613 		*fw_on_ctlr_build = init_connect->fw_build;
   2614 		*init_connect_result = init_connect->result;
   2615 	}
   2616 	twa_release_request(tr);
   2617 	return(error);
   2618 
   2619 out:
   2620 	if (tr)
   2621 		twa_release_request(tr);
   2622 	return(error);
   2623 }
   2624 
   2625 static int
   2626 twa_reset(struct twa_softc *sc)
   2627 {
   2628 	int	s;
   2629 	int	error = 0;
   2630 
   2631 	/*
   2632 	 * Disable interrupts from the controller, and mask any
   2633 	 * accidental entry into our interrupt handler.
   2634 	 */
   2635 	twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   2636 		TWA_CONTROL_DISABLE_INTERRUPTS);
   2637 
   2638 	s = splbio();
   2639 
   2640 	/* Soft reset the controller. */
   2641 	if ((error = twa_soft_reset(sc)))
   2642 		goto out;
   2643 
   2644 	/* Re-establish logical connection with the controller. */
   2645 	if ((error = twa_init_connection(sc, TWA_INIT_MESSAGE_CREDITS,
   2646 					0, 0, 0, 0, 0,
   2647 					NULL, NULL, NULL, NULL, NULL))) {
   2648 		goto out;
   2649 	}
   2650 	/*
   2651 	 * Complete all requests in the complete queue; error back all requests
   2652 	 * in the busy queue.  Any internal requests will be simply freed.
   2653 	 * Re-submit any requests in the pending queue.
   2654 	 */
   2655 	twa_drain_busy_queue(sc);
   2656 
   2657 out:
   2658 	splx(s);
   2659 	/*
   2660 	 * Enable interrupts, and also clear attention and response interrupts.
   2661 	 */
   2662 	twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   2663 		TWA_CONTROL_CLEAR_ATTENTION_INTERRUPT |
   2664 		TWA_CONTROL_UNMASK_RESPONSE_INTERRUPT |
   2665 		TWA_CONTROL_ENABLE_INTERRUPTS);
   2666 	return(error);
   2667 }
   2668 
   2669 static int
   2670 twa_soft_reset(struct twa_softc *sc)
   2671 {
   2672 	uint32_t	status_reg;
   2673 
   2674 	twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   2675 			TWA_CONTROL_ISSUE_SOFT_RESET |
   2676 			TWA_CONTROL_CLEAR_HOST_INTERRUPT |
   2677 			TWA_CONTROL_CLEAR_ATTENTION_INTERRUPT |
   2678 			TWA_CONTROL_MASK_COMMAND_INTERRUPT |
   2679 			TWA_CONTROL_MASK_RESPONSE_INTERRUPT |
   2680 			TWA_CONTROL_DISABLE_INTERRUPTS);
   2681 
   2682 	if (twa_wait_status(sc, TWA_STATUS_MICROCONTROLLER_READY |
   2683 				TWA_STATUS_ATTENTION_INTERRUPT, 30)) {
   2684 		aprint_error("%s: no attention interrupt after reset.\n",
   2685 			sc->twa_dv.dv_xname);
   2686 		return(1);
   2687 	}
   2688 	twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   2689 		TWA_CONTROL_CLEAR_ATTENTION_INTERRUPT);
   2690 
   2691 	if (twa_drain_response_queue(sc)) {
   2692 		aprint_error("%s: cannot drain response queue.\n",
   2693 		    sc->twa_dv.dv_xname);
   2694 		return(1);
   2695 	}
   2696 	if (twa_drain_aen_queue(sc)) {
   2697 		aprint_error("%s: cannot drain AEN queue.\n",
   2698 		    sc->twa_dv.dv_xname);
   2699 		return(1);
   2700 	}
   2701 	if (twa_find_aen(sc, TWA_AEN_SOFT_RESET)) {
   2702 		aprint_error("%s: reset not reported by controller.\n",
   2703 			 sc->twa_dv.dv_xname);
   2704 		return(1);
   2705 	}
   2706 	status_reg = twa_inl(sc, TWA_STATUS_REGISTER_OFFSET);
   2707 	if (TWA_STATUS_ERRORS(status_reg) ||
   2708 	    twa_check_ctlr_state(sc, status_reg)) {
   2709 		aprint_error("%s: controller errors detected.\n",
   2710 		    sc->twa_dv.dv_xname);
   2711 		return(1);
   2712 	}
   2713 	return(0);
   2714 }
   2715 
   2716 static int
   2717 twa_wait_status(struct twa_softc *sc, uint32_t status, uint32_t timeout)
   2718 {
   2719 	struct timeval		t1;
   2720 	time_t		end_time;
   2721 	uint32_t	status_reg;
   2722 
   2723 	timeout = (timeout * 1000 * 100);
   2724 
   2725 	microtime(&t1);
   2726 
   2727 	end_time = t1.tv_usec + timeout;
   2728 
   2729 	do {
   2730 		status_reg = twa_inl(sc, TWA_STATUS_REGISTER_OFFSET);
   2731 		/* got the required bit(s)? */
   2732 		if ((status_reg & status) == status)
   2733 			return(0);
   2734 		DELAY(100000);
   2735 		microtime(&t1);
   2736 	} while (t1.tv_usec <= end_time);
   2737 
   2738 	return(1);
   2739 }
   2740 
   2741 static int
   2742 twa_fetch_aen(struct twa_softc *sc)
   2743 {
   2744 	struct twa_request	*tr;
   2745 	int			s, error = 0;
   2746 
   2747 	s = splbio();
   2748 
   2749 	if ((tr = twa_get_request(sc, TWA_CMD_AEN)) == NULL)
   2750 		return(EIO);
   2751 	tr->tr_cmd_pkt_type |= TWA_CMD_PKT_TYPE_INTERNAL;
   2752 	tr->tr_callback = twa_aen_callback;
   2753 	tr->tr_data = malloc(TWA_SECTOR_SIZE, M_DEVBUF, M_NOWAIT);
   2754 	if (twa_request_sense(tr, 0) != 0) {
   2755 		if (tr->tr_data)
   2756 			free(tr->tr_data, M_DEVBUF);
   2757 		twa_release_request(tr);
   2758 		error = 1;
   2759 	}
   2760 	splx(s);
   2761 
   2762 	return(error);
   2763 }
   2764 
   2765 /*
   2766  * Function name:	twa_aen_callback
   2767  * Description:		Callback for requests to fetch AEN's.
   2768  *
   2769  * Input:		tr	-- ptr to completed request pkt
   2770  * Output:		None
   2771  * Return value:	None
   2772  */
   2773 static void
   2774 twa_aen_callback(struct twa_request *tr)
   2775 {
   2776 	int i;
   2777 	int fetch_more_aens = 0;
   2778 	struct twa_softc		*sc = tr->tr_sc;
   2779 	struct twa_command_header	*cmd_hdr =
   2780 		(struct twa_command_header *)(tr->tr_data);
   2781 	struct twa_command_9k		*cmd =
   2782 		&(tr->tr_command->command.cmd_pkt_9k);
   2783 
   2784 	if (! cmd->status) {
   2785 		if ((tr->tr_cmd_pkt_type & TWA_CMD_PKT_TYPE_9K) &&
   2786 			(cmd->cdb[0] == 0x3 /* REQUEST_SENSE */))
   2787 			if (twa_enqueue_aen(sc, cmd_hdr)
   2788 				!= TWA_AEN_QUEUE_EMPTY)
   2789 				fetch_more_aens = 1;
   2790 	} else {
   2791 		cmd_hdr->err_specific_desc[sizeof(cmd_hdr->err_specific_desc) - 1] = '\0';
   2792 		for (i = 0; i < 18; i++)
   2793 			printf("%x\t", tr->tr_command->cmd_hdr.sense_data[i]);
   2794 
   2795 		printf(""); /* print new line */
   2796 
   2797 		for (i = 0; i < 128; i++)
   2798 			printf("%x\t", ((int8_t *)(tr->tr_data))[i]);
   2799 	}
   2800 	if (tr->tr_data)
   2801 		free(tr->tr_data, M_DEVBUF);
   2802 	twa_release_request(tr);
   2803 
   2804 	if (fetch_more_aens)
   2805 		twa_fetch_aen(sc);
   2806 }
   2807 
   2808 /*
   2809  * Function name:	twa_enqueue_aen
   2810  * Description:		Queues AEN's to be supplied to user-space tools on request.
   2811  *
   2812  * Input:		sc	-- ptr to per ctlr structure
   2813  *			cmd_hdr	-- ptr to hdr of fw cmd pkt, from where the AEN
   2814  *				   details can be retrieved.
   2815  * Output:		None
   2816  * Return value:	None
   2817  */
   2818 static uint16_t
   2819 twa_enqueue_aen(struct twa_softc *sc, struct twa_command_header *cmd_hdr)
   2820 {
   2821 	int			rv, s;
   2822 	struct tw_cl_event_packet *event;
   2823 	uint16_t		aen_code;
   2824 	unsigned long		sync_time;
   2825 
   2826 	s = splbio();
   2827 	aen_code = cmd_hdr->status_block.error;
   2828 
   2829 	switch (aen_code) {
   2830 	case TWA_AEN_SYNC_TIME_WITH_HOST:
   2831 
   2832 		sync_time = (time_second - (3 * 86400)) % 604800;
   2833 		rv = twa_set_param(sc, TWA_PARAM_TIME_TABLE,
   2834 				TWA_PARAM_TIME_SchedulerTime, 4,
   2835 				&sync_time, twa_aen_callback);
   2836 #ifdef DIAGNOSTIC
   2837 		if (rv != 0)
   2838 			printf("%s: unable to sync time with ctlr\n",
   2839 				sc->twa_dv.dv_xname);
   2840 #endif
   2841 		break;
   2842 
   2843 	case TWA_AEN_QUEUE_EMPTY:
   2844 		break;
   2845 
   2846 	default:
   2847 		/* Queue the event. */
   2848 		event = sc->twa_aen_queue[sc->twa_aen_head];
   2849 		if (event->retrieved == TWA_AEN_NOT_RETRIEVED)
   2850 			sc->twa_aen_queue_overflow = TRUE;
   2851 		event->severity =
   2852 			cmd_hdr->status_block.substatus_block.severity;
   2853 		event->time_stamp_sec = time_second;
   2854 		event->aen_code = aen_code;
   2855 		event->retrieved = TWA_AEN_NOT_RETRIEVED;
   2856 		event->sequence_id = ++(sc->twa_current_sequence_id);
   2857 		cmd_hdr->err_specific_desc[sizeof(cmd_hdr->err_specific_desc) - 1] = '\0';
   2858 		event->parameter_len = strlen(cmd_hdr->err_specific_desc);
   2859 		memcpy(event->parameter_data, cmd_hdr->err_specific_desc,
   2860 			event->parameter_len);
   2861 
   2862 		if (event->severity < TWA_AEN_SEVERITY_DEBUG) {
   2863 			printf("%s: AEN 0x%04X: %s: %s: %s\n",
   2864 				sc->twa_dv.dv_xname,
   2865 				aen_code,
   2866 				twa_aen_severity_table[event->severity],
   2867 				twa_find_msg_string(twa_aen_table, aen_code),
   2868 				event->parameter_data);
   2869 		}
   2870 
   2871 		if ((sc->twa_aen_head + 1) == TWA_Q_LENGTH)
   2872 			sc->twa_aen_queue_wrapped = TRUE;
   2873 		sc->twa_aen_head = (sc->twa_aen_head + 1) % TWA_Q_LENGTH;
   2874 		break;
   2875 	} /* switch */
   2876 	splx(s);
   2877 
   2878 	return (aen_code);
   2879 }
   2880 
   2881 /*
   2882  * Function name:	twa_find_aen
   2883  * Description:		Reports whether a given AEN ever occurred.
   2884  *
   2885  * Input:		sc	-- ptr to per ctlr structure
   2886  *			aen_code-- AEN to look for
   2887  * Output:		None
   2888  * Return value:	0	-- success
   2889  *			non-zero-- failure
   2890  */
   2891 static int
   2892 twa_find_aen(struct twa_softc *sc, uint16_t aen_code)
   2893 {
   2894 	uint32_t	last_index;
   2895 	int		s;
   2896 	int		i;
   2897 
   2898 	s = splbio();
   2899 
   2900 	if (sc->twa_aen_queue_wrapped)
   2901 		last_index = sc->twa_aen_head;
   2902 	else
   2903 		last_index = 0;
   2904 
   2905 	i = sc->twa_aen_head;
   2906 	do {
   2907 		i = (i + TWA_Q_LENGTH - 1) % TWA_Q_LENGTH;
   2908 		if ((sc->twa_aen_queue[i])->aen_code == aen_code) {
   2909 			splx(s);
   2910 			return(0);
   2911 		}
   2912 	} while (i != last_index);
   2913 
   2914 	splx(s);
   2915 	return(1);
   2916 }
   2917 
   2918 static void inline
   2919 twa_request_init(struct twa_request *tr, int flags)
   2920 {
   2921 	tr->tr_data = NULL;
   2922 	tr->tr_real_data = NULL;
   2923 	tr->tr_length = 0;
   2924 	tr->tr_real_length = 0;
   2925 	tr->tr_status = TWA_CMD_SETUP;/* command is in setup phase */
   2926 	tr->tr_flags = flags;
   2927 	tr->tr_error = 0;
   2928 	tr->tr_callback = NULL;
   2929 	tr->tr_cmd_pkt_type = 0;
   2930 
   2931 	/*
   2932 	 * Look at the status field in the command packet to see how
   2933 	 * it completed the last time it was used, and zero out only
   2934 	 * the portions that might have changed.  Note that we don't
   2935 	 * care to zero out the sglist.
   2936 	 */
   2937 	if (tr->tr_command->command.cmd_pkt_9k.status)
   2938 		memset(tr->tr_command, 0,
   2939 			sizeof(struct twa_command_header) + 28);
   2940 	else
   2941 		memset(&(tr->tr_command->command), 0, 28);
   2942 }
   2943 
   2944 struct twa_request *
   2945 twa_get_request_wait(struct twa_softc *sc, int flags)
   2946 {
   2947 	struct twa_request *tr;
   2948 	int s;
   2949 
   2950 	KASSERT((flags & TWA_CMD_AEN) == 0);
   2951 
   2952 	s = splbio();
   2953 	while ((tr = TAILQ_FIRST(&sc->twa_free)) == NULL) {
   2954 		sc->twa_sc_flags |= TWA_STATE_REQUEST_WAIT;
   2955 		(void) tsleep(&sc->twa_free, PRIBIO, "twaccb", hz);
   2956 	}
   2957 	TAILQ_REMOVE(&sc->twa_free, tr, tr_link);
   2958 
   2959 	splx(s);
   2960 
   2961 	twa_request_init(tr, flags);
   2962 
   2963 	return(tr);
   2964 }
   2965 
   2966 struct twa_request *
   2967 twa_get_request(struct twa_softc *sc, int flags)
   2968 {
   2969 	int s;
   2970 	struct twa_request *tr;
   2971 
   2972 	/* Get a free request packet. */
   2973 	s = splbio();
   2974 	if (__predict_false((flags & TWA_CMD_AEN) != 0)) {
   2975 
   2976 		if ((sc->sc_twa_request->tr_flags & TWA_CMD_AEN_BUSY) == 0) {
   2977 			tr = sc->sc_twa_request;
   2978 			flags |= TWA_CMD_AEN_BUSY;
   2979 		} else {
   2980 			splx(s);
   2981 			return (NULL);
   2982 		}
   2983 	} else {
   2984 		if (__predict_false((tr =
   2985 				TAILQ_FIRST(&sc->twa_free)) == NULL)) {
   2986 			splx(s);
   2987 			return (NULL);
   2988 		}
   2989 		TAILQ_REMOVE(&sc->twa_free, tr, tr_link);
   2990 	}
   2991 	splx(s);
   2992 
   2993 	twa_request_init(tr, flags);
   2994 
   2995 	return(tr);
   2996 }
   2997 
   2998 /*
   2999  * Print some information about the controller
   3000  */
   3001 static void
   3002 twa_describe_controller(struct twa_softc *sc)
   3003 {
   3004 	struct twa_param_9k	*p[10];
   3005 	int			i, rv = 0;
   3006 	uint32_t		dsize;
   3007 	uint8_t			ports;
   3008 
   3009 	memset(p, sizeof(struct twa_param_9k *), 10);
   3010 
   3011 	/* Get the port count. */
   3012 	rv |= twa_get_param(sc, TWA_PARAM_CONTROLLER,
   3013 		TWA_PARAM_CONTROLLER_PortCount, 1, NULL, &p[0]);
   3014 
   3015 	/* get version strings */
   3016 	rv |= twa_get_param(sc, TWA_PARAM_VERSION, TWA_PARAM_VERSION_FW,
   3017 		16, NULL, &p[1]);
   3018 	rv |= twa_get_param(sc, TWA_PARAM_VERSION, TWA_PARAM_VERSION_BIOS,
   3019 		16, NULL, &p[2]);
   3020 	rv |= twa_get_param(sc, TWA_PARAM_VERSION, TWA_PARAM_VERSION_Mon,
   3021 		16, NULL, &p[3]);
   3022 	rv |= twa_get_param(sc, TWA_PARAM_VERSION, TWA_PARAM_VERSION_PCBA,
   3023 		8, NULL, &p[4]);
   3024 	rv |= twa_get_param(sc, TWA_PARAM_VERSION, TWA_PARAM_VERSION_ATA,
   3025 		8, NULL, &p[5]);
   3026 	rv |= twa_get_param(sc, TWA_PARAM_VERSION, TWA_PARAM_VERSION_PCI,
   3027 		8, NULL, &p[6]);
   3028 	rv |= twa_get_param(sc, TWA_PARAM_DRIVESUMMARY, TWA_PARAM_DRIVESTATUS,
   3029 		16, NULL, &p[7]);
   3030 
   3031 	if (rv) {
   3032 		/* some error occurred */
   3033 		aprint_error("%s: failed to fetch version information\n",
   3034 			sc->twa_dv.dv_xname);
   3035 		goto bail;
   3036 	}
   3037 
   3038 	ports = *(uint8_t *)(p[0]->data);
   3039 
   3040 	aprint_normal("%s: %d ports, Firmware %.16s, BIOS %.16s\n",
   3041 		sc->twa_dv.dv_xname, ports,
   3042 		p[1]->data, p[2]->data);
   3043 
   3044 	aprint_verbose("%s: Monitor %.16s, PCB %.8s, Achip %.8s, Pchip %.8s\n",
   3045 		sc->twa_dv.dv_xname,
   3046 		p[3]->data, p[4]->data,
   3047 		p[5]->data, p[6]->data);
   3048 
   3049 	for (i = 0; i < ports; i++) {
   3050 
   3051 		if ((*((char *)(p[7]->data + i)) & TWA_DRIVE_DETECTED) == 0)
   3052 			continue;
   3053 
   3054 		rv = twa_get_param(sc, TWA_PARAM_DRIVE_TABLE,
   3055 			TWA_PARAM_DRIVEMODELINDEX,
   3056 			TWA_PARAM_DRIVEMODEL_LENGTH, NULL, &p[8]);
   3057 
   3058 		if (rv != 0) {
   3059 			aprint_error("%s: unable to get drive model for port"
   3060 				" %d\n", sc->twa_dv.dv_xname, i);
   3061 			continue;
   3062 		}
   3063 
   3064 		rv = twa_get_param(sc, TWA_PARAM_DRIVE_TABLE,
   3065 			TWA_PARAM_DRIVESIZEINDEX,
   3066 			TWA_PARAM_DRIVESIZE_LENGTH, NULL, &p[9]);
   3067 
   3068 		if (rv != 0) {
   3069 			aprint_error("%s: unable to get drive size"
   3070 				" for port %d\n", sc->twa_dv.dv_xname,
   3071 					i);
   3072 			free(p[8], M_DEVBUF);
   3073 			continue;
   3074 		}
   3075 
   3076 		dsize = *(uint32_t *)(p[9]->data);
   3077 
   3078 		aprint_verbose("%s: port %d: %.40s %d MB\n",
   3079 		    sc->twa_dv.dv_xname, i, p[8]->data, dsize / 2048);
   3080 
   3081 		if (p[8])
   3082 			free(p[8], M_DEVBUF);
   3083 		if (p[9])
   3084 			free(p[9], M_DEVBUF);
   3085 	}
   3086 bail:
   3087 	if (p[0])
   3088 		free(p[0], M_DEVBUF);
   3089 	if (p[1])
   3090 		free(p[1], M_DEVBUF);
   3091 	if (p[2])
   3092 		free(p[2], M_DEVBUF);
   3093 	if (p[3])
   3094 		free(p[3], M_DEVBUF);
   3095 	if (p[4])
   3096 		free(p[4], M_DEVBUF);
   3097 	if (p[5])
   3098 		free(p[5], M_DEVBUF);
   3099 	if (p[6])
   3100 		free(p[6], M_DEVBUF);
   3101 }
   3102 
   3103 /*
   3104  * Function name:	twa_check_ctlr_state
   3105  * Description:		Makes sure that the fw status register reports a
   3106  *			proper status.
   3107  *
   3108  * Input:		sc		-- ptr to per ctlr structure
   3109  *			status_reg	-- value in the status register
   3110  * Output:		None
   3111  * Return value:	0	-- no errors
   3112  *			non-zero-- errors
   3113  */
   3114 static int
   3115 twa_check_ctlr_state(struct twa_softc *sc, uint32_t status_reg)
   3116 {
   3117 	int		result = 0;
   3118 	struct timeval	t1;
   3119 	static time_t	last_warning[2] = {0, 0};
   3120 
   3121 	/* Check if the 'micro-controller ready' bit is not set. */
   3122 	if ((status_reg & TWA_STATUS_EXPECTED_BITS) !=
   3123 				TWA_STATUS_EXPECTED_BITS) {
   3124 
   3125 		microtime(&t1);
   3126 
   3127 		last_warning[0] += (5 * 1000 * 100);
   3128 
   3129 		if (t1.tv_usec > last_warning[0]) {
   3130 			microtime(&t1);
   3131 			last_warning[0] = t1.tv_usec;
   3132 		}
   3133 		result = 1;
   3134 	}
   3135 
   3136 	/* Check if any error bits are set. */
   3137 	if ((status_reg & TWA_STATUS_UNEXPECTED_BITS) != 0) {
   3138 
   3139 		microtime(&t1);
   3140 		last_warning[1] += (5 * 1000 * 100);
   3141 		if (t1.tv_usec > last_warning[1]) {
   3142 		     	microtime(&t1);
   3143 			last_warning[1] = t1.tv_usec;
   3144 		}
   3145 		if (status_reg & TWA_STATUS_PCI_PARITY_ERROR_INTERRUPT) {
   3146 			aprint_error("%s: clearing PCI parity error "
   3147 				"re-seat/move/replace card.\n",
   3148 				 sc->twa_dv.dv_xname);
   3149 			twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   3150 				TWA_CONTROL_CLEAR_PARITY_ERROR);
   3151 			pci_conf_write(sc->pc, sc->tag,
   3152 				PCI_COMMAND_STATUS_REG,
   3153 				TWA_PCI_CONFIG_CLEAR_PARITY_ERROR);
   3154 			result = 1;
   3155 		}
   3156 		if (status_reg & TWA_STATUS_PCI_ABORT_INTERRUPT) {
   3157 			aprint_error("%s: clearing PCI abort\n",
   3158 				sc->twa_dv.dv_xname);
   3159 			twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   3160 				TWA_CONTROL_CLEAR_PCI_ABORT);
   3161 			pci_conf_write(sc->pc, sc->tag,
   3162 				PCI_COMMAND_STATUS_REG,
   3163 				TWA_PCI_CONFIG_CLEAR_PCI_ABORT);
   3164 			result = 1;
   3165 		}
   3166 		if (status_reg & TWA_STATUS_QUEUE_ERROR_INTERRUPT) {
   3167 			aprint_error("%s: clearing controller queue error\n",
   3168 				sc->twa_dv.dv_xname);
   3169 			twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   3170 				TWA_CONTROL_CLEAR_PCI_ABORT);
   3171 			result = 1;
   3172 		}
   3173 		if (status_reg & TWA_STATUS_SBUF_WRITE_ERROR) {
   3174 			aprint_error("%s: clearing SBUF write error\n",
   3175 				sc->twa_dv.dv_xname);
   3176 			twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
   3177 				TWA_CONTROL_CLEAR_SBUF_WRITE_ERROR);
   3178 			result = 1;
   3179 		}
   3180 		if (status_reg & TWA_STATUS_MICROCONTROLLER_ERROR) {
   3181 			aprint_error("%s: micro-controller error\n",
   3182 				sc->twa_dv.dv_xname);
   3183 			result = 1;
   3184 		}
   3185 	}
   3186 	return(result);
   3187 }
   3188