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