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