Home | History | Annotate | Line # | Download | only in pci
twe.c revision 1.103
      1 /*	$NetBSD: twe.c,v 1.103 2014/07/25 08:10:38 dholland Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2000, 2001, 2002, 2003, 2004 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Andrew Doran; and by Jason R. Thorpe of Wasabi Systems, Inc.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 /*-
     33  * Copyright (c) 2000 Michael Smith
     34  * Copyright (c) 2000 BSDi
     35  * All rights reserved.
     36  *
     37  * Redistribution and use in source and binary forms, with or without
     38  * modification, are permitted provided that the following conditions
     39  * are met:
     40  * 1. Redistributions of source code must retain the above copyright
     41  *    notice, this list of conditions and the following disclaimer.
     42  * 2. Redistributions in binary form must reproduce the above copyright
     43  *    notice, this list of conditions and the following disclaimer in the
     44  *    documentation and/or other materials provided with the distribution.
     45  *
     46  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
     47  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     48  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     49  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     50  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     51  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     52  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     53  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     54  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     55  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     56  * SUCH DAMAGE.
     57  *
     58  * from FreeBSD: twe.c,v 1.1 2000/05/24 23:35:23 msmith Exp
     59  */
     60 
     61 /*
     62  * Driver for the 3ware Escalade family of RAID controllers.
     63  */
     64 
     65 #include <sys/cdefs.h>
     66 __KERNEL_RCSID(0, "$NetBSD: twe.c,v 1.103 2014/07/25 08:10:38 dholland Exp $");
     67 
     68 #include <sys/param.h>
     69 #include <sys/systm.h>
     70 #include <sys/kernel.h>
     71 #include <sys/device.h>
     72 #include <sys/queue.h>
     73 #include <sys/proc.h>
     74 #include <sys/buf.h>
     75 #include <sys/endian.h>
     76 #include <sys/malloc.h>
     77 #include <sys/conf.h>
     78 #include <sys/disk.h>
     79 #include <sys/sysctl.h>
     80 #include <sys/syslog.h>
     81 #include <sys/kauth.h>
     82 
     83 #include <sys/bswap.h>
     84 #include <sys/bus.h>
     85 
     86 #include <dev/pci/pcireg.h>
     87 #include <dev/pci/pcivar.h>
     88 #include <dev/pci/pcidevs.h>
     89 #include <dev/pci/twereg.h>
     90 #include <dev/pci/twevar.h>
     91 #include <dev/pci/tweio.h>
     92 
     93 #include "locators.h"
     94 
     95 #define	PCI_CBIO	0x10
     96 
     97 static int	twe_aen_get(struct twe_softc *, uint16_t *);
     98 static void	twe_aen_handler(struct twe_ccb *, int);
     99 static void	twe_aen_enqueue(struct twe_softc *sc, uint16_t, int);
    100 static uint16_t	twe_aen_dequeue(struct twe_softc *);
    101 
    102 static void	twe_attach(device_t, device_t, void *);
    103 static int	twe_init_connection(struct twe_softc *);
    104 static int	twe_intr(void *);
    105 static int	twe_match(device_t, cfdata_t, void *);
    106 static int	twe_param_set(struct twe_softc *, int, int, size_t, void *);
    107 static void	twe_poll(struct twe_softc *);
    108 static int	twe_print(void *, const char *);
    109 static int	twe_reset(struct twe_softc *);
    110 static int	twe_status_check(struct twe_softc *, u_int);
    111 static int	twe_status_wait(struct twe_softc *, u_int, int);
    112 static void	twe_describe_controller(struct twe_softc *);
    113 static void twe_clear_pci_abort(struct twe_softc *sc);
    114 static void twe_clear_pci_parity_error(struct twe_softc *sc);
    115 
    116 static int	twe_add_unit(struct twe_softc *, int);
    117 static int	twe_del_unit(struct twe_softc *, int);
    118 static int	twe_init_connection(struct twe_softc *);
    119 
    120 static inline u_int32_t	twe_inl(struct twe_softc *, int);
    121 static inline void twe_outl(struct twe_softc *, int, u_int32_t);
    122 
    123 extern struct	cfdriver twe_cd;
    124 
    125 CFATTACH_DECL_NEW(twe, sizeof(struct twe_softc),
    126     twe_match, twe_attach, NULL, NULL);
    127 
    128 /* FreeBSD driver revision for sysctl expected by the 3ware cli */
    129 const char twever[] = "1.50.01.002";
    130 
    131 /*
    132  * Tables to convert numeric codes to strings.
    133  */
    134 const struct twe_code_table twe_table_status[] = {
    135 	{ 0x00,	"successful completion" },
    136 
    137 	/* info */
    138 	{ 0x42,	"command in progress" },
    139 	{ 0x6c,	"retrying interface CRC error from UDMA command" },
    140 
    141 	/* warning */
    142 	{ 0x81,	"redundant/inconsequential request ignored" },
    143 	{ 0x8e,	"failed to write zeroes to LBA 0" },
    144 	{ 0x8f,	"failed to profile TwinStor zones" },
    145 
    146 	/* fatal */
    147 	{ 0xc1,	"aborted due to system command or reconfiguration" },
    148 	{ 0xc4,	"aborted" },
    149 	{ 0xc5,	"access error" },
    150 	{ 0xc6,	"access violation" },
    151 	{ 0xc7,	"device failure" },	/* high byte may be port # */
    152 	{ 0xc8,	"controller error" },
    153 	{ 0xc9,	"timed out" },
    154 	{ 0xcb,	"invalid unit number" },
    155 	{ 0xcf,	"unit not available" },
    156 	{ 0xd2,	"undefined opcode" },
    157 	{ 0xdb,	"request incompatible with unit" },
    158 	{ 0xdc,	"invalid request" },
    159 	{ 0xff,	"firmware error, reset requested" },
    160 
    161 	{ 0,	NULL }
    162 };
    163 
    164 const struct twe_code_table twe_table_unitstate[] = {
    165 	{ TWE_PARAM_UNITSTATUS_Normal,		"Normal" },
    166 	{ TWE_PARAM_UNITSTATUS_Initialising,	"Initializing" },
    167 	{ TWE_PARAM_UNITSTATUS_Degraded,	"Degraded" },
    168 	{ TWE_PARAM_UNITSTATUS_Rebuilding,	"Rebuilding" },
    169 	{ TWE_PARAM_UNITSTATUS_Verifying,	"Verifying" },
    170 	{ TWE_PARAM_UNITSTATUS_Corrupt,		"Corrupt" },
    171 	{ TWE_PARAM_UNITSTATUS_Missing,		"Missing" },
    172 
    173 	{ 0,					NULL }
    174 };
    175 
    176 const struct twe_code_table twe_table_unittype[] = {
    177 	/* array descriptor configuration */
    178 	{ TWE_AD_CONFIG_RAID0,			"RAID0" },
    179 	{ TWE_AD_CONFIG_RAID1,			"RAID1" },
    180 	{ TWE_AD_CONFIG_TwinStor,		"TwinStor" },
    181 	{ TWE_AD_CONFIG_RAID5,			"RAID5" },
    182 	{ TWE_AD_CONFIG_RAID10,			"RAID10" },
    183 	{ TWE_UD_CONFIG_JBOD,			"JBOD" },
    184 
    185 	{ 0,					NULL }
    186 };
    187 
    188 const struct twe_code_table twe_table_stripedepth[] = {
    189 	{ TWE_AD_STRIPE_4k,			"4K" },
    190 	{ TWE_AD_STRIPE_8k,			"8K" },
    191 	{ TWE_AD_STRIPE_16k,			"16K" },
    192 	{ TWE_AD_STRIPE_32k,			"32K" },
    193 	{ TWE_AD_STRIPE_64k,			"64K" },
    194 	{ TWE_AD_STRIPE_128k,			"128K" },
    195 	{ TWE_AD_STRIPE_256k,			"256K" },
    196 	{ TWE_AD_STRIPE_512k,			"512K" },
    197 	{ TWE_AD_STRIPE_1024k,			"1024K" },
    198 
    199 	{ 0,					NULL }
    200 };
    201 
    202 /*
    203  * Asynchronous event notification messages are qualified:
    204  *	a - not unit/port specific
    205  *	u - unit specific
    206  *	p - port specific
    207  *
    208  * They are further qualified with a severity:
    209  *	E - LOG_EMERG
    210  *	a - LOG_ALERT
    211  *	c - LOG_CRIT
    212  *	e - LOG_ERR
    213  *	w - LOG_WARNING
    214  *	n - LOG_NOTICE
    215  *	i - LOG_INFO
    216  *	d - LOG_DEBUG
    217  *	blank - just use printf
    218  */
    219 const struct twe_code_table twe_table_aen[] = {
    220 	{ 0x00,	"a  queue empty" },
    221 	{ 0x01,	"a  soft reset" },
    222 	{ 0x02,	"uc degraded mode" },
    223 	{ 0x03,	"aa controller error" },
    224 	{ 0x04,	"uE rebuild fail" },
    225 	{ 0x05,	"un rebuild done" },
    226 	{ 0x06,	"ue incomplete unit" },
    227 	{ 0x07,	"un initialization done" },
    228 	{ 0x08,	"uw unclean shutdown detected" },
    229 	{ 0x09,	"pe drive timeout" },
    230 	{ 0x0a,	"pc drive error" },
    231 	{ 0x0b,	"un rebuild started" },
    232 	{ 0x0c,	"un initialization started" },
    233 	{ 0x0d,	"ui logical unit deleted" },
    234 	{ 0x0f,	"pc SMART threshold exceeded" },
    235 	{ 0x15,	"a  table undefined" },	/* XXX: Not in FreeBSD's table */
    236 	{ 0x21,	"pe ATA UDMA downgrade" },
    237 	{ 0x22,	"pi ATA UDMA upgrade" },
    238 	{ 0x23,	"pw sector repair occurred" },
    239 	{ 0x24,	"aa SBUF integrity check failure" },
    240 	{ 0x25,	"pa lost cached write" },
    241 	{ 0x26,	"pa drive ECC error detected" },
    242 	{ 0x27,	"pe DCB checksum error" },
    243 	{ 0x28,	"pn DCB unsupported version" },
    244 	{ 0x29,	"ui verify started" },
    245 	{ 0x2a,	"ua verify failed" },
    246 	{ 0x2b,	"ui verify complete" },
    247 	{ 0x2c,	"pw overwrote bad sector during rebuild" },
    248 	{ 0x2d,	"pa encountered bad sector during rebuild" },
    249 	{ 0x2e,	"pe replacement drive too small" },
    250 	{ 0x2f,	"ue array not previously initialized" },
    251 	{ 0x30,	"p  drive not supported" },
    252 	{ 0xff,	"a  aen queue full" },
    253 
    254 	{ 0,	NULL },
    255 };
    256 
    257 const char *
    258 twe_describe_code(const struct twe_code_table *table, uint32_t code)
    259 {
    260 
    261 	for (; table->string != NULL; table++) {
    262 		if (table->code == code)
    263 			return (table->string);
    264 	}
    265 	return (NULL);
    266 }
    267 
    268 static inline u_int32_t
    269 twe_inl(struct twe_softc *sc, int off)
    270 {
    271 
    272 	bus_space_barrier(sc->sc_iot, sc->sc_ioh, off, 4,
    273 	    BUS_SPACE_BARRIER_WRITE | BUS_SPACE_BARRIER_READ);
    274 	return (bus_space_read_4(sc->sc_iot, sc->sc_ioh, off));
    275 }
    276 
    277 static inline void
    278 twe_outl(struct twe_softc *sc, int off, u_int32_t val)
    279 {
    280 
    281 	bus_space_write_4(sc->sc_iot, sc->sc_ioh, off, val);
    282 	bus_space_barrier(sc->sc_iot, sc->sc_ioh, off, 4,
    283 	    BUS_SPACE_BARRIER_WRITE);
    284 }
    285 
    286 /*
    287  * Match a supported board.
    288  */
    289 static int
    290 twe_match(device_t parent, cfdata_t cfdata, void *aux)
    291 {
    292 	struct pci_attach_args *pa;
    293 
    294 	pa = aux;
    295 
    296 	return (PCI_VENDOR(pa->pa_id) == PCI_VENDOR_3WARE &&
    297 	    (PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_3WARE_ESCALADE ||
    298 	    PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_3WARE_ESCALADE_ASIC));
    299 }
    300 
    301 /*
    302  * Attach a supported board.
    303  *
    304  * XXX This doesn't fail gracefully.
    305  */
    306 static void
    307 twe_attach(device_t parent, device_t self, void *aux)
    308 {
    309 	struct pci_attach_args *pa;
    310 	struct twe_softc *sc;
    311 	pci_chipset_tag_t pc;
    312 	pci_intr_handle_t ih;
    313 	pcireg_t csr;
    314 	const char *intrstr;
    315 	int s, size, i, rv, rseg;
    316 	size_t max_segs, max_xfer;
    317 	bus_dma_segment_t seg;
    318 	const struct sysctlnode *node;
    319 	struct twe_cmd *tc;
    320 	struct twe_ccb *ccb;
    321 	char intrbuf[PCI_INTRSTR_LEN];
    322 
    323 	sc = device_private(self);
    324 	sc->sc_dev = self;
    325 	pa = aux;
    326 	pc = pa->pa_pc;
    327 	sc->sc_dmat = pa->pa_dmat;
    328 	SIMPLEQ_INIT(&sc->sc_ccb_queue);
    329 	SLIST_INIT(&sc->sc_ccb_freelist);
    330 
    331 	aprint_naive(": RAID controller\n");
    332 	aprint_normal(": 3ware Escalade\n");
    333 
    334 
    335 	if (pci_mapreg_map(pa, PCI_CBIO, PCI_MAPREG_TYPE_IO, 0,
    336 	    &sc->sc_iot, &sc->sc_ioh, NULL, NULL)) {
    337 		aprint_error_dev(self, "can't map i/o space\n");
    338 		return;
    339 	}
    340 
    341 	/* Enable the device. */
    342 	csr = pci_conf_read(pa->pa_pc, pa->pa_tag, PCI_COMMAND_STATUS_REG);
    343 	pci_conf_write(pa->pa_pc, pa->pa_tag, PCI_COMMAND_STATUS_REG,
    344 	    csr | PCI_COMMAND_MASTER_ENABLE);
    345 
    346 	/* Map and establish the interrupt. */
    347 	if (pci_intr_map(pa, &ih)) {
    348 		aprint_error_dev(self, "can't map interrupt\n");
    349 		return;
    350 	}
    351 
    352 	intrstr = pci_intr_string(pc, ih, intrbuf, sizeof(intrbuf));
    353 	sc->sc_ih = pci_intr_establish(pc, ih, IPL_BIO, twe_intr, sc);
    354 	if (sc->sc_ih == NULL) {
    355 		aprint_error_dev(self, "can't establish interrupt%s%s\n",
    356 			(intrstr) ? " at " : "",
    357 			(intrstr) ? intrstr : "");
    358 		return;
    359 	}
    360 
    361 	if (intrstr != NULL)
    362 		aprint_normal_dev(self, "interrupting at %s\n",
    363 			intrstr);
    364 
    365 	/*
    366 	 * Allocate and initialise the command blocks and CCBs.
    367 	 */
    368 	size = sizeof(struct twe_cmd) * TWE_MAX_QUEUECNT;
    369 
    370 	if ((rv = bus_dmamem_alloc(sc->sc_dmat, size, PAGE_SIZE, 0, &seg, 1,
    371 	    &rseg, BUS_DMA_NOWAIT)) != 0) {
    372 		aprint_error_dev(self, "unable to allocate commands, rv = %d\n", rv);
    373 		return;
    374 	}
    375 
    376 	if ((rv = bus_dmamem_map(sc->sc_dmat, &seg, rseg, size,
    377 	    (void **)&sc->sc_cmds,
    378 	    BUS_DMA_NOWAIT | BUS_DMA_COHERENT)) != 0) {
    379 		aprint_error_dev(self, "unable to map commands, rv = %d\n", rv);
    380 		return;
    381 	}
    382 
    383 	if ((rv = bus_dmamap_create(sc->sc_dmat, size, size, 1, 0,
    384 	    BUS_DMA_NOWAIT, &sc->sc_dmamap)) != 0) {
    385 		aprint_error_dev(self, "unable to create command DMA map, rv = %d\n", rv);
    386 		return;
    387 	}
    388 
    389 	if ((rv = bus_dmamap_load(sc->sc_dmat, sc->sc_dmamap, sc->sc_cmds,
    390 	    size, NULL, BUS_DMA_NOWAIT)) != 0) {
    391 		aprint_error_dev(self, "unable to load command DMA map, rv = %d\n", rv);
    392 		return;
    393 	}
    394 
    395 	ccb = malloc(sizeof(*ccb) * TWE_MAX_QUEUECNT, M_DEVBUF, M_NOWAIT);
    396 	if (ccb == NULL) {
    397 		aprint_error_dev(self, "unable to allocate memory for ccbs\n");
    398 		return;
    399 	}
    400 
    401 	sc->sc_cmds_paddr = sc->sc_dmamap->dm_segs[0].ds_addr;
    402 	memset(sc->sc_cmds, 0, size);
    403 
    404 	sc->sc_ccbs = ccb;
    405 	tc = (struct twe_cmd *)sc->sc_cmds;
    406 	max_segs = twe_get_maxsegs();
    407 	max_xfer = twe_get_maxxfer(max_segs);
    408 
    409 	for (i = 0; i < TWE_MAX_QUEUECNT; i++, tc++, ccb++) {
    410 		ccb->ccb_cmd = tc;
    411 		ccb->ccb_cmdid = i;
    412 		ccb->ccb_flags = 0;
    413 		rv = bus_dmamap_create(sc->sc_dmat, max_xfer,
    414 		    max_segs, PAGE_SIZE, 0,
    415 		    BUS_DMA_NOWAIT | BUS_DMA_ALLOCNOW,
    416 		    &ccb->ccb_dmamap_xfer);
    417 		if (rv != 0) {
    418 			aprint_error_dev(self, "can't create dmamap, rv = %d\n", rv);
    419 			return;
    420 		}
    421 
    422 		/* Save the first CCB for AEN retrieval. */
    423 		if (i != 0)
    424 			SLIST_INSERT_HEAD(&sc->sc_ccb_freelist, ccb,
    425 			    ccb_chain.slist);
    426 	}
    427 
    428 	/* Wait for the controller to become ready. */
    429 	if (twe_status_wait(sc, TWE_STS_MICROCONTROLLER_READY, 6)) {
    430 		aprint_error_dev(self, "microcontroller not ready\n");
    431 		return;
    432 	}
    433 
    434 	twe_outl(sc, TWE_REG_CTL, TWE_CTL_DISABLE_INTRS);
    435 
    436 	/* Reset the controller. */
    437 	s = splbio();
    438 	rv = twe_reset(sc);
    439 	splx(s);
    440 	if (rv) {
    441 		aprint_error_dev(self, "reset failed\n");
    442 		return;
    443 	}
    444 
    445 	/* Initialise connection with controller. */
    446 	twe_init_connection(sc);
    447 
    448 	twe_describe_controller(sc);
    449 
    450 	/* Find and attach RAID array units. */
    451 	sc->sc_nunits = 0;
    452 	for (i = 0; i < TWE_MAX_UNITS; i++)
    453 		(void) twe_add_unit(sc, i);
    454 
    455 	/* ...and finally, enable interrupts. */
    456 	twe_outl(sc, TWE_REG_CTL, TWE_CTL_CLEAR_ATTN_INTR |
    457 	    TWE_CTL_UNMASK_RESP_INTR |
    458 	    TWE_CTL_ENABLE_INTRS);
    459 
    460 	/* sysctl set-up for 3ware cli */
    461 	if (sysctl_createv(NULL, 0, NULL, &node,
    462 				0, CTLTYPE_NODE, device_xname(self),
    463 				SYSCTL_DESCR("twe driver information"),
    464 				NULL, 0, NULL, 0,
    465 				CTL_HW, CTL_CREATE, CTL_EOL) != 0) {
    466 		aprint_error_dev(self, "could not create %s.%s sysctl node\n",
    467 			"hw", device_xname(self));
    468 		return;
    469 	}
    470 	if ((i = sysctl_createv(NULL, 0, NULL, NULL,
    471 				0, CTLTYPE_STRING, "driver_version",
    472 				SYSCTL_DESCR("twe0 driver version"),
    473 				NULL, 0, __UNCONST(&twever), 0,
    474 				CTL_HW, node->sysctl_num, CTL_CREATE, CTL_EOL))
    475 				!= 0) {
    476 		aprint_error_dev(self, "could not create %s.%s.driver_version sysctl\n",
    477 			"hw", device_xname(self));
    478 		return;
    479 	}
    480 }
    481 
    482 void
    483 twe_register_callbacks(struct twe_softc *sc, int unit,
    484     const struct twe_callbacks *tcb)
    485 {
    486 
    487 	sc->sc_units[unit].td_callbacks = tcb;
    488 }
    489 
    490 static void
    491 twe_recompute_openings(struct twe_softc *sc)
    492 {
    493 	struct twe_drive *td;
    494 	int unit, openings;
    495 
    496 	if (sc->sc_nunits != 0)
    497 		openings = (TWE_MAX_QUEUECNT - 1) / sc->sc_nunits;
    498 	else
    499 		openings = 0;
    500 	if (openings == sc->sc_openings)
    501 		return;
    502 	sc->sc_openings = openings;
    503 
    504 #ifdef TWE_DEBUG
    505 	printf("%s: %d array%s, %d openings per array\n",
    506 	    device_xname(sc->sc_dev), sc->sc_nunits,
    507 	    sc->sc_nunits == 1 ? "" : "s", sc->sc_openings);
    508 #endif
    509 
    510 	for (unit = 0; unit < TWE_MAX_UNITS; unit++) {
    511 		td = &sc->sc_units[unit];
    512 		if (td->td_dev != NULL)
    513 			(*td->td_callbacks->tcb_openings)(td->td_dev,
    514 			    sc->sc_openings);
    515 	}
    516 }
    517 
    518 static int
    519 twe_add_unit(struct twe_softc *sc, int unit)
    520 {
    521 	struct twe_param *dtp, *atp;
    522 	struct twe_array_descriptor *ad;
    523 	struct twe_drive *td;
    524 	struct twe_attach_args twea;
    525 	uint32_t newsize;
    526 	int rv;
    527 	uint16_t dsize;
    528 	uint8_t newtype, newstripe;
    529 	int locs[TWECF_NLOCS];
    530 
    531 	if (unit < 0 || unit >= TWE_MAX_UNITS)
    532 		return (EINVAL);
    533 
    534 	/* Find attached units. */
    535 	rv = twe_param_get(sc, TWE_PARAM_UNITSUMMARY,
    536 	    TWE_PARAM_UNITSUMMARY_Status, TWE_MAX_UNITS, NULL, &dtp);
    537 	if (rv != 0) {
    538 		aprint_error_dev(sc->sc_dev, "error %d fetching unit summary\n",
    539 		    rv);
    540 		return (rv);
    541 	}
    542 
    543 	/* For each detected unit, collect size and store in an array. */
    544 	td = &sc->sc_units[unit];
    545 
    546 	/* Unit present? */
    547 	if ((dtp->tp_data[unit] & TWE_PARAM_UNITSTATUS_Online) == 0) {
    548 		/*
    549 		 * XXX Should we check to see if a device has been
    550 		 * XXX attached at this index and detach it if it
    551 		 * XXX has?  ("rescan" semantics)
    552 		 */
    553 		rv = 0;
    554 		goto out;
    555    	}
    556 
    557 	rv = twe_param_get_2(sc, TWE_PARAM_UNITINFO + unit,
    558 	    TWE_PARAM_UNITINFO_DescriptorSize, &dsize);
    559 	if (rv != 0) {
    560 		aprint_error_dev(sc->sc_dev, "error %d fetching descriptor size "
    561 		    "for unit %d\n", rv, unit);
    562 		goto out;
    563 	}
    564 
    565 	rv = twe_param_get(sc, TWE_PARAM_UNITINFO + unit,
    566 	    TWE_PARAM_UNITINFO_Descriptor, dsize - 3, NULL, &atp);
    567 	if (rv != 0) {
    568 		aprint_error_dev(sc->sc_dev, "error %d fetching array descriptor "
    569 		    "for unit %d\n", rv, unit);
    570 		goto out;
    571 	}
    572 
    573 	ad = (struct twe_array_descriptor *)atp->tp_data;
    574 	newtype = ad->configuration;
    575 	newstripe = ad->stripe_size;
    576 	free(atp, M_DEVBUF);
    577 
    578 	rv = twe_param_get_4(sc, TWE_PARAM_UNITINFO + unit,
    579 	    TWE_PARAM_UNITINFO_Capacity, &newsize);
    580 	if (rv != 0) {
    581 		aprint_error_dev(sc->sc_dev,
    582 		    "error %d fetching capacity for unit %d\n",
    583 		    rv, unit);
    584 		goto out;
    585 	}
    586 
    587 	/*
    588 	 * Have a device, so we need to attach it.  If there is currently
    589 	 * something sitting at the slot, and the parameters are different,
    590 	 * then we detach the old device before attaching the new one.
    591 	 */
    592 	if (td->td_dev != NULL &&
    593 	    td->td_size == newsize &&
    594 	    td->td_type == newtype &&
    595 	    td->td_stripe == newstripe) {
    596 		/* Same as the old device; just keep using it. */
    597 		rv = 0;
    598 		goto out;
    599 	} else if (td->td_dev != NULL) {
    600 		/* Detach the old device first. */
    601 		(void) config_detach(td->td_dev, DETACH_FORCE);
    602 		td->td_dev = NULL;
    603 	} else if (td->td_size == 0)
    604 		sc->sc_nunits++;
    605 
    606 	/*
    607 	 * Committed to the new array unit; assign its parameters and
    608 	 * recompute the number of available command openings.
    609 	 */
    610 	td->td_size = newsize;
    611 	td->td_type = newtype;
    612 	td->td_stripe = newstripe;
    613 	twe_recompute_openings(sc);
    614 
    615 	twea.twea_unit = unit;
    616 
    617 	locs[TWECF_UNIT] = unit;
    618 
    619 	td->td_dev = config_found_sm_loc(sc->sc_dev, "twe", locs, &twea,
    620 					 twe_print, config_stdsubmatch);
    621 
    622 	rv = 0;
    623  out:
    624 	free(dtp, M_DEVBUF);
    625 	return (rv);
    626 }
    627 
    628 static int
    629 twe_del_unit(struct twe_softc *sc, int unit)
    630 {
    631 	struct twe_drive *td;
    632 
    633 	if (unit < 0 || unit >= TWE_MAX_UNITS)
    634 		return (EINVAL);
    635 
    636 	td = &sc->sc_units[unit];
    637 	if (td->td_size != 0)
    638 		sc->sc_nunits--;
    639 	td->td_size = 0;
    640 	td->td_type = 0;
    641 	td->td_stripe = 0;
    642 	if (td->td_dev != NULL) {
    643 		(void) config_detach(td->td_dev, DETACH_FORCE);
    644 		td->td_dev = NULL;
    645 	}
    646 	twe_recompute_openings(sc);
    647 	return (0);
    648 }
    649 
    650 /*
    651  * Reset the controller.
    652  * MUST BE CALLED AT splbio()!
    653  */
    654 static int
    655 twe_reset(struct twe_softc *sc)
    656 {
    657 	uint16_t aen;
    658 	u_int status;
    659 	int got, rv;
    660 
    661 	/* Issue a soft reset. */
    662 	twe_outl(sc, TWE_REG_CTL, TWE_CTL_ISSUE_SOFT_RESET |
    663 	    TWE_CTL_CLEAR_HOST_INTR |
    664 	    TWE_CTL_CLEAR_ATTN_INTR |
    665 	    TWE_CTL_MASK_CMD_INTR |
    666 	    TWE_CTL_MASK_RESP_INTR |
    667 	    TWE_CTL_CLEAR_ERROR_STS |
    668 	    TWE_CTL_DISABLE_INTRS);
    669 
    670 	/* Wait for attention... */
    671 	if (twe_status_wait(sc, TWE_STS_ATTN_INTR, 30)) {
    672 		aprint_error_dev(sc->sc_dev, "timeout waiting for attention interrupt\n");
    673 		return (-1);
    674 	}
    675 
    676 	/* ...and ACK it. */
    677 	twe_outl(sc, TWE_REG_CTL, TWE_CTL_CLEAR_ATTN_INTR);
    678 
    679 	/*
    680 	 * Pull AENs out of the controller; look for a soft reset AEN.
    681 	 * Open code this, since we want to detect reset even if the
    682 	 * queue for management tools is full.
    683 	 *
    684 	 * Note that since:
    685 	 *	- interrupts are blocked
    686 	 *	- we have reset the controller
    687 	 *	- acknowledged the pending ATTENTION
    688 	 * that there is no way a pending asynchronous AEN fetch would
    689 	 * finish, so clear the flag.
    690 	 */
    691 	sc->sc_flags &= ~TWEF_AEN;
    692 	for (got = 0;;) {
    693 		rv = twe_aen_get(sc, &aen);
    694 		if (rv != 0)
    695 			printf("%s: error %d while draining event queue\n",
    696 			    device_xname(sc->sc_dev), rv);
    697 		if (TWE_AEN_CODE(aen) == TWE_AEN_QUEUE_EMPTY)
    698 			break;
    699 		if (TWE_AEN_CODE(aen) == TWE_AEN_SOFT_RESET)
    700 			got = 1;
    701 		twe_aen_enqueue(sc, aen, 1);
    702 	}
    703 
    704 	if (!got) {
    705 		printf("%s: reset not reported\n", device_xname(sc->sc_dev));
    706 		return (-1);
    707 	}
    708 
    709 	/* Check controller status. */
    710 	status = twe_inl(sc, TWE_REG_STS);
    711 	if (twe_status_check(sc, status)) {
    712 		printf("%s: controller errors detected\n",
    713 		    device_xname(sc->sc_dev));
    714 		return (-1);
    715 	}
    716 
    717 	/* Drain the response queue. */
    718 	for (;;) {
    719 		status = twe_inl(sc, TWE_REG_STS);
    720 		if (twe_status_check(sc, status) != 0) {
    721 			aprint_error_dev(sc->sc_dev, "can't drain response queue\n");
    722 			return (-1);
    723 		}
    724 		if ((status & TWE_STS_RESP_QUEUE_EMPTY) != 0)
    725 			break;
    726 		(void)twe_inl(sc, TWE_REG_RESP_QUEUE);
    727 	}
    728 
    729 	return (0);
    730 }
    731 
    732 /*
    733  * Print autoconfiguration message for a sub-device.
    734  */
    735 static int
    736 twe_print(void *aux, const char *pnp)
    737 {
    738 	struct twe_attach_args *twea;
    739 
    740 	twea = aux;
    741 
    742 	if (pnp != NULL)
    743 		aprint_normal("block device at %s", pnp);
    744 	aprint_normal(" unit %d", twea->twea_unit);
    745 	return (UNCONF);
    746 }
    747 
    748 /*
    749  * Interrupt service routine.
    750  */
    751 static int
    752 twe_intr(void *arg)
    753 {
    754 	struct twe_softc *sc;
    755 	u_int status;
    756 	int caught, rv;
    757 
    758 	sc = arg;
    759 	caught = 0;
    760 	status = twe_inl(sc, TWE_REG_STS);
    761 	twe_status_check(sc, status);
    762 
    763 	/* Host interrupts - purpose unknown. */
    764 	if ((status & TWE_STS_HOST_INTR) != 0) {
    765 #ifdef DEBUG
    766 		printf("%s: host interrupt\n", device_xname(sc->sc_dev));
    767 #endif
    768 		twe_outl(sc, TWE_REG_CTL, TWE_CTL_CLEAR_HOST_INTR);
    769 		caught = 1;
    770 	}
    771 
    772 	/*
    773 	 * Attention interrupts, signalled when a controller or child device
    774 	 * state change has occurred.
    775 	 */
    776 	if ((status & TWE_STS_ATTN_INTR) != 0) {
    777 		rv = twe_aen_get(sc, NULL);
    778 		if (rv != 0)
    779 			aprint_error_dev(sc->sc_dev, "unable to retrieve AEN (%d)\n", rv);
    780 		else
    781 			twe_outl(sc, TWE_REG_CTL, TWE_CTL_CLEAR_ATTN_INTR);
    782 		caught = 1;
    783 	}
    784 
    785 	/*
    786 	 * Command interrupts, signalled when the controller can accept more
    787 	 * commands.  We don't use this; instead, we try to submit commands
    788 	 * when we receive them, and when other commands have completed.
    789 	 * Mask it so we don't get another one.
    790 	 */
    791 	if ((status & TWE_STS_CMD_INTR) != 0) {
    792 #ifdef DEBUG
    793 		printf("%s: command interrupt\n", device_xname(sc->sc_dev));
    794 #endif
    795 		twe_outl(sc, TWE_REG_CTL, TWE_CTL_MASK_CMD_INTR);
    796 		caught = 1;
    797 	}
    798 
    799 	if ((status & TWE_STS_RESP_INTR) != 0) {
    800 		twe_poll(sc);
    801 		caught = 1;
    802 	}
    803 
    804 	return (caught);
    805 }
    806 
    807 /*
    808  * Fetch an AEN.  Even though this is really like parameter
    809  * retrieval, we handle this specially, because we issue this
    810  * AEN retrieval command from interrupt context, and thus
    811  * reserve a CCB for it to avoid resource shortage.
    812  *
    813  * XXX There are still potential resource shortages we could
    814  * XXX encounter.  Consider pre-allocating all AEN-related
    815  * XXX resources.
    816  *
    817  * MUST BE CALLED AT splbio()!
    818  */
    819 static int
    820 twe_aen_get(struct twe_softc *sc, uint16_t *aenp)
    821 {
    822 	struct twe_ccb *ccb;
    823 	struct twe_cmd *tc;
    824 	struct twe_param *tp;
    825 	int rv;
    826 
    827 	/*
    828 	 * If we're already retrieving an AEN, just wait; another
    829 	 * retrieval will be chained after the current one completes.
    830 	 */
    831 	if (sc->sc_flags & TWEF_AEN) {
    832 		/*
    833 		 * It is a fatal software programming error to attempt
    834 		 * to fetch an AEN synchronously when an AEN fetch is
    835 		 * already pending.
    836 		 */
    837 		KASSERT(aenp == NULL);
    838 		return (0);
    839 	}
    840 
    841 	tp = malloc(TWE_SECTOR_SIZE, M_DEVBUF, M_NOWAIT);
    842 	if (tp == NULL)
    843 		return (ENOMEM);
    844 
    845 	ccb = twe_ccb_alloc(sc,
    846 	    TWE_CCB_AEN | TWE_CCB_DATA_IN | TWE_CCB_DATA_OUT);
    847 	KASSERT(ccb != NULL);
    848 
    849 	ccb->ccb_data = tp;
    850 	ccb->ccb_datasize = TWE_SECTOR_SIZE;
    851 	ccb->ccb_tx.tx_handler = (aenp == NULL) ? twe_aen_handler : NULL;
    852 	ccb->ccb_tx.tx_context = tp;
    853 	ccb->ccb_tx.tx_dv = sc->sc_dev;
    854 
    855 	tc = ccb->ccb_cmd;
    856 	tc->tc_size = 2;
    857 	tc->tc_opcode = TWE_OP_GET_PARAM | (tc->tc_size << 5);
    858 	tc->tc_unit = 0;
    859 	tc->tc_count = htole16(1);
    860 
    861 	/* Fill in the outbound parameter data. */
    862 	tp->tp_table_id = htole16(TWE_PARAM_AEN);
    863 	tp->tp_param_id = TWE_PARAM_AEN_UnitCode;
    864 	tp->tp_param_size = 2;
    865 
    866 	/* Map the transfer. */
    867 	if ((rv = twe_ccb_map(sc, ccb)) != 0) {
    868 		twe_ccb_free(sc, ccb);
    869 		goto done;
    870 	}
    871 
    872 	/* Enqueue the command and wait. */
    873 	if (aenp != NULL) {
    874 		rv = twe_ccb_poll(sc, ccb, 5);
    875 		twe_ccb_unmap(sc, ccb);
    876 		twe_ccb_free(sc, ccb);
    877 		if (rv == 0)
    878 			*aenp = le16toh(*(uint16_t *)tp->tp_data);
    879 		free(tp, M_DEVBUF);
    880 	} else {
    881 		sc->sc_flags |= TWEF_AEN;
    882 		twe_ccb_enqueue(sc, ccb);
    883 		rv = 0;
    884 	}
    885 
    886  done:
    887 	return (rv);
    888 }
    889 
    890 /*
    891  * Handle an AEN returned by the controller.
    892  * MUST BE CALLED AT splbio()!
    893  */
    894 static void
    895 twe_aen_handler(struct twe_ccb *ccb, int error)
    896 {
    897 	struct twe_softc *sc;
    898 	struct twe_param *tp;
    899 	uint16_t aen;
    900 	int rv;
    901 
    902 	sc = device_private(ccb->ccb_tx.tx_dv);
    903 	tp = ccb->ccb_tx.tx_context;
    904 	twe_ccb_unmap(sc, ccb);
    905 
    906 	sc->sc_flags &= ~TWEF_AEN;
    907 
    908 	if (error) {
    909 		aprint_error_dev(sc->sc_dev, "error retrieving AEN\n");
    910 		aen = TWE_AEN_QUEUE_EMPTY;
    911 	} else
    912 		aen = le16toh(*(u_int16_t *)tp->tp_data);
    913 	free(tp, M_DEVBUF);
    914 	twe_ccb_free(sc, ccb);
    915 
    916 	if (TWE_AEN_CODE(aen) == TWE_AEN_QUEUE_EMPTY) {
    917 		twe_outl(sc, TWE_REG_CTL, TWE_CTL_CLEAR_ATTN_INTR);
    918 		return;
    919 	}
    920 
    921 	twe_aen_enqueue(sc, aen, 0);
    922 
    923 	/*
    924 	 * Chain another retrieval in case interrupts have been
    925 	 * coalesced.
    926 	 */
    927 	rv = twe_aen_get(sc, NULL);
    928 	if (rv != 0)
    929 		aprint_error_dev(sc->sc_dev, "unable to retrieve AEN (%d)\n", rv);
    930 }
    931 
    932 static void
    933 twe_aen_enqueue(struct twe_softc *sc, uint16_t aen, int quiet)
    934 {
    935 	const char *str, *msg;
    936 	int s, next, nextnext, level;
    937 
    938 	/*
    939 	 * First report the AEN on the console.  Maybe.
    940 	 */
    941 	if (! quiet) {
    942 		str = twe_describe_code(twe_table_aen, TWE_AEN_CODE(aen));
    943 		if (str == NULL) {
    944 			aprint_error_dev(sc->sc_dev, "unknown AEN 0x%04x\n", aen);
    945 		} else {
    946 			msg = str + 3;
    947 			switch (str[1]) {
    948 			case 'E':	level = LOG_EMERG; break;
    949 			case 'a':	level = LOG_ALERT; break;
    950 			case 'c':	level = LOG_CRIT; break;
    951 			case 'e':	level = LOG_ERR; break;
    952 			case 'w':	level = LOG_WARNING; break;
    953 			case 'n':	level = LOG_NOTICE; break;
    954 			case 'i':	level = LOG_INFO; break;
    955 			case 'd':	level = LOG_DEBUG; break;
    956 			default:
    957 				/* Don't use syslog. */
    958 				level = -1;
    959 			}
    960 
    961 			if (level < 0) {
    962 				switch (str[0]) {
    963 				case 'u':
    964 				case 'p':
    965 					printf("%s: %s %d: %s\n",
    966 					    device_xname(sc->sc_dev),
    967 					    str[0] == 'u' ? "unit" : "port",
    968 					    TWE_AEN_UNIT(aen), msg);
    969 					break;
    970 
    971 				default:
    972 					printf("%s: %s\n",
    973 					    device_xname(sc->sc_dev), msg);
    974 				}
    975 			} else {
    976 				switch (str[0]) {
    977 				case 'u':
    978 				case 'p':
    979 					log(level, "%s: %s %d: %s\n",
    980 					    device_xname(sc->sc_dev),
    981 					    str[0] == 'u' ? "unit" : "port",
    982 					    TWE_AEN_UNIT(aen), msg);
    983 					break;
    984 
    985 				default:
    986 					log(level, "%s: %s\n",
    987 					    device_xname(sc->sc_dev), msg);
    988 				}
    989 			}
    990 		}
    991 	}
    992 
    993 	/* Now enqueue the AEN for mangement tools. */
    994 	s = splbio();
    995 
    996 	next = (sc->sc_aen_head + 1) % TWE_AEN_Q_LENGTH;
    997 	nextnext = (sc->sc_aen_head + 2) % TWE_AEN_Q_LENGTH;
    998 
    999 	/*
   1000 	 * If this is the last free slot, then queue up a "queue
   1001 	 * full" message.
   1002 	 */
   1003 	if (nextnext == sc->sc_aen_tail)
   1004 		aen = TWE_AEN_QUEUE_FULL;
   1005 
   1006 	if (next != sc->sc_aen_tail) {
   1007 		sc->sc_aen_queue[sc->sc_aen_head] = aen;
   1008 		sc->sc_aen_head = next;
   1009 	}
   1010 
   1011 	if (sc->sc_flags & TWEF_AENQ_WAIT) {
   1012 		sc->sc_flags &= ~TWEF_AENQ_WAIT;
   1013 		wakeup(&sc->sc_aen_queue);
   1014 	}
   1015 
   1016 	splx(s);
   1017 }
   1018 
   1019 /* NOTE: Must be called at splbio(). */
   1020 static uint16_t
   1021 twe_aen_dequeue(struct twe_softc *sc)
   1022 {
   1023 	uint16_t aen;
   1024 
   1025 	if (sc->sc_aen_tail == sc->sc_aen_head)
   1026 		aen = TWE_AEN_QUEUE_EMPTY;
   1027 	else {
   1028 		aen = sc->sc_aen_queue[sc->sc_aen_tail];
   1029 		sc->sc_aen_tail = (sc->sc_aen_tail + 1) % TWE_AEN_Q_LENGTH;
   1030 	}
   1031 
   1032 	return (aen);
   1033 }
   1034 
   1035 /*
   1036  * These are short-hand functions that execute TWE_OP_GET_PARAM to
   1037  * fetch 1, 2, and 4 byte parameter values, respectively.
   1038  */
   1039 int
   1040 twe_param_get_1(struct twe_softc *sc, int table_id, int param_id,
   1041     uint8_t *valp)
   1042 {
   1043 	struct twe_param *tp;
   1044 	int rv;
   1045 
   1046 	rv = twe_param_get(sc, table_id, param_id, 1, NULL, &tp);
   1047 	if (rv != 0)
   1048 		return (rv);
   1049 	*valp = *(uint8_t *)tp->tp_data;
   1050 	free(tp, M_DEVBUF);
   1051 	return (0);
   1052 }
   1053 
   1054 int
   1055 twe_param_get_2(struct twe_softc *sc, int table_id, int param_id,
   1056     uint16_t *valp)
   1057 {
   1058 	struct twe_param *tp;
   1059 	int rv;
   1060 
   1061 	rv = twe_param_get(sc, table_id, param_id, 2, NULL, &tp);
   1062 	if (rv != 0)
   1063 		return (rv);
   1064 	*valp = le16toh(*(uint16_t *)tp->tp_data);
   1065 	free(tp, M_DEVBUF);
   1066 	return (0);
   1067 }
   1068 
   1069 int
   1070 twe_param_get_4(struct twe_softc *sc, int table_id, int param_id,
   1071     uint32_t *valp)
   1072 {
   1073 	struct twe_param *tp;
   1074 	int rv;
   1075 
   1076 	rv = twe_param_get(sc, table_id, param_id, 4, NULL, &tp);
   1077 	if (rv != 0)
   1078 		return (rv);
   1079 	*valp = le32toh(*(uint32_t *)tp->tp_data);
   1080 	free(tp, M_DEVBUF);
   1081 	return (0);
   1082 }
   1083 
   1084 /*
   1085  * Execute a TWE_OP_GET_PARAM command.  If a callback function is provided,
   1086  * it will be called with generated context when the command has completed.
   1087  * If no callback is provided, the command will be executed synchronously
   1088  * and a pointer to a buffer containing the data returned.
   1089  *
   1090  * The caller or callback is responsible for freeing the buffer.
   1091  *
   1092  * NOTE: We assume we can sleep here to wait for a CCB to become available.
   1093  */
   1094 int
   1095 twe_param_get(struct twe_softc *sc, int table_id, int param_id, size_t size,
   1096 	      void (*func)(struct twe_ccb *, int), struct twe_param **pbuf)
   1097 {
   1098 	struct twe_ccb *ccb;
   1099 	struct twe_cmd *tc;
   1100 	struct twe_param *tp;
   1101 	int rv, s;
   1102 
   1103 	tp = malloc(TWE_SECTOR_SIZE, M_DEVBUF, M_NOWAIT);
   1104 	if (tp == NULL)
   1105 		return ENOMEM;
   1106 
   1107 	ccb = twe_ccb_alloc_wait(sc, TWE_CCB_DATA_IN | TWE_CCB_DATA_OUT);
   1108 	KASSERT(ccb != NULL);
   1109 
   1110 	ccb->ccb_data = tp;
   1111 	ccb->ccb_datasize = TWE_SECTOR_SIZE;
   1112 	ccb->ccb_tx.tx_handler = func;
   1113 	ccb->ccb_tx.tx_context = tp;
   1114 	ccb->ccb_tx.tx_dv = sc->sc_dev;
   1115 
   1116 	tc = ccb->ccb_cmd;
   1117 	tc->tc_size = 2;
   1118 	tc->tc_opcode = TWE_OP_GET_PARAM | (tc->tc_size << 5);
   1119 	tc->tc_unit = 0;
   1120 	tc->tc_count = htole16(1);
   1121 
   1122 	/* Fill in the outbound parameter data. */
   1123 	tp->tp_table_id = htole16(table_id);
   1124 	tp->tp_param_id = param_id;
   1125 	tp->tp_param_size = size;
   1126 
   1127 	/* Map the transfer. */
   1128 	if ((rv = twe_ccb_map(sc, ccb)) != 0) {
   1129 		twe_ccb_free(sc, ccb);
   1130 		goto done;
   1131 	}
   1132 
   1133 	/* Submit the command and either wait or let the callback handle it. */
   1134 	if (func == NULL) {
   1135 		s = splbio();
   1136 		rv = twe_ccb_poll(sc, ccb, 5);
   1137 		twe_ccb_unmap(sc, ccb);
   1138 		twe_ccb_free(sc, ccb);
   1139 		splx(s);
   1140 	} else {
   1141 #ifdef DEBUG
   1142 		if (pbuf != NULL)
   1143 			panic("both func and pbuf defined");
   1144 #endif
   1145 		twe_ccb_enqueue(sc, ccb);
   1146 		return 0;
   1147 	}
   1148 
   1149 done:
   1150 	if (pbuf == NULL || rv != 0)
   1151 		free(tp, M_DEVBUF);
   1152 	else if (pbuf != NULL && rv == 0)
   1153 		*pbuf = tp;
   1154 	return rv;
   1155 }
   1156 
   1157 /*
   1158  * Execute a TWE_OP_SET_PARAM command.
   1159  *
   1160  * NOTE: We assume we can sleep here to wait for a CCB to become available.
   1161  */
   1162 static int
   1163 twe_param_set(struct twe_softc *sc, int table_id, int param_id, size_t size,
   1164 	      void *sbuf)
   1165 {
   1166 	struct twe_ccb *ccb;
   1167 	struct twe_cmd *tc;
   1168 	struct twe_param *tp;
   1169 	int rv, s;
   1170 
   1171 	tp = malloc(TWE_SECTOR_SIZE, M_DEVBUF, M_NOWAIT);
   1172 	if (tp == NULL)
   1173 		return ENOMEM;
   1174 
   1175 	ccb = twe_ccb_alloc_wait(sc, TWE_CCB_DATA_IN | TWE_CCB_DATA_OUT);
   1176 	KASSERT(ccb != NULL);
   1177 
   1178 	ccb->ccb_data = tp;
   1179 	ccb->ccb_datasize = TWE_SECTOR_SIZE;
   1180 	ccb->ccb_tx.tx_handler = 0;
   1181 	ccb->ccb_tx.tx_context = tp;
   1182 	ccb->ccb_tx.tx_dv = sc->sc_dev;
   1183 
   1184 	tc = ccb->ccb_cmd;
   1185 	tc->tc_size = 2;
   1186 	tc->tc_opcode = TWE_OP_SET_PARAM | (tc->tc_size << 5);
   1187 	tc->tc_unit = 0;
   1188 	tc->tc_count = htole16(1);
   1189 
   1190 	/* Fill in the outbound parameter data. */
   1191 	tp->tp_table_id = htole16(table_id);
   1192 	tp->tp_param_id = param_id;
   1193 	tp->tp_param_size = size;
   1194 	memcpy(tp->tp_data, sbuf, size);
   1195 
   1196 	/* Map the transfer. */
   1197 	if ((rv = twe_ccb_map(sc, ccb)) != 0) {
   1198 		twe_ccb_free(sc, ccb);
   1199 		goto done;
   1200 	}
   1201 
   1202 	/* Submit the command and wait. */
   1203 	s = splbio();
   1204 	rv = twe_ccb_poll(sc, ccb, 5);
   1205 	twe_ccb_unmap(sc, ccb);
   1206 	twe_ccb_free(sc, ccb);
   1207 	splx(s);
   1208 done:
   1209 	free(tp, M_DEVBUF);
   1210 	return (rv);
   1211 }
   1212 
   1213 /*
   1214  * Execute a TWE_OP_INIT_CONNECTION command.  Return non-zero on error.
   1215  * Must be called with interrupts blocked.
   1216  */
   1217 static int
   1218 twe_init_connection(struct twe_softc *sc)
   1219 {
   1220 	struct twe_ccb *ccb;
   1221 	struct twe_cmd *tc;
   1222 	int rv;
   1223 
   1224 	if ((ccb = twe_ccb_alloc(sc, 0)) == NULL)
   1225 		return (EAGAIN);
   1226 
   1227 	/* Build the command. */
   1228 	tc = ccb->ccb_cmd;
   1229 	tc->tc_size = 3;
   1230 	tc->tc_opcode = TWE_OP_INIT_CONNECTION;
   1231 	tc->tc_unit = 0;
   1232 	tc->tc_count = htole16(TWE_MAX_CMDS);
   1233 	tc->tc_args.init_connection.response_queue_pointer = 0;
   1234 
   1235 	/* Submit the command for immediate execution. */
   1236 	rv = twe_ccb_poll(sc, ccb, 5);
   1237 	twe_ccb_free(sc, ccb);
   1238 	return (rv);
   1239 }
   1240 
   1241 /*
   1242  * Poll the controller for completed commands.  Must be called with
   1243  * interrupts blocked.
   1244  */
   1245 static void
   1246 twe_poll(struct twe_softc *sc)
   1247 {
   1248 	struct twe_ccb *ccb;
   1249 	int found;
   1250 	u_int status, cmdid;
   1251 
   1252 	found = 0;
   1253 
   1254 	for (;;) {
   1255 		status = twe_inl(sc, TWE_REG_STS);
   1256 		twe_status_check(sc, status);
   1257 
   1258 		if ((status & TWE_STS_RESP_QUEUE_EMPTY))
   1259 			break;
   1260 
   1261 		found = 1;
   1262 		cmdid = twe_inl(sc, TWE_REG_RESP_QUEUE);
   1263 		cmdid = (cmdid & TWE_RESP_MASK) >> TWE_RESP_SHIFT;
   1264 		if (cmdid >= TWE_MAX_QUEUECNT) {
   1265 			aprint_error_dev(sc->sc_dev, "bad cmdid %d\n", cmdid);
   1266 			continue;
   1267 		}
   1268 
   1269 		ccb = sc->sc_ccbs + cmdid;
   1270 		if ((ccb->ccb_flags & TWE_CCB_ACTIVE) == 0) {
   1271 			printf("%s: CCB for cmdid %d not active\n",
   1272 			    device_xname(sc->sc_dev), cmdid);
   1273 			continue;
   1274 		}
   1275 		ccb->ccb_flags ^= TWE_CCB_COMPLETE | TWE_CCB_ACTIVE;
   1276 
   1277 		bus_dmamap_sync(sc->sc_dmat, sc->sc_dmamap,
   1278 		    (char *)ccb->ccb_cmd - (char *)sc->sc_cmds,
   1279 		    sizeof(struct twe_cmd),
   1280 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
   1281 
   1282 		/* Pass notification to upper layers. */
   1283 		if (ccb->ccb_tx.tx_handler != NULL)
   1284 			(*ccb->ccb_tx.tx_handler)(ccb,
   1285 			    ccb->ccb_cmd->tc_status != 0 ? EIO : 0);
   1286 	}
   1287 
   1288 	/* If any commands have completed, run the software queue. */
   1289 	if (found)
   1290 		twe_ccb_enqueue(sc, NULL);
   1291 }
   1292 
   1293 /*
   1294  * Wait for `status' to be set in the controller status register.  Return
   1295  * zero if found, non-zero if the operation timed out.
   1296  */
   1297 static int
   1298 twe_status_wait(struct twe_softc *sc, u_int32_t status, int timo)
   1299 {
   1300 
   1301 	for (timo *= 10; timo != 0; timo--) {
   1302 		if ((twe_inl(sc, TWE_REG_STS) & status) == status)
   1303 			break;
   1304 		delay(100000);
   1305 	}
   1306 
   1307 	return (timo == 0);
   1308 }
   1309 
   1310 /*
   1311  * Clear a PCI parity error.
   1312  */
   1313 static void
   1314 twe_clear_pci_parity_error(struct twe_softc *sc)
   1315 {
   1316 	bus_space_write_4(sc->sc_iot, sc->sc_ioh, 0x0, TWE_CTL_CLEAR_PARITY_ERROR);
   1317 
   1318 	//FreeBSD: pci_write_config(sc->twe_dev, PCIR_STATUS, TWE_PCI_CLEAR_PARITY_ERROR, 2);
   1319 }
   1320 
   1321 
   1322 /*
   1323  * Clear a PCI abort.
   1324  */
   1325 static void
   1326 twe_clear_pci_abort(struct twe_softc *sc)
   1327 {
   1328 	bus_space_write_4(sc->sc_iot, sc->sc_ioh, 0x0, TWE_CTL_CLEAR_PCI_ABORT);
   1329 
   1330 	//FreeBSD: pci_write_config(sc->twe_dev, PCIR_STATUS, TWE_PCI_CLEAR_PCI_ABORT, 2);
   1331 }
   1332 
   1333 /*
   1334  * Complain if the status bits aren't what we expect.
   1335  */
   1336 static int
   1337 twe_status_check(struct twe_softc *sc, u_int status)
   1338 {
   1339 	int rv;
   1340 
   1341 	rv = 0;
   1342 
   1343 	if ((status & TWE_STS_EXPECTED_BITS) != TWE_STS_EXPECTED_BITS) {
   1344 		aprint_error_dev(sc->sc_dev, "missing status bits: 0x%08x\n",
   1345 		    status & ~TWE_STS_EXPECTED_BITS);
   1346 		rv = -1;
   1347 	}
   1348 
   1349 	if ((status & TWE_STS_UNEXPECTED_BITS) != 0) {
   1350 		aprint_error_dev(sc->sc_dev, "unexpected status bits: 0x%08x\n",
   1351 		    status & TWE_STS_UNEXPECTED_BITS);
   1352 		rv = -1;
   1353 		if (status & TWE_STS_PCI_PARITY_ERROR) {
   1354 			aprint_error_dev(sc->sc_dev, "PCI parity error: Reseat card, move card "
   1355 			       "or buggy device present.\n");
   1356 			twe_clear_pci_parity_error(sc);
   1357 		}
   1358 		if (status & TWE_STS_PCI_ABORT) {
   1359 			aprint_error_dev(sc->sc_dev, "PCI abort, clearing.\n");
   1360 			twe_clear_pci_abort(sc);
   1361 		}
   1362 	}
   1363 
   1364 	return (rv);
   1365 }
   1366 
   1367 /*
   1368  * Allocate and initialise a CCB.
   1369  */
   1370 static inline void
   1371 twe_ccb_init(struct twe_softc *sc, struct twe_ccb *ccb, int flags)
   1372 {
   1373 	struct twe_cmd *tc;
   1374 
   1375 	ccb->ccb_tx.tx_handler = NULL;
   1376 	ccb->ccb_flags = flags;
   1377 	tc = ccb->ccb_cmd;
   1378 	tc->tc_status = 0;
   1379 	tc->tc_flags = 0;
   1380 	tc->tc_cmdid = ccb->ccb_cmdid;
   1381 }
   1382 
   1383 struct twe_ccb *
   1384 twe_ccb_alloc(struct twe_softc *sc, int flags)
   1385 {
   1386 	struct twe_ccb *ccb;
   1387 	int s;
   1388 
   1389 	s = splbio();
   1390 	if (__predict_false((flags & TWE_CCB_AEN) != 0)) {
   1391 		/* Use the reserved CCB. */
   1392 		ccb = sc->sc_ccbs;
   1393 	} else {
   1394 		/* Allocate a CCB and command block. */
   1395 		if (__predict_false((ccb =
   1396 				SLIST_FIRST(&sc->sc_ccb_freelist)) == NULL)) {
   1397 			splx(s);
   1398 			return (NULL);
   1399 		}
   1400 		SLIST_REMOVE_HEAD(&sc->sc_ccb_freelist, ccb_chain.slist);
   1401 	}
   1402 #ifdef DIAGNOSTIC
   1403 	if ((long)(ccb - sc->sc_ccbs) == 0 && (flags & TWE_CCB_AEN) == 0)
   1404 		panic("twe_ccb_alloc: got reserved CCB for non-AEN");
   1405 	if ((ccb->ccb_flags & TWE_CCB_ALLOCED) != 0)
   1406 		panic("twe_ccb_alloc: CCB %ld already allocated",
   1407 		    (long)(ccb - sc->sc_ccbs));
   1408 	flags |= TWE_CCB_ALLOCED;
   1409 #endif
   1410 	splx(s);
   1411 
   1412 	twe_ccb_init(sc, ccb, flags);
   1413 	return (ccb);
   1414 }
   1415 
   1416 struct twe_ccb *
   1417 twe_ccb_alloc_wait(struct twe_softc *sc, int flags)
   1418 {
   1419 	struct twe_ccb *ccb;
   1420 	int s;
   1421 
   1422 	KASSERT((flags & TWE_CCB_AEN) == 0);
   1423 
   1424 	s = splbio();
   1425 	while (__predict_false((ccb =
   1426 				SLIST_FIRST(&sc->sc_ccb_freelist)) == NULL)) {
   1427 		sc->sc_flags |= TWEF_WAIT_CCB;
   1428 		(void) tsleep(&sc->sc_ccb_freelist, PRIBIO, "tweccb", 0);
   1429 	}
   1430 	SLIST_REMOVE_HEAD(&sc->sc_ccb_freelist, ccb_chain.slist);
   1431 #ifdef DIAGNOSTIC
   1432 	if ((ccb->ccb_flags & TWE_CCB_ALLOCED) != 0)
   1433 		panic("twe_ccb_alloc_wait: CCB %ld already allocated",
   1434 		    (long)(ccb - sc->sc_ccbs));
   1435 	flags |= TWE_CCB_ALLOCED;
   1436 #endif
   1437 	splx(s);
   1438 
   1439 	twe_ccb_init(sc, ccb, flags);
   1440 	return (ccb);
   1441 }
   1442 
   1443 /*
   1444  * Free a CCB.
   1445  */
   1446 void
   1447 twe_ccb_free(struct twe_softc *sc, struct twe_ccb *ccb)
   1448 {
   1449 	int s;
   1450 
   1451 	s = splbio();
   1452 	if ((ccb->ccb_flags & TWE_CCB_AEN) == 0) {
   1453 		SLIST_INSERT_HEAD(&sc->sc_ccb_freelist, ccb, ccb_chain.slist);
   1454 		if (__predict_false((sc->sc_flags & TWEF_WAIT_CCB) != 0)) {
   1455 			sc->sc_flags &= ~TWEF_WAIT_CCB;
   1456 			wakeup(&sc->sc_ccb_freelist);
   1457 		}
   1458 	}
   1459 	ccb->ccb_flags = 0;
   1460 	splx(s);
   1461 }
   1462 
   1463 /*
   1464  * Map the specified CCB's command block and data buffer (if any) into
   1465  * controller visible space.  Perform DMA synchronisation.
   1466  */
   1467 int
   1468 twe_ccb_map(struct twe_softc *sc, struct twe_ccb *ccb)
   1469 {
   1470 	struct twe_cmd *tc;
   1471 	int flags, nsegs, i, s, rv;
   1472 	void *data;
   1473 
   1474 	/*
   1475 	 * The data as a whole must be 512-byte aligned.
   1476 	 */
   1477 	if (((u_long)ccb->ccb_data & (TWE_ALIGNMENT - 1)) != 0) {
   1478 		s = splvm();
   1479 		/* XXX */
   1480 		rv = uvm_km_kmem_alloc(kmem_va_arena,
   1481 		    ccb->ccb_datasize, (VM_NOSLEEP | VM_INSTANTFIT),
   1482 		    (vmem_addr_t *)&ccb->ccb_abuf);
   1483 		splx(s);
   1484 		data = (void *)ccb->ccb_abuf;
   1485 		if ((ccb->ccb_flags & TWE_CCB_DATA_OUT) != 0)
   1486 			memcpy(data, ccb->ccb_data, ccb->ccb_datasize);
   1487 	} else {
   1488 		ccb->ccb_abuf = (vaddr_t)0;
   1489 		data = ccb->ccb_data;
   1490 	}
   1491 
   1492 	/*
   1493 	 * Map the data buffer into bus space and build the S/G list.
   1494 	 */
   1495 	rv = bus_dmamap_load(sc->sc_dmat, ccb->ccb_dmamap_xfer, data,
   1496 	    ccb->ccb_datasize, NULL, BUS_DMA_NOWAIT | BUS_DMA_STREAMING |
   1497 	    ((ccb->ccb_flags & TWE_CCB_DATA_IN) ?
   1498 	    BUS_DMA_READ : BUS_DMA_WRITE));
   1499 	if (rv != 0) {
   1500 		if (ccb->ccb_abuf != (vaddr_t)0) {
   1501 			s = splvm();
   1502 			/* XXX */
   1503 			uvm_km_kmem_free(kmem_va_arena, ccb->ccb_abuf,
   1504 			    ccb->ccb_datasize);
   1505 			splx(s);
   1506 		}
   1507 		return (rv);
   1508 	}
   1509 
   1510 	nsegs = ccb->ccb_dmamap_xfer->dm_nsegs;
   1511 	tc = ccb->ccb_cmd;
   1512 	tc->tc_size += 2 * nsegs;
   1513 
   1514 	/* The location of the S/G list is dependent upon command type. */
   1515 	switch (tc->tc_opcode >> 5) {
   1516 	case 2:
   1517 		for (i = 0; i < nsegs; i++) {
   1518 			tc->tc_args.param.sgl[i].tsg_address =
   1519 			    htole32(ccb->ccb_dmamap_xfer->dm_segs[i].ds_addr);
   1520 			tc->tc_args.param.sgl[i].tsg_length =
   1521 			    htole32(ccb->ccb_dmamap_xfer->dm_segs[i].ds_len);
   1522 		}
   1523 		/* XXX Needed? */
   1524 		for (; i < TWE_SG_SIZE; i++) {
   1525 			tc->tc_args.param.sgl[i].tsg_address = 0;
   1526 			tc->tc_args.param.sgl[i].tsg_length = 0;
   1527 		}
   1528 		break;
   1529 	case 3:
   1530 		for (i = 0; i < nsegs; i++) {
   1531 			tc->tc_args.io.sgl[i].tsg_address =
   1532 			    htole32(ccb->ccb_dmamap_xfer->dm_segs[i].ds_addr);
   1533 			tc->tc_args.io.sgl[i].tsg_length =
   1534 			    htole32(ccb->ccb_dmamap_xfer->dm_segs[i].ds_len);
   1535 		}
   1536 		/* XXX Needed? */
   1537 		for (; i < TWE_SG_SIZE; i++) {
   1538 			tc->tc_args.io.sgl[i].tsg_address = 0;
   1539 			tc->tc_args.io.sgl[i].tsg_length = 0;
   1540 		}
   1541 		break;
   1542 	default:
   1543 		/*
   1544 		 * In all likelihood, this is a command passed from
   1545 		 * management tools in userspace where no S/G list is
   1546 		 * necessary because no data is being passed.
   1547 		 */
   1548 		break;
   1549 	}
   1550 
   1551 	if ((ccb->ccb_flags & TWE_CCB_DATA_IN) != 0)
   1552 		flags = BUS_DMASYNC_PREREAD;
   1553 	else
   1554 		flags = 0;
   1555 	if ((ccb->ccb_flags & TWE_CCB_DATA_OUT) != 0)
   1556 		flags |= BUS_DMASYNC_PREWRITE;
   1557 
   1558 	bus_dmamap_sync(sc->sc_dmat, ccb->ccb_dmamap_xfer, 0,
   1559 	    ccb->ccb_datasize, flags);
   1560 	return (0);
   1561 }
   1562 
   1563 /*
   1564  * Unmap the specified CCB's command block and data buffer (if any) and
   1565  * perform DMA synchronisation.
   1566  */
   1567 void
   1568 twe_ccb_unmap(struct twe_softc *sc, struct twe_ccb *ccb)
   1569 {
   1570 	int flags, s;
   1571 
   1572 	if ((ccb->ccb_flags & TWE_CCB_DATA_IN) != 0)
   1573 		flags = BUS_DMASYNC_POSTREAD;
   1574 	else
   1575 		flags = 0;
   1576 	if ((ccb->ccb_flags & TWE_CCB_DATA_OUT) != 0)
   1577 		flags |= BUS_DMASYNC_POSTWRITE;
   1578 
   1579 	bus_dmamap_sync(sc->sc_dmat, ccb->ccb_dmamap_xfer, 0,
   1580 	    ccb->ccb_datasize, flags);
   1581 	bus_dmamap_unload(sc->sc_dmat, ccb->ccb_dmamap_xfer);
   1582 
   1583 	if (ccb->ccb_abuf != (vaddr_t)0) {
   1584 		if ((ccb->ccb_flags & TWE_CCB_DATA_IN) != 0)
   1585 			memcpy(ccb->ccb_data, (void *)ccb->ccb_abuf,
   1586 			    ccb->ccb_datasize);
   1587 		s = splvm();
   1588 		/* XXX */
   1589 		uvm_km_kmem_free(kmem_va_arena, ccb->ccb_abuf,
   1590 		    ccb->ccb_datasize);
   1591 		splx(s);
   1592 	}
   1593 }
   1594 
   1595 /*
   1596  * Submit a command to the controller and poll on completion.  Return
   1597  * non-zero on timeout (but don't check status, as some command types don't
   1598  * return status).  Must be called with interrupts blocked.
   1599  */
   1600 int
   1601 twe_ccb_poll(struct twe_softc *sc, struct twe_ccb *ccb, int timo)
   1602 {
   1603 	int rv;
   1604 
   1605 	if ((rv = twe_ccb_submit(sc, ccb)) != 0)
   1606 		return (rv);
   1607 
   1608 	for (timo *= 1000; timo != 0; timo--) {
   1609 		twe_poll(sc);
   1610 		if ((ccb->ccb_flags & TWE_CCB_COMPLETE) != 0)
   1611 			break;
   1612 		DELAY(100);
   1613 	}
   1614 
   1615 	return (timo == 0);
   1616 }
   1617 
   1618 /*
   1619  * If a CCB is specified, enqueue it.  Pull CCBs off the software queue in
   1620  * the order that they were enqueued and try to submit their command blocks
   1621  * to the controller for execution.
   1622  */
   1623 void
   1624 twe_ccb_enqueue(struct twe_softc *sc, struct twe_ccb *ccb)
   1625 {
   1626 	int s;
   1627 
   1628 	s = splbio();
   1629 
   1630 	if (ccb != NULL)
   1631 		SIMPLEQ_INSERT_TAIL(&sc->sc_ccb_queue, ccb, ccb_chain.simpleq);
   1632 
   1633 	while ((ccb = SIMPLEQ_FIRST(&sc->sc_ccb_queue)) != NULL) {
   1634 		if (twe_ccb_submit(sc, ccb))
   1635 			break;
   1636 		SIMPLEQ_REMOVE_HEAD(&sc->sc_ccb_queue, ccb_chain.simpleq);
   1637 	}
   1638 
   1639 	splx(s);
   1640 }
   1641 
   1642 /*
   1643  * Submit the command block associated with the specified CCB to the
   1644  * controller for execution.  Must be called with interrupts blocked.
   1645  */
   1646 int
   1647 twe_ccb_submit(struct twe_softc *sc, struct twe_ccb *ccb)
   1648 {
   1649 	bus_addr_t pa;
   1650 	int rv;
   1651 	u_int status;
   1652 
   1653 	/* Check to see if we can post a command. */
   1654 	status = twe_inl(sc, TWE_REG_STS);
   1655 	twe_status_check(sc, status);
   1656 
   1657 	if ((status & TWE_STS_CMD_QUEUE_FULL) == 0) {
   1658 		bus_dmamap_sync(sc->sc_dmat, sc->sc_dmamap,
   1659 		    (char *)ccb->ccb_cmd - (char *)sc->sc_cmds,
   1660 		    sizeof(struct twe_cmd),
   1661 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
   1662 #ifdef DIAGNOSTIC
   1663 		if ((ccb->ccb_flags & TWE_CCB_ALLOCED) == 0)
   1664 			panic("%s: CCB %ld not ALLOCED\n",
   1665 			    device_xname(sc->sc_dev), (long)(ccb - sc->sc_ccbs));
   1666 #endif
   1667 		ccb->ccb_flags |= TWE_CCB_ACTIVE;
   1668 		pa = sc->sc_cmds_paddr +
   1669 		    ccb->ccb_cmdid * sizeof(struct twe_cmd);
   1670 		twe_outl(sc, TWE_REG_CMD_QUEUE, (u_int32_t)pa);
   1671 		rv = 0;
   1672 	} else
   1673 		rv = EBUSY;
   1674 
   1675 	return (rv);
   1676 }
   1677 
   1678 
   1679 /*
   1680  * Accept an open operation on the control device.
   1681  */
   1682 static int
   1683 tweopen(dev_t dev, int flag, int mode, struct lwp *l)
   1684 {
   1685 	struct twe_softc *twe;
   1686 
   1687 	if ((twe = device_lookup_private(&twe_cd, minor(dev))) == NULL)
   1688 		return (ENXIO);
   1689 	if ((twe->sc_flags & TWEF_OPEN) != 0)
   1690 		return (EBUSY);
   1691 
   1692 	twe->sc_flags |= TWEF_OPEN;
   1693 	return (0);
   1694 }
   1695 
   1696 /*
   1697  * Accept the last close on the control device.
   1698  */
   1699 static int
   1700 tweclose(dev_t dev, int flag, int mode,
   1701     struct lwp *l)
   1702 {
   1703 	struct twe_softc *twe;
   1704 
   1705 	twe = device_lookup_private(&twe_cd, minor(dev));
   1706 	twe->sc_flags &= ~TWEF_OPEN;
   1707 	return (0);
   1708 }
   1709 
   1710 void
   1711 twe_ccb_wait_handler(struct twe_ccb *ccb, int error)
   1712 {
   1713 
   1714 	/* Just wake up the sleeper. */
   1715 	wakeup(ccb);
   1716 }
   1717 
   1718 /*
   1719  * Handle control operations.
   1720  */
   1721 static int
   1722 tweioctl(dev_t dev, u_long cmd, void *data, int flag,
   1723     struct lwp *l)
   1724 {
   1725 	struct twe_softc *twe;
   1726 	struct twe_ccb *ccb;
   1727 	struct twe_param *param;
   1728 	struct twe_usercommand *tu;
   1729 	struct twe_paramcommand *tp;
   1730 	struct twe_drivecommand *td;
   1731 	void *pdata = NULL;
   1732 	int s, error = 0;
   1733 	u_int8_t cmdid;
   1734 
   1735 	twe = device_lookup_private(&twe_cd, minor(dev));
   1736 	tu = (struct twe_usercommand *)data;
   1737 	tp = (struct twe_paramcommand *)data;
   1738 	td = (struct twe_drivecommand *)data;
   1739 
   1740 	/* This is intended to be compatible with the FreeBSD interface. */
   1741 	switch (cmd) {
   1742 	case TWEIO_COMMAND:
   1743 		error = kauth_authorize_device_passthru(l->l_cred, dev,
   1744 		    KAUTH_REQ_DEVICE_RAWIO_PASSTHRU_ALL, data);
   1745 		if (error)
   1746 			return (error);
   1747 
   1748 		/* XXX mutex */
   1749 		if (tu->tu_size > 0) {
   1750 			/*
   1751 			 * XXX Handle > TWE_SECTOR_SIZE?  Let's see if
   1752 			 * it's really necessary, first.
   1753 			 */
   1754 			if (tu->tu_size > TWE_SECTOR_SIZE) {
   1755 #ifdef TWE_DEBUG
   1756 				printf("%s: TWEIO_COMMAND: tu_size = %zu\n",
   1757 				    device_xname(twe->sc_dev), tu->tu_size);
   1758 #endif
   1759 				return EINVAL;
   1760 			}
   1761 			pdata = malloc(TWE_SECTOR_SIZE, M_DEVBUF, M_WAITOK);
   1762 			error = copyin(tu->tu_data, pdata, tu->tu_size);
   1763 			if (error != 0)
   1764 				goto done;
   1765 			ccb = twe_ccb_alloc_wait(twe,
   1766 			    TWE_CCB_DATA_IN | TWE_CCB_DATA_OUT);
   1767 			KASSERT(ccb != NULL);
   1768 			ccb->ccb_data = pdata;
   1769 			ccb->ccb_datasize = TWE_SECTOR_SIZE;
   1770 		} else {
   1771 			ccb = twe_ccb_alloc_wait(twe, 0);
   1772 			KASSERT(ccb != NULL);
   1773 		}
   1774 
   1775 		ccb->ccb_tx.tx_handler = twe_ccb_wait_handler;
   1776 		ccb->ccb_tx.tx_context = NULL;
   1777 		ccb->ccb_tx.tx_dv = twe->sc_dev;
   1778 
   1779 		cmdid = ccb->ccb_cmdid;
   1780 		memcpy(ccb->ccb_cmd, &tu->tu_cmd, sizeof(struct twe_cmd));
   1781 		ccb->ccb_cmd->tc_cmdid = cmdid;
   1782 
   1783 		/* Map the transfer. */
   1784 		if ((error = twe_ccb_map(twe, ccb)) != 0) {
   1785 			twe_ccb_free(twe, ccb);
   1786 			goto done;
   1787 		}
   1788 
   1789 		/* Submit the command and wait up to 1 minute. */
   1790 		error = 0;
   1791 		twe_ccb_enqueue(twe, ccb);
   1792 		s = splbio();
   1793 		while ((ccb->ccb_flags & TWE_CCB_COMPLETE) == 0)
   1794 			if ((error = tsleep(ccb, PRIBIO, "tweioctl",
   1795 					    60 * hz)) != 0)
   1796 				break;
   1797 		splx(s);
   1798 
   1799 		/* Copy the command back to the ioctl argument. */
   1800 		memcpy(&tu->tu_cmd, ccb->ccb_cmd, sizeof(struct twe_cmd));
   1801 #ifdef TWE_DEBUG
   1802 		printf("%s: TWEIO_COMMAND: tc_opcode = 0x%02x, "
   1803 		    "tc_status = 0x%02x\n", device_xname(twe->sc_dev),
   1804 		    tu->tu_cmd.tc_opcode, tu->tu_cmd.tc_status);
   1805 #endif
   1806 
   1807 		s = splbio();
   1808 		twe_ccb_free(twe, ccb);
   1809 		splx(s);
   1810 
   1811 		if (tu->tu_size > 0)
   1812 			error = copyout(pdata, tu->tu_data, tu->tu_size);
   1813 		goto done;
   1814 
   1815 	case TWEIO_STATS:
   1816 		return (ENOENT);
   1817 
   1818 	case TWEIO_AEN_POLL:
   1819 		s = splbio();
   1820 		*(u_int *)data = twe_aen_dequeue(twe);
   1821 		splx(s);
   1822 		return (0);
   1823 
   1824 	case TWEIO_AEN_WAIT:
   1825 		s = splbio();
   1826 		while ((*(u_int *)data =
   1827 		    twe_aen_dequeue(twe)) == TWE_AEN_QUEUE_EMPTY) {
   1828 			twe->sc_flags |= TWEF_AENQ_WAIT;
   1829 			error = tsleep(&twe->sc_aen_queue, PRIBIO | PCATCH,
   1830 			    "tweaen", 0);
   1831 			if (error == EINTR) {
   1832 				splx(s);
   1833 				return (error);
   1834 			}
   1835 		}
   1836 		splx(s);
   1837 		return (0);
   1838 
   1839 	case TWEIO_GET_PARAM:
   1840 		error = twe_param_get(twe, tp->tp_table_id, tp->tp_param_id,
   1841 		    tp->tp_size, 0, &param);
   1842 		if (error != 0)
   1843 			return (error);
   1844 		if (param->tp_param_size > tp->tp_size) {
   1845 			error = EFAULT;
   1846 			goto done;
   1847 		}
   1848 		error = copyout(param->tp_data, tp->tp_data,
   1849 		    param->tp_param_size);
   1850 		free(param, M_DEVBUF);
   1851 		goto done;
   1852 
   1853 	case TWEIO_SET_PARAM:
   1854 		pdata = malloc(tp->tp_size, M_DEVBUF, M_WAITOK);
   1855 		if ((error = copyin(tp->tp_data, pdata, tp->tp_size)) != 0)
   1856 			goto done;
   1857 		error = twe_param_set(twe, tp->tp_table_id, tp->tp_param_id,
   1858 		    tp->tp_size, pdata);
   1859 		goto done;
   1860 
   1861 	case TWEIO_RESET:
   1862 		s = splbio();
   1863 		twe_reset(twe);
   1864 		splx(s);
   1865 		return (0);
   1866 
   1867 	case TWEIO_ADD_UNIT:
   1868 		/* XXX mutex */
   1869 		return (twe_add_unit(twe, td->td_unit));
   1870 
   1871 	case TWEIO_DEL_UNIT:
   1872 		/* XXX mutex */
   1873 		return (twe_del_unit(twe, td->td_unit));
   1874 
   1875 	default:
   1876 		return EINVAL;
   1877 	}
   1878 done:
   1879 	if (pdata)
   1880 		free(pdata, M_DEVBUF);
   1881 	return error;
   1882 }
   1883 
   1884 const struct cdevsw twe_cdevsw = {
   1885 	.d_open = tweopen,
   1886 	.d_close = tweclose,
   1887 	.d_read = noread,
   1888 	.d_write = nowrite,
   1889 	.d_ioctl = tweioctl,
   1890 	.d_stop = nostop,
   1891 	.d_tty = notty,
   1892 	.d_poll = nopoll,
   1893 	.d_mmap = nommap,
   1894 	.d_kqfilter = nokqfilter,
   1895 	.d_discard = nodiscard,
   1896 	.d_flag = D_OTHER
   1897 };
   1898 
   1899 /*
   1900  * Print some information about the controller
   1901  */
   1902 static void
   1903 twe_describe_controller(struct twe_softc *sc)
   1904 {
   1905 	struct twe_param *p[6];
   1906 	int i, rv = 0;
   1907 	uint32_t dsize;
   1908 	uint8_t ports;
   1909 
   1910 	ports = 0;
   1911 
   1912 	/* get the port count */
   1913 	rv |= twe_param_get_1(sc, TWE_PARAM_CONTROLLER,
   1914 		TWE_PARAM_CONTROLLER_PortCount, &ports);
   1915 
   1916 	/* get version strings */
   1917 	rv |= twe_param_get(sc, TWE_PARAM_VERSION, TWE_PARAM_VERSION_Mon,
   1918 		16, NULL, &p[0]);
   1919 	rv |= twe_param_get(sc, TWE_PARAM_VERSION, TWE_PARAM_VERSION_FW,
   1920 		16, NULL, &p[1]);
   1921 	rv |= twe_param_get(sc, TWE_PARAM_VERSION, TWE_PARAM_VERSION_BIOS,
   1922 		16, NULL, &p[2]);
   1923 	rv |= twe_param_get(sc, TWE_PARAM_VERSION, TWE_PARAM_VERSION_PCB,
   1924 		8, NULL, &p[3]);
   1925 	rv |= twe_param_get(sc, TWE_PARAM_VERSION, TWE_PARAM_VERSION_ATA,
   1926 		8, NULL, &p[4]);
   1927 	rv |= twe_param_get(sc, TWE_PARAM_VERSION, TWE_PARAM_VERSION_PCI,
   1928 		8, NULL, &p[5]);
   1929 
   1930 	if (rv) {
   1931 		/* some error occurred */
   1932 		aprint_error_dev(sc->sc_dev, "failed to fetch version information\n");
   1933 		return;
   1934 	}
   1935 
   1936 	aprint_normal_dev(sc->sc_dev, "%d ports, Firmware %.16s, BIOS %.16s\n",
   1937 		ports, p[1]->tp_data, p[2]->tp_data);
   1938 
   1939 	aprint_verbose_dev(sc->sc_dev, "Monitor %.16s, PCB %.8s, Achip %.8s, Pchip %.8s\n",
   1940 		p[0]->tp_data, p[3]->tp_data,
   1941 		p[4]->tp_data, p[5]->tp_data);
   1942 
   1943 	free(p[0], M_DEVBUF);
   1944 	free(p[1], M_DEVBUF);
   1945 	free(p[2], M_DEVBUF);
   1946 	free(p[3], M_DEVBUF);
   1947 	free(p[4], M_DEVBUF);
   1948 	free(p[5], M_DEVBUF);
   1949 
   1950 	rv = twe_param_get(sc, TWE_PARAM_DRIVESUMMARY,
   1951 	    TWE_PARAM_DRIVESUMMARY_Status, 16, NULL, &p[0]);
   1952 	if (rv) {
   1953 		aprint_error_dev(sc->sc_dev, "failed to get drive status summary\n");
   1954 		return;
   1955 	}
   1956 	for (i = 0; i < ports; i++) {
   1957 		if (p[0]->tp_data[i] != TWE_PARAM_DRIVESTATUS_Present)
   1958 			continue;
   1959 		rv = twe_param_get_4(sc, TWE_PARAM_DRIVEINFO + i,
   1960 		    TWE_PARAM_DRIVEINFO_Size, &dsize);
   1961 		if (rv) {
   1962 			aprint_error_dev(sc->sc_dev,
   1963 			    "unable to get drive size for port %d\n", i);
   1964 			continue;
   1965 		}
   1966 		rv = twe_param_get(sc, TWE_PARAM_DRIVEINFO + i,
   1967 		    TWE_PARAM_DRIVEINFO_Model, 40, NULL, &p[1]);
   1968 		if (rv) {
   1969 			aprint_error_dev(sc->sc_dev,
   1970 			    "unable to get drive model for port %d\n", i);
   1971 			continue;
   1972 		}
   1973 		aprint_verbose_dev(sc->sc_dev, "port %d: %.40s %d MB\n",
   1974 		    i, p[1]->tp_data, dsize / 2048);
   1975 		free(p[1], M_DEVBUF);
   1976 	}
   1977 	free(p[0], M_DEVBUF);
   1978 }
   1979