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