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