Home | History | Annotate | Line # | Download | only in maple
maple.c revision 1.48
      1 /*	$NetBSD: maple.c,v 1.48 2014/03/16 05:20:23 dholland Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2002 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by ITOH Yasufumi.
      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) 2001 Marcus Comstedt
     34  * All rights reserved.
     35  *
     36  * Redistribution and use in source and binary forms, with or without
     37  * modification, are permitted provided that the following conditions
     38  * are met:
     39  * 1. Redistributions of source code must retain the above copyright
     40  *    notice, this list of conditions and the following disclaimer.
     41  * 2. Redistributions in binary form must reproduce the above copyright
     42  *    notice, this list of conditions and the following disclaimer in the
     43  *    documentation and/or other materials provided with the distribution.
     44  * 3. All advertising materials mentioning features or use of this software
     45  *    must display the following acknowledgement:
     46  *	This product includes software developed by Marcus Comstedt.
     47  * 4. Neither the name of The NetBSD Foundation nor the names of its
     48  *    contributors may be used to endorse or promote products derived
     49  *    from this software without specific prior written permission.
     50  *
     51  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     52  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     53  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     54  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     55  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     56  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     57  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     58  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     59  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     60  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     61  * POSSIBILITY OF SUCH DAMAGE.
     62  */
     63 
     64 #include <sys/cdefs.h>
     65 __KERNEL_RCSID(0, "$NetBSD: maple.c,v 1.48 2014/03/16 05:20:23 dholland Exp $");
     66 
     67 #include <sys/param.h>
     68 #include <sys/device.h>
     69 #include <sys/fcntl.h>
     70 #include <sys/kernel.h>
     71 #include <sys/kthread.h>
     72 #include <sys/poll.h>
     73 #include <sys/select.h>
     74 #include <sys/proc.h>
     75 #include <sys/signalvar.h>
     76 #include <sys/systm.h>
     77 #include <sys/conf.h>
     78 #include <sys/bus.h>
     79 
     80 #include <uvm/uvm.h>
     81 
     82 #include <machine/cpu.h>
     83 #include <machine/sysasicvar.h>
     84 #include <sh3/pmap.h>
     85 
     86 #include <dreamcast/dev/maple/maple.h>
     87 #include <dreamcast/dev/maple/mapleconf.h>
     88 #include <dreamcast/dev/maple/maplevar.h>
     89 #include <dreamcast/dev/maple/maplereg.h>
     90 #include <dreamcast/dev/maple/mapleio.h>
     91 
     92 #include "ioconf.h"
     93 #include "locators.h"
     94 
     95 /* Internal macros, functions, and variables. */
     96 
     97 #define MAPLE_CALLOUT_TICKS 2
     98 
     99 #define MAPLEBUSUNIT(dev)  (minor(dev)>>5)
    100 #define MAPLEPORT(dev)     ((minor(dev) & 0x18) >> 3)
    101 #define MAPLESUBUNIT(dev)  (minor(dev) & 0x7)
    102 
    103 /* interrupt priority level */
    104 #define	IPL_MAPLE	IPL_BIO
    105 #define splmaple()	splbio()
    106 #define IRL_MAPLE       SYSASIC_IRL9
    107 
    108 /*
    109  * Function declarations.
    110  */
    111 static int	maplematch(device_t, cfdata_t, void *);
    112 static void	mapleattach(device_t, device_t, void *);
    113 static void	maple_scanbus(struct maple_softc *);
    114 static char *	maple_unit_name(char *, int port, int subunit);
    115 static void	maple_begin_txbuf(struct maple_softc *);
    116 static int	maple_end_txbuf(struct maple_softc *);
    117 static void	maple_queue_command(struct maple_softc *, struct maple_unit *,
    118 		    int command, int datalen, const void *dataaddr);
    119 static void	maple_write_command(struct maple_softc *, struct maple_unit *,
    120 		    int, int, const void *);
    121 static void	maple_start(struct maple_softc *sc);
    122 static void	maple_start_poll(struct maple_softc *);
    123 static void	maple_check_subunit_change(struct maple_softc *,
    124 		    struct maple_unit *);
    125 static void	maple_check_unit_change(struct maple_softc *,
    126 		    struct maple_unit *);
    127 static void	maple_print_unit(void *, const char *);
    128 static int	maplesubmatch(device_t, cfdata_t, const int *, void *);
    129 static int	mapleprint(void *, const char *);
    130 static void	maple_attach_unit(struct maple_softc *, struct maple_unit *);
    131 static void	maple_detach_unit_nofix(struct maple_softc *,
    132 		    struct maple_unit *);
    133 static void	maple_detach_unit(struct maple_softc *, struct maple_unit *);
    134 static void	maple_queue_cmds(struct maple_softc *,
    135 		    struct maple_cmdq_head *);
    136 static void	maple_unit_probe(struct maple_softc *);
    137 static void	maple_unit_ping(struct maple_softc *);
    138 static int	maple_send_defered_periodic(struct maple_softc *);
    139 static void	maple_send_periodic(struct maple_softc *);
    140 static void	maple_remove_from_queues(struct maple_softc *,
    141 		    struct maple_unit *);
    142 static int	maple_retry(struct maple_softc *, struct maple_unit *,
    143 		    enum maple_dma_stat);
    144 static void	maple_queue_retry(struct maple_softc *);
    145 static void	maple_check_responses(struct maple_softc *);
    146 static void	maple_event_thread(void *);
    147 static int	maple_intr(void *);
    148 static void	maple_callout(void *);
    149 
    150 int	maple_alloc_dma(size_t, vaddr_t *, paddr_t *);
    151 #if 0
    152 void	maple_free_dma(paddr_t, size_t);
    153 #endif
    154 
    155 /*
    156  * Global variables.
    157  */
    158 int	maple_polling;		/* Are we polling?  (Debugger mode) */
    159 
    160 CFATTACH_DECL_NEW(maple, sizeof(struct maple_softc),
    161     maplematch, mapleattach, NULL, NULL);
    162 
    163 dev_type_open(mapleopen);
    164 dev_type_close(mapleclose);
    165 dev_type_ioctl(mapleioctl);
    166 
    167 const struct cdevsw maple_cdevsw = {
    168 	.d_open = mapleopen,
    169 	.d_close = mapleclose,
    170 	.d_read = noread,
    171 	.d_write = nowrite,
    172 	.d_ioctl = mapleioctl,
    173 	.d_stop = nostop,
    174 	.d_tty = notty,
    175 	.d_poll = nopoll,
    176 	.d_mmap = nommap,
    177 	.d_kqfilter = nokqfilter,
    178 	.d_flag = 0
    179 };
    180 
    181 static int
    182 maplematch(device_t parent, cfdata_t cf, void *aux)
    183 {
    184 
    185 	return 1;
    186 }
    187 
    188 static void
    189 mapleattach(device_t parent, device_t self, void *aux)
    190 {
    191 	struct maple_softc *sc;
    192 	struct maple_unit *u;
    193 	vaddr_t dmabuffer;
    194 	paddr_t dmabuffer_phys;
    195 	uint32_t *p;
    196 	int port, subunit, f;
    197 
    198 	sc = device_private(self);
    199 	sc->sc_dev = self;
    200 
    201 	printf(": %s\n", sysasic_intr_string(IRL_MAPLE));
    202 
    203 	if (maple_alloc_dma(MAPLE_DMABUF_SIZE, &dmabuffer, &dmabuffer_phys)) {
    204 		printf("%s: unable to allocate DMA buffers.\n",
    205 		    device_xname(self));
    206 		return;
    207 	}
    208 
    209 	p = (uint32_t *)dmabuffer;
    210 
    211 	for (port = 0; port < MAPLE_PORTS; port++) {
    212 		for (subunit = 0; subunit < MAPLE_SUBUNITS; subunit++) {
    213 			u = &sc->sc_unit[port][subunit];
    214 			u->port = port;
    215 			u->subunit = subunit;
    216 			u->u_dma_stat = MAPLE_DMA_IDLE;
    217 			u->u_rxbuf = p;
    218 			u->u_rxbuf_phys = SH3_P2SEG_TO_PHYS(p);
    219 			p += 256;
    220 
    221 			for (f = 0; f < MAPLE_NFUNC; f++) {
    222 				u->u_func[f].f_funcno = f;
    223 				u->u_func[f].f_unit = u;
    224 			}
    225 		}
    226 	}
    227 
    228 	sc->sc_txbuf = p;
    229 	sc->sc_txbuf_phys = SH3_P2SEG_TO_PHYS(p);
    230 
    231 	SIMPLEQ_INIT(&sc->sc_retryq);
    232 	TAILQ_INIT(&sc->sc_probeq);
    233 	TAILQ_INIT(&sc->sc_pingq);
    234 	TAILQ_INIT(&sc->sc_periodicq);
    235 	TAILQ_INIT(&sc->sc_periodicdeferq);
    236 	TAILQ_INIT(&sc->sc_acmdq);
    237 	TAILQ_INIT(&sc->sc_pcmdq);
    238 
    239 	MAPLE_RESET = RESET_MAGIC;
    240 	MAPLE_RESET2 = 0;
    241 
    242 	MAPLE_SPEED = SPEED_2MBPS | TIMEOUT(50000);
    243 
    244 	MAPLE_ENABLE = 1;
    245 
    246 	maple_polling = 1;
    247 	maple_scanbus(sc);
    248 
    249 	callout_init(&sc->maple_callout_ch, 0);
    250 
    251 	sc->sc_intrhand = sysasic_intr_establish(SYSASIC_EVENT_MAPLE_DMADONE,
    252 	    IPL_MAPLE, IRL_MAPLE, maple_intr, sc);
    253 
    254 	config_pending_incr(self); /* create thread before mounting root */
    255 
    256 	if (kthread_create(PRI_NONE, 0, NULL, maple_event_thread, sc,
    257 	    &sc->event_thread, "%s", device_xname(self)) == 0)
    258 		return;
    259 
    260 	panic("%s: unable to create event thread", device_xname(self));
    261 }
    262 
    263 /*
    264  * initial device attach
    265  */
    266 static void
    267 maple_scanbus(struct maple_softc *sc)
    268 {
    269 	struct maple_unit *u;
    270 	int port;
    271 	int last_port, last_subunit;
    272 	int i;
    273 
    274 	KASSERT(cold && maple_polling);
    275 
    276 	/* probe all ports */
    277 	for (port = 0; port < MAPLE_PORTS; port++) {
    278 		u = &sc->sc_unit[port][0];
    279 #if defined(MAPLE_DEBUG) && MAPLE_DEBUG > 2
    280 		{
    281 			char buf[16];
    282 			printf("%s: queued to probe 1\n",
    283 			    maple_unit_name(buf, u->port, u->subunit));
    284 		}
    285 #endif
    286 		TAILQ_INSERT_TAIL(&sc->sc_probeq, u, u_q);
    287 		u->u_queuestat = MAPLE_QUEUE_PROBE;
    288 	}
    289 
    290 	last_port = last_subunit = -1;
    291 	maple_begin_txbuf(sc);
    292 	while ((u = TAILQ_FIRST(&sc->sc_probeq)) != NULL) {
    293 		/*
    294 		 * Check wrap condition
    295 		 */
    296 		if (u->port < last_port || u->subunit <= last_subunit)
    297 			break;
    298 		last_port = u->port;
    299 		if (u->port == MAPLE_PORTS - 1)
    300 			last_subunit = u->subunit;
    301 
    302 		maple_unit_probe(sc);
    303 		for (i = 10 /* just not forever */; maple_end_txbuf(sc); i--) {
    304 			maple_start_poll(sc);
    305 			maple_check_responses(sc);
    306 			if (i == 0)
    307 				break;
    308 			/* attach may issue cmds */
    309 			maple_queue_cmds(sc, &sc->sc_acmdq);
    310 		}
    311 	}
    312 }
    313 
    314 void
    315 maple_run_polling(device_t dev)
    316 {
    317 	struct maple_softc *sc;
    318 	int port, subunit;
    319 	int i;
    320 
    321 	sc = device_private(dev);
    322 
    323 	/*
    324 	 * first, make sure polling works
    325 	 */
    326 	while (MAPLE_STATE != 0)	/* XXX may lost a DMA cycle */
    327 		;
    328 
    329 	/* XXX this will break internal state */
    330 	for (port = 0; port < MAPLE_PORTS; port++)
    331 		for (subunit = 0; subunit < MAPLE_SUBUNITS; subunit++)
    332 			sc->sc_unit[port][subunit].u_dma_stat = MAPLE_DMA_IDLE;
    333 	SIMPLEQ_INIT(&sc->sc_retryq);	/* XXX discard current retrys */
    334 
    335 	/*
    336 	 * do polling (periodic status check only)
    337 	 */
    338 	maple_begin_txbuf(sc);
    339 	maple_send_defered_periodic(sc);
    340 	maple_send_periodic(sc);
    341 	for (i = 10 /* just not forever */; maple_end_txbuf(sc); i--) {
    342 		maple_start_poll(sc);
    343 		maple_check_responses(sc);
    344 		if (i == 0)
    345 			break;
    346 
    347 		/* maple_check_responses() has executed maple_begin_txbuf() */
    348 		maple_queue_retry(sc);
    349 		maple_send_defered_periodic(sc);
    350 	}
    351 }
    352 
    353 static char *
    354 maple_unit_name(char *buf, int port, int subunit)
    355 {
    356 
    357 	sprintf(buf, "maple%c", port + 'A');
    358 	if (subunit)
    359 		sprintf(buf+6, "%d", subunit);
    360 
    361 	return buf;
    362 }
    363 
    364 int
    365 maple_alloc_dma(size_t size, vaddr_t *vap, paddr_t *pap)
    366 {
    367 	extern paddr_t avail_start, avail_end;	/* from pmap.c */
    368 	struct pglist mlist;
    369 	struct vm_page *m;
    370 	int error;
    371 
    372 	size = round_page(size);
    373 
    374 	error = uvm_pglistalloc(size, avail_start, avail_end - PAGE_SIZE,
    375 	    0, 0, &mlist, 1, 0);
    376 	if (error)
    377 		return error;
    378 
    379 	m = TAILQ_FIRST(&mlist);
    380 	*pap = VM_PAGE_TO_PHYS(m);
    381 	*vap = SH3_PHYS_TO_P2SEG(VM_PAGE_TO_PHYS(m));
    382 
    383 	return 0;
    384 }
    385 
    386 #if 0	/* currently unused */
    387 void
    388 maple_free_dma(paddr_t paddr, size_t size)
    389 {
    390 	struct pglist mlist;
    391 	struct vm_page *m;
    392 	bus_addr_t addr;
    393 
    394 	TAILQ_INIT(&mlist);
    395 	for (addr = paddr; addr < paddr + size; addr += PAGE_SIZE) {
    396 		m = PHYS_TO_VM_PAGE(addr);
    397 		TAILQ_INSERT_TAIL(&mlist, m, pageq.queue);
    398 	}
    399 	uvm_pglistfree(&mlist);
    400 }
    401 #endif
    402 
    403 static void
    404 maple_begin_txbuf(struct maple_softc *sc)
    405 {
    406 
    407 	sc->sc_txlink = sc->sc_txpos = sc->sc_txbuf;
    408 	SIMPLEQ_INIT(&sc->sc_dmaq);
    409 }
    410 
    411 static int
    412 maple_end_txbuf(struct maple_softc *sc)
    413 {
    414 
    415 	/* if no frame have been written, we can't mark the
    416 	   list end, and so the DMA must not be activated   */
    417 	if (sc->sc_txpos == sc->sc_txbuf)
    418 		return 0;
    419 
    420 	*sc->sc_txlink |= 0x80000000;
    421 
    422 	return 1;
    423 }
    424 
    425 static const int8_t subunit_code[] = { 0x20, 0x01, 0x02, 0x04, 0x08, 0x10 };
    426 
    427 static void
    428 maple_queue_command(struct maple_softc *sc, struct maple_unit *u,
    429 	int command, int datalen, const void *dataaddr)
    430 {
    431 	int to, from;
    432 	uint32_t *p = sc->sc_txpos;
    433 
    434 	/* Max data length = 255 longs = 1020 bytes */
    435 	KASSERT(datalen >= 0 && datalen <= 255);
    436 
    437 	/* Compute sender and recipient address */
    438 	from = u->port << 6;
    439 	to = from | subunit_code[u->subunit];
    440 
    441 	sc->sc_txlink = p;
    442 
    443 	/* Set length of packet and destination port (A-D) */
    444 	*p++ = datalen | (u->port << 16);
    445 
    446 	/* Write address to receive buffer where the response
    447 	   frame should be put */
    448 	*p++ = u->u_rxbuf_phys;
    449 
    450 	/* Create the frame header.  The fields are assembled "backwards"
    451 	   because of the Maple Bus big-endianness.                       */
    452 	*p++ = (command & 0xff) | (to << 8) | (from << 16) | (datalen << 24);
    453 
    454 	/* Copy parameter data, if any */
    455 	if (datalen > 0) {
    456 		const uint32_t *param = dataaddr;
    457 		int i;
    458 		for (i = 0; i < datalen; i++)
    459 			*p++ = *param++;
    460 	}
    461 
    462 	sc->sc_txpos = p;
    463 
    464 	SIMPLEQ_INSERT_TAIL(&sc->sc_dmaq, u, u_dmaq);
    465 }
    466 
    467 static void
    468 maple_write_command(struct maple_softc *sc, struct maple_unit *u, int command,
    469 	int datalen, const void *dataaddr)
    470 {
    471 #if defined(MAPLE_DEBUG) && MAPLE_DEBUG > 2
    472 	char buf[16];
    473 
    474 	if (u->u_retrycnt)
    475 		printf("%s: retrycnt %d\n",
    476 		    maple_unit_name(buf, u->port, u->subunit), u->u_retrycnt);
    477 #endif
    478 	u->u_retrycnt = 0;
    479 	u->u_command = command;
    480 	u->u_datalen = datalen;
    481 	u->u_dataaddr = dataaddr;
    482 
    483 	maple_queue_command(sc, u, command, datalen, dataaddr);
    484 }
    485 
    486 /* start DMA */
    487 static void
    488 maple_start(struct maple_softc *sc)
    489 {
    490 
    491 	MAPLE_DMAADDR = sc->sc_txbuf_phys;
    492 	MAPLE_STATE = 1;
    493 }
    494 
    495 /* start DMA -- wait until DMA done */
    496 static void
    497 maple_start_poll(struct maple_softc *sc)
    498 {
    499 
    500 	MAPLE_DMAADDR = sc->sc_txbuf_phys;
    501 	MAPLE_STATE = 1;
    502 	while (MAPLE_STATE != 0)
    503 		;
    504 }
    505 
    506 static void
    507 maple_check_subunit_change(struct maple_softc *sc, struct maple_unit *u)
    508 {
    509 	struct maple_unit *u1;
    510 	int port;
    511 	int8_t unit_map;
    512 	int units, un;
    513 	int i;
    514 
    515 	KASSERT(u->subunit == 0);
    516 
    517 	port = u->port;
    518 	unit_map = ((int8_t *) u->u_rxbuf)[2];
    519 	if (sc->sc_port_unit_map[port] == unit_map)
    520 		return;
    521 
    522 	units = ((unit_map & 0x1f) << 1) | 1;
    523 #if defined(MAPLE_DEBUG) && MAPLE_DEBUG > 1
    524 	{
    525 		char buf[16];
    526 		printf("%s: unit_map 0x%x -> 0x%x (units 0x%x)\n",
    527 		    maple_unit_name(buf, u->port, u->subunit),
    528 		    sc->sc_port_unit_map[port], unit_map, units);
    529 	}
    530 #endif
    531 #if 0	/* this detects unit removal rapidly but is not reliable */
    532 	/* check for unit change */
    533 	un = sc->sc_port_units[port] & ~units;
    534 
    535 	/* detach removed devices */
    536 	for (i = MAPLE_SUBUNITS - 1; i > 0; i--)
    537 		if (un & (1 << i))
    538 			maple_detach_unit_nofix(sc, &sc->sc_unit[port][i]);
    539 #endif
    540 
    541 	sc->sc_port_unit_map[port] = unit_map;
    542 
    543 	/* schedule scanning child devices */
    544 	un = units & ~sc->sc_port_units[port];
    545 	for (i = MAPLE_SUBUNITS - 1; i > 0; i--)
    546 		if (un & (1 << i)) {
    547 			u1 = &sc->sc_unit[port][i];
    548 			maple_remove_from_queues(sc, u1);
    549 #if defined(MAPLE_DEBUG) && MAPLE_DEBUG > 2
    550 			{
    551 				char buf[16];
    552 				printf("%s: queued to probe 2\n",
    553 				    maple_unit_name(buf, u1->port, u1->subunit));
    554 			}
    555 #endif
    556 			TAILQ_INSERT_HEAD(&sc->sc_probeq, u1, u_q);
    557 			u1->u_queuestat = MAPLE_QUEUE_PROBE;
    558 			u1->u_proberetry = 0;
    559 		}
    560 }
    561 
    562 static void
    563 maple_check_unit_change(struct maple_softc *sc, struct maple_unit *u)
    564 {
    565 	struct maple_devinfo *newinfo = (void *) (u->u_rxbuf + 1);
    566 
    567 	if (memcmp(&u->devinfo, newinfo, sizeof(struct maple_devinfo)) == 0)
    568 		goto out;	/* no change */
    569 
    570 	/* unit inserted */
    571 
    572 	/* attach this device */
    573 	u->devinfo = *newinfo;
    574 	maple_attach_unit(sc, u);
    575 
    576 out:
    577 	maple_remove_from_queues(sc, u);
    578 #if defined(MAPLE_DEBUG) && MAPLE_DEBUG > 2
    579 	{
    580 		char buf[16];
    581 		printf("%s: queued to ping\n",
    582 		    maple_unit_name(buf, u->port, u->subunit));
    583 	}
    584 #endif
    585 	TAILQ_INSERT_TAIL(&sc->sc_pingq, u, u_q);
    586 	u->u_queuestat = MAPLE_QUEUE_PING;
    587 }
    588 
    589 static void
    590 maple_print_unit(void *aux, const char *pnp)
    591 {
    592 	struct maple_attach_args *ma = aux;
    593 	int port, subunit;
    594 	char buf[16];
    595 	char *prod, *p, oc;
    596 
    597 	port = ma->ma_unit->port;
    598 	subunit = ma->ma_unit->subunit;
    599 
    600 	if (pnp != NULL)
    601 		printf("%s at %s", maple_unit_name(buf, port, subunit), pnp);
    602 
    603 	printf(" port %d", port);
    604 
    605 	if (subunit != 0)
    606 		printf(" subunit %d", subunit);
    607 
    608 #ifdef MAPLE_DEBUG
    609 	printf(": a %#x c %#x fn %#x d %#x,%#x,%#x",
    610 	    ma->ma_devinfo->di_area_code,
    611 	    ma->ma_devinfo->di_connector_direction,
    612 	    be32toh(ma->ma_devinfo->di_func),
    613 	    be32toh(ma->ma_devinfo->di_function_data[0]),
    614 	    be32toh(ma->ma_devinfo->di_function_data[1]),
    615 	    be32toh(ma->ma_devinfo->di_function_data[2]));
    616 #endif
    617 
    618 	/* nul termination */
    619 	prod = ma->ma_devinfo->di_product_name;
    620 	for (p = prod + sizeof ma->ma_devinfo->di_product_name; p >= prod; p--)
    621 		if (p[-1] != '\0' && p[-1] != ' ')
    622 			break;
    623 	oc = *p;
    624 	*p = '\0';
    625 
    626 	printf(": %s", prod);
    627 
    628 	*p = oc;	/* restore */
    629 }
    630 
    631 static int
    632 maplesubmatch(device_t parent, cfdata_t match, const int *ldesc, void *aux)
    633 {
    634 	struct maple_attach_args *ma = aux;
    635 
    636 	if (match->cf_loc[MAPLECF_PORT] != MAPLECF_PORT_DEFAULT &&
    637 	    match->cf_loc[MAPLECF_PORT] != ma->ma_unit->port)
    638 		return 0;
    639 
    640 	if (match->cf_loc[MAPLECF_SUBUNIT] != MAPLECF_SUBUNIT_DEFAULT &&
    641 	    match->cf_loc[MAPLECF_SUBUNIT] != ma->ma_unit->subunit)
    642 		return 0;
    643 
    644 	return config_match(parent, match, aux);
    645 }
    646 
    647 static int
    648 mapleprint(void *aux, const char *str)
    649 {
    650 	struct maple_attach_args *ma = aux;
    651 
    652 #ifdef MAPLE_DEBUG
    653 	if (str)
    654 		aprint_normal("%s", str);
    655 	aprint_normal(" function %d", ma->ma_function);
    656 
    657 	return UNCONF;
    658 #else	/* quiet */
    659 	if (!str)
    660 		aprint_normal(" function %d", ma->ma_function);
    661 
    662 	return QUIET;
    663 #endif
    664 }
    665 
    666 static void
    667 maple_attach_unit(struct maple_softc *sc, struct maple_unit *u)
    668 {
    669 	struct maple_attach_args ma;
    670 	uint32_t func;
    671 	int f;
    672 	char oldxname[16];
    673 
    674 	ma.ma_unit = u;
    675 	ma.ma_devinfo = &u->devinfo;
    676 	ma.ma_basedevinfo = &sc->sc_unit[u->port][0].devinfo;
    677 	func = be32toh(ma.ma_devinfo->di_func);
    678 
    679 	maple_print_unit(&ma, device_xname(sc->sc_dev));
    680 	printf("\n");
    681 	strcpy(oldxname, device_xname(sc->sc_dev));
    682 	maple_unit_name(sc->sc_dev->dv_xname, u->port, u->subunit);
    683 
    684 	for (f = 0; f < MAPLE_NFUNC; f++) {
    685 		u->u_func[f].f_callback = NULL;
    686 		u->u_func[f].f_arg = NULL;
    687 		u->u_func[f].f_cmdstat = MAPLE_CMDSTAT_NONE;
    688 		u->u_func[f].f_dev = NULL;
    689 		if (func & MAPLE_FUNC(f)) {
    690 			ma.ma_function = f;
    691 			u->u_func[f].f_dev = config_found_sm_loc(sc->sc_dev,
    692 			    "maple", NULL, &ma, mapleprint, maplesubmatch);
    693 			u->u_ping_func = f;	/* XXX using largest func */
    694 		}
    695 	}
    696 #ifdef MAPLE_MEMCARD_PING_HACK
    697 	/*
    698 	 * Some 3rd party memory card pretend to be Visual Memory,
    699 	 * but need special handling for ping.
    700 	 */
    701 	if (func == (MAPLE_FUNC(MAPLE_FN_MEMCARD) | MAPLE_FUNC(MAPLE_FN_LCD) |
    702 	    MAPLE_FUNC(MAPLE_FN_CLOCK))) {
    703 		u->u_ping_func = MAPLE_FN_MEMCARD;
    704 		u->u_ping_stat = MAPLE_PING_MEMCARD;
    705 	} else {
    706 		u->u_ping_stat = MAPLE_PING_NORMAL;
    707 	}
    708 #endif
    709 	strcpy(sc->sc_dev->dv_xname, oldxname);
    710 
    711 	sc->sc_port_units[u->port] |= 1 << u->subunit;
    712 }
    713 
    714 static void
    715 maple_detach_unit_nofix(struct maple_softc *sc, struct maple_unit *u)
    716 {
    717 	struct maple_func *fn;
    718 	device_t dev;
    719 	struct maple_unit *u1;
    720 	int port;
    721 	int error;
    722 	int i;
    723 	char buf[16];
    724 
    725 #if defined(MAPLE_DEBUG) && MAPLE_DEBUG > 1
    726 	printf("%s: remove\n", maple_unit_name(buf, u->port, u->subunit));
    727 #endif
    728 	maple_remove_from_queues(sc, u);
    729 	port = u->port;
    730 	sc->sc_port_units[port] &= ~(1 << u->subunit);
    731 
    732 	if (u->subunit == 0) {
    733 		for (i = MAPLE_SUBUNITS - 1; i > 0; i--)
    734 			maple_detach_unit_nofix(sc, &sc->sc_unit[port][i]);
    735 	}
    736 
    737 	for (fn = u->u_func; fn < &u->u_func[MAPLE_NFUNC]; fn++) {
    738 		if ((dev = fn->f_dev) != NULL) {
    739 #if defined(MAPLE_DEBUG) && MAPLE_DEBUG > 1
    740 			printf("%s: detaching func %d\n",
    741 			    maple_unit_name(buf, port, u->subunit),
    742 			    fn->f_funcno);
    743 #endif
    744 
    745 			/*
    746 			 * Remove functions from command queue.
    747 			 */
    748 			switch (fn->f_cmdstat) {
    749 			case MAPLE_CMDSTAT_ASYNC:
    750 			case MAPLE_CMDSTAT_PERIODIC_DEFERED:
    751 				TAILQ_REMOVE(&sc->sc_acmdq, fn, f_cmdq);
    752 				break;
    753 			case MAPLE_CMDSTAT_ASYNC_PERIODICQ:
    754 			case MAPLE_CMDSTAT_PERIODIC:
    755 				TAILQ_REMOVE(&sc->sc_pcmdq, fn, f_cmdq);
    756 				break;
    757 			default:
    758 				break;
    759 			}
    760 
    761 			/*
    762 			 * Detach devices.
    763 			 */
    764 			if ((error = config_detach(fn->f_dev, DETACH_FORCE))) {
    765 				printf("%s: failed to detach %s (func %d), errno %d\n",
    766 				    maple_unit_name(buf, port, u->subunit),
    767 				    device_xname(fn->f_dev), fn->f_funcno, error);
    768 			}
    769 		}
    770 
    771 		maple_enable_periodic(sc->sc_dev, u, fn->f_funcno, 0);
    772 
    773 		fn->f_dev = NULL;
    774 		fn->f_callback = NULL;
    775 		fn->f_arg = NULL;
    776 		fn->f_cmdstat = MAPLE_CMDSTAT_NONE;
    777 	}
    778 	if (u->u_dma_stat == MAPLE_DMA_RETRY) {
    779 		/* XXX expensive? */
    780 		SIMPLEQ_FOREACH(u1, &sc->sc_retryq, u_dmaq) {
    781 			if (u1 == u) {
    782 #if defined(MAPLE_DEBUG) && MAPLE_DEBUG > 1
    783 				printf("%s: abort retry\n",
    784 				    maple_unit_name(buf, port, u->subunit));
    785 #endif
    786 				SIMPLEQ_REMOVE(&sc->sc_retryq, u, maple_unit,
    787 				    u_dmaq);
    788 				break;
    789 			}
    790 		}
    791 	}
    792 	u->u_dma_stat = MAPLE_DMA_IDLE;
    793 	u->u_noping = 0;
    794 	/* u->u_dma_func = uninitialized; */
    795 	KASSERT(u->getcond_func_set == 0);
    796 	memset(&u->devinfo, 0, sizeof(struct maple_devinfo));
    797 
    798 	if (u->subunit == 0) {
    799 		sc->sc_port_unit_map[port] = 0;
    800 #if defined(MAPLE_DEBUG) && MAPLE_DEBUG > 2
    801 		{
    802 			char buf2[16];
    803 			printf("%s: queued to probe 3\n",
    804 			    maple_unit_name(buf2, port, u->subunit));
    805 		}
    806 #endif
    807 		TAILQ_INSERT_TAIL(&sc->sc_probeq, u, u_q);
    808 		u->u_queuestat = MAPLE_QUEUE_PROBE;
    809 	}
    810 }
    811 
    812 static void
    813 maple_detach_unit(struct maple_softc *sc, struct maple_unit *u)
    814 {
    815 
    816 	maple_detach_unit_nofix(sc, u);
    817 	if (u->subunit != 0)
    818 		sc->sc_port_unit_map[u->port] &= ~(1 << (u->subunit - 1));
    819 }
    820 
    821 /*
    822  * Send a command (called by drivers)
    823  *
    824  * The "cataaddr" must not point at temporary storage like stack.
    825  * Only one command (per function) is valid at a time.
    826  */
    827 void
    828 maple_command(device_t dev, struct maple_unit *u, int func,
    829 	int command, int datalen, const void *dataaddr, int flags)
    830 {
    831 	struct maple_softc *sc = device_private(dev);
    832 	struct maple_func *fn;
    833 	int s;
    834 
    835 	KASSERT(func >= 0 && func < 32);
    836 	KASSERT(command);
    837 	KASSERT((flags & ~MAPLE_FLAG_CMD_PERIODIC_TIMING) == 0);
    838 
    839 	s = splsoftclock();
    840 
    841 	fn = &u->u_func[func];
    842 #if 1 /*def DIAGNOSTIC*/
    843 	{char buf[16];
    844 	if (fn->f_cmdstat != MAPLE_CMDSTAT_NONE)
    845 		panic("maple_command: %s func %d: requesting more than one commands",
    846 		    maple_unit_name(buf, u->port, u->subunit), func);
    847 	}
    848 #endif
    849 	fn->f_command = command;
    850 	fn->f_datalen = datalen;
    851 	fn->f_dataaddr = dataaddr;
    852 	if (flags & MAPLE_FLAG_CMD_PERIODIC_TIMING) {
    853 		fn->f_cmdstat = MAPLE_CMDSTAT_PERIODIC;
    854 		TAILQ_INSERT_TAIL(&sc->sc_pcmdq, fn, f_cmdq);
    855 	} else {
    856 		fn->f_cmdstat = MAPLE_CMDSTAT_ASYNC;
    857 		TAILQ_INSERT_TAIL(&sc->sc_acmdq, fn, f_cmdq);
    858 		wakeup(&sc->sc_event);	/* wake for async event */
    859 	}
    860 	splx(s);
    861 }
    862 
    863 static void
    864 maple_queue_cmds(struct maple_softc *sc,
    865 	struct maple_cmdq_head *head)
    866 {
    867 	struct maple_func *fn, *nextfn;
    868 	struct maple_unit *u;
    869 
    870 	/*
    871 	 * Note: since the queue element may be queued immediately,
    872 	 *	 we can't use TAILQ_FOREACH.
    873 	 */
    874 	fn = TAILQ_FIRST(head);
    875 	TAILQ_INIT(head);
    876 	for ( ; fn; fn = nextfn) {
    877 		nextfn = TAILQ_NEXT(fn, f_cmdq);
    878 
    879 		KASSERT(fn->f_cmdstat != MAPLE_CMDSTAT_NONE);
    880 		u = fn->f_unit;
    881 		if (u->u_dma_stat == MAPLE_DMA_IDLE) {
    882 			maple_write_command(sc, u,
    883 			    fn->f_command, fn->f_datalen, fn->f_dataaddr);
    884 			u->u_dma_stat = (fn->f_cmdstat == MAPLE_CMDSTAT_ASYNC ||
    885 			    fn->f_cmdstat == MAPLE_CMDSTAT_ASYNC_PERIODICQ) ?
    886 			    MAPLE_DMA_ACMD : MAPLE_DMA_PCMD;
    887 			u->u_dma_func = fn->f_funcno;
    888 			fn->f_cmdstat = MAPLE_CMDSTAT_NONE;
    889 		} else if (u->u_dma_stat == MAPLE_DMA_RETRY) {
    890 			/* unit is busy --- try again */
    891 			/*
    892 			 * always add to periodic command queue
    893 			 * (wait until the next periodic timing),
    894 			 * since the unit will never be freed until the
    895 			 * next periodic timing.
    896 			 */
    897 			switch (fn->f_cmdstat) {
    898 			case MAPLE_CMDSTAT_ASYNC:
    899 				fn->f_cmdstat = MAPLE_CMDSTAT_ASYNC_PERIODICQ;
    900 				break;
    901 			case MAPLE_CMDSTAT_PERIODIC_DEFERED:
    902 				fn->f_cmdstat = MAPLE_CMDSTAT_PERIODIC;
    903 				break;
    904 			default:
    905 				break;
    906 			}
    907 			TAILQ_INSERT_TAIL(&sc->sc_pcmdq, fn, f_cmdq);
    908 		} else {
    909 			/* unit is busy --- try again */
    910 			/*
    911 			 * always add to async command queue
    912 			 * (process immediately)
    913 			 */
    914 			switch (fn->f_cmdstat) {
    915 			case MAPLE_CMDSTAT_ASYNC_PERIODICQ:
    916 				fn->f_cmdstat = MAPLE_CMDSTAT_ASYNC;
    917 				break;
    918 			case MAPLE_CMDSTAT_PERIODIC:
    919 				fn->f_cmdstat = MAPLE_CMDSTAT_PERIODIC_DEFERED;
    920 				break;
    921 			default:
    922 				break;
    923 			}
    924 			TAILQ_INSERT_TAIL(&sc->sc_acmdq, fn, f_cmdq);
    925 		}
    926 	}
    927 }
    928 
    929 /* schedule probing a device */
    930 static void
    931 maple_unit_probe(struct maple_softc *sc)
    932 {
    933 	struct maple_unit *u;
    934 
    935 	if ((u = TAILQ_FIRST(&sc->sc_probeq)) != NULL) {
    936 		KASSERT(u->u_dma_stat == MAPLE_DMA_IDLE);
    937 		KASSERT(u->u_queuestat == MAPLE_QUEUE_PROBE);
    938 		maple_remove_from_queues(sc, u);
    939 		maple_write_command(sc, u, MAPLE_COMMAND_DEVINFO, 0, NULL);
    940 		u->u_dma_stat = MAPLE_DMA_PROBE;
    941 		/* u->u_dma_func = ignored; */
    942 	}
    943 }
    944 
    945 /*
    946  * Enable/disable unit pinging (called by drivers)
    947  */
    948 /* ARGSUSED */
    949 void
    950 maple_enable_unit_ping(device_t dev, struct maple_unit *u, int func, int enable)
    951 {
    952 #if 0	/* currently unused */
    953 	struct maple_softc *sc = device_private(dev);
    954 #endif
    955 
    956 	if (enable)
    957 		u->u_noping &= ~MAPLE_FUNC(func);
    958 	else
    959 		u->u_noping |= MAPLE_FUNC(func);
    960 }
    961 
    962 /* schedule pinging a device */
    963 static void
    964 maple_unit_ping(struct maple_softc *sc)
    965 {
    966 	struct maple_unit *u;
    967 	struct maple_func *fn;
    968 #ifdef MAPLE_MEMCARD_PING_HACK
    969 	static const uint32_t memcard_ping_arg[2] = {
    970 		0x02000000,	/* htobe32(MAPLE_FUNC(MAPLE_FN_MEMCARD)) */
    971 		0		/* pt (1 byte) and unused 3 bytes */
    972 	};
    973 #endif
    974 
    975 	if ((u = TAILQ_FIRST(&sc->sc_pingq)) != NULL) {
    976 		KASSERT(u->u_queuestat == MAPLE_QUEUE_PING);
    977 		maple_remove_from_queues(sc, u);
    978 		if (u->u_dma_stat == MAPLE_DMA_IDLE && u->u_noping == 0) {
    979 #ifdef MAPLE_MEMCARD_PING_HACK
    980 			if (u->u_ping_stat == MAPLE_PING_MINFO) {
    981 				/* use MINFO for some memory cards */
    982 				maple_write_command(sc, u,
    983 				    MAPLE_COMMAND_GETMINFO,
    984 				    2, memcard_ping_arg);
    985 			} else
    986 #endif
    987 			{
    988 				fn = &u->u_func[u->u_ping_func];
    989 				fn->f_work = htobe32(MAPLE_FUNC(u->u_ping_func));
    990 				maple_write_command(sc, u,
    991 				    MAPLE_COMMAND_GETCOND,
    992 				    1, &fn->f_work);
    993 			}
    994 			u->u_dma_stat = MAPLE_DMA_PING;
    995 			/* u->u_dma_func = XXX; */
    996 		} else {
    997 			/* no need if periodic */
    998 			TAILQ_INSERT_TAIL(&sc->sc_pingq, u, u_q);
    999 			u->u_queuestat = MAPLE_QUEUE_PING;
   1000 		}
   1001 	}
   1002 }
   1003 
   1004 /*
   1005  * Enable/disable periodic GETCOND (called by drivers)
   1006  */
   1007 void
   1008 maple_enable_periodic(device_t dev, struct maple_unit *u, int func, int on)
   1009 {
   1010 	struct maple_softc *sc = device_private(dev);
   1011 	struct maple_func *fn;
   1012 
   1013 	KASSERT(func >= 0 && func < 32);
   1014 
   1015 	fn = &u->u_func[func];
   1016 
   1017 	if (on) {
   1018 		if (fn->f_periodic_stat == MAPLE_PERIODIC_NONE) {
   1019 			TAILQ_INSERT_TAIL(&sc->sc_periodicq, fn, f_periodicq);
   1020 			fn->f_periodic_stat = MAPLE_PERIODIC_INQ;
   1021 			u->getcond_func_set |= MAPLE_FUNC(func);
   1022 		}
   1023 	} else {
   1024 		if (fn->f_periodic_stat == MAPLE_PERIODIC_INQ)
   1025 			TAILQ_REMOVE(&sc->sc_periodicq, fn, f_periodicq);
   1026 		else if (fn->f_periodic_stat == MAPLE_PERIODIC_DEFERED)
   1027 			TAILQ_REMOVE(&sc->sc_periodicdeferq, fn, f_periodicq);
   1028 		fn->f_periodic_stat = MAPLE_PERIODIC_NONE;
   1029 		u->getcond_func_set &= ~MAPLE_FUNC(func);
   1030 	}
   1031 }
   1032 
   1033 /*
   1034  * queue periodic GETCOND
   1035  */
   1036 static int
   1037 maple_send_defered_periodic(struct maple_softc *sc)
   1038 {
   1039 	struct maple_unit *u;
   1040 	struct maple_func *fn, *nextfn;
   1041 	int defer_remain = 0;
   1042 
   1043 	for (fn = TAILQ_FIRST(&sc->sc_periodicdeferq); fn; fn = nextfn) {
   1044 		KASSERT(fn->f_periodic_stat == MAPLE_PERIODIC_DEFERED);
   1045 
   1046 		nextfn = TAILQ_NEXT(fn, f_periodicq);
   1047 
   1048 		u = fn->f_unit;
   1049 		if (u->u_dma_stat == MAPLE_DMA_IDLE ||
   1050 		    u->u_dma_stat == MAPLE_DMA_RETRY) {
   1051 			/*
   1052 			 * if IDLE  ->	queue this request
   1053 			 * if RETRY ->	the unit never be freed until the next
   1054 			 *		periodic timing, so just restore to
   1055 			 *		the normal periodic queue.
   1056 			 */
   1057 			TAILQ_REMOVE(&sc->sc_periodicdeferq, fn, f_periodicq);
   1058 			TAILQ_INSERT_TAIL(&sc->sc_periodicq, fn, f_periodicq);
   1059 			fn->f_periodic_stat = MAPLE_PERIODIC_INQ;
   1060 
   1061 			if (u->u_dma_stat == MAPLE_DMA_IDLE) {
   1062 				/*
   1063 				 * queue periodic command
   1064 				 */
   1065 				fn->f_work = htobe32(MAPLE_FUNC(fn->f_funcno));
   1066 				maple_write_command(sc, u,
   1067 				    MAPLE_COMMAND_GETCOND, 1, &fn->f_work);
   1068 				u->u_dma_stat = MAPLE_DMA_PERIODIC;
   1069 				u->u_dma_func = fn->f_funcno;
   1070 			}
   1071 		} else {
   1072 			defer_remain = 1;
   1073 		}
   1074 	}
   1075 
   1076 	return defer_remain;
   1077 }
   1078 
   1079 static void
   1080 maple_send_periodic(struct maple_softc *sc)
   1081 {
   1082 	struct maple_unit *u;
   1083 	struct maple_func *fn, *nextfn;
   1084 
   1085 	for (fn = TAILQ_FIRST(&sc->sc_periodicq); fn; fn = nextfn) {
   1086 		KASSERT(fn->f_periodic_stat == MAPLE_PERIODIC_INQ);
   1087 
   1088 		nextfn = TAILQ_NEXT(fn, f_periodicq);
   1089 
   1090 		u = fn->f_unit;
   1091 		if (u->u_dma_stat != MAPLE_DMA_IDLE) {
   1092 			if (u->u_dma_stat != MAPLE_DMA_RETRY) {
   1093 				/*
   1094 				 * can't be queued --- move to defered queue
   1095 				 */
   1096 				TAILQ_REMOVE(&sc->sc_periodicq, fn,
   1097 				    f_periodicq);
   1098 				TAILQ_INSERT_TAIL(&sc->sc_periodicdeferq, fn,
   1099 				    f_periodicq);
   1100 				fn->f_periodic_stat = MAPLE_PERIODIC_DEFERED;
   1101 			}
   1102 		} else {
   1103 			/*
   1104 			 * queue periodic command
   1105 			 */
   1106 			fn->f_work = htobe32(MAPLE_FUNC(fn->f_funcno));
   1107 			maple_write_command(sc, u, MAPLE_COMMAND_GETCOND,
   1108 			    1, &fn->f_work);
   1109 			u->u_dma_stat = MAPLE_DMA_PERIODIC;
   1110 			u->u_dma_func = fn->f_funcno;
   1111 		}
   1112 	}
   1113 }
   1114 
   1115 static void
   1116 maple_remove_from_queues(struct maple_softc *sc, struct maple_unit *u)
   1117 {
   1118 
   1119 	/* remove from queues */
   1120 	if (u->u_queuestat == MAPLE_QUEUE_PROBE)
   1121 		TAILQ_REMOVE(&sc->sc_probeq, u, u_q);
   1122 	else if (u->u_queuestat == MAPLE_QUEUE_PING)
   1123 		TAILQ_REMOVE(&sc->sc_pingq, u, u_q);
   1124 #ifdef DIAGNOSTIC
   1125 	else if (u->u_queuestat != MAPLE_QUEUE_NONE)
   1126 		panic("maple_remove_from_queues: queuestat %d", u->u_queuestat);
   1127 #endif
   1128 #if defined(MAPLE_DEBUG) && MAPLE_DEBUG > 2
   1129 	if (u->u_queuestat != MAPLE_QUEUE_NONE) {
   1130 		char buf[16];
   1131 		printf("%s: dequeued\n",
   1132 		    maple_unit_name(buf, u->port, u->subunit));
   1133 	}
   1134 #endif
   1135 
   1136 	u->u_queuestat = MAPLE_QUEUE_NONE;
   1137 }
   1138 
   1139 /*
   1140  * retry current command at next periodic timing
   1141  */
   1142 static int
   1143 maple_retry(struct maple_softc *sc, struct maple_unit *u,
   1144 	enum maple_dma_stat st)
   1145 {
   1146 
   1147 	KASSERT(st != MAPLE_DMA_IDLE && st != MAPLE_DMA_RETRY);
   1148 
   1149 #if defined(MAPLE_DEBUG) && MAPLE_DEBUG > 2
   1150 	if (u->u_retrycnt == 0) {
   1151 		char buf[16];
   1152 		printf("%s: retrying: %#x, %#x, %p\n",
   1153 		    maple_unit_name(buf, u->port, u->subunit),
   1154 		    u->u_command, u->u_datalen, u->u_dataaddr);
   1155 	}
   1156 #endif
   1157 	if (u->u_retrycnt >= MAPLE_RETRY_MAX)
   1158 		return 1;
   1159 
   1160 	u->u_retrycnt++;
   1161 
   1162 	u->u_saved_dma_stat = st;
   1163 	u->u_dma_stat = MAPLE_DMA_RETRY; /* no new command before retry done */
   1164 	SIMPLEQ_INSERT_TAIL(&sc->sc_retryq, u, u_dmaq);
   1165 
   1166 	return 0;
   1167 }
   1168 
   1169 static void
   1170 maple_queue_retry(struct maple_softc *sc)
   1171 {
   1172 	struct maple_unit *u, *nextu;
   1173 
   1174 	/*
   1175 	 * Note: since the queue element is queued immediately
   1176 	 *	 in maple_queue_command, we can't use SIMPLEQ_FOREACH.
   1177 	 */
   1178 	for (u = SIMPLEQ_FIRST(&sc->sc_retryq); u; u = nextu) {
   1179 		nextu = SIMPLEQ_NEXT(u, u_dmaq);
   1180 
   1181 		/*
   1182 		 * Retrying is in the highest priority, and the unit shall
   1183 		 * always be free.
   1184 		 */
   1185 		KASSERT(u->u_dma_stat == MAPLE_DMA_RETRY);
   1186 		maple_queue_command(sc, u, u->u_command, u->u_datalen,
   1187 		    u->u_dataaddr);
   1188 		u->u_dma_stat = u->u_saved_dma_stat;
   1189 
   1190 #ifdef DIAGNOSTIC
   1191 		KASSERT(u->u_saved_dma_stat != MAPLE_DMA_IDLE);
   1192 		u->u_saved_dma_stat = MAPLE_DMA_IDLE;
   1193 #endif
   1194 	}
   1195 	SIMPLEQ_INIT(&sc->sc_retryq);
   1196 }
   1197 
   1198 /*
   1199  * Process DMA results.
   1200  * Requires kernel context.
   1201  */
   1202 static void
   1203 maple_check_responses(struct maple_softc *sc)
   1204 {
   1205 	struct maple_unit *u, *nextu;
   1206 	struct maple_func *fn;
   1207 	maple_response_t response;
   1208 	int func_code, len;
   1209 	int flags;
   1210 	char buf[16];
   1211 
   1212 	/*
   1213 	 * Note: since the queue element may be queued immediately,
   1214 	 *	 we can't use SIMPLEQ_FOREACH.
   1215 	 */
   1216 	for (u = SIMPLEQ_FIRST(&sc->sc_dmaq), maple_begin_txbuf(sc);
   1217 	    u; u = nextu) {
   1218 		nextu = SIMPLEQ_NEXT(u, u_dmaq);
   1219 
   1220 		if (u->u_dma_stat == MAPLE_DMA_IDLE)
   1221 			continue;	/* just detached or DDB was active */
   1222 
   1223 		/*
   1224 		 * check for retransmission
   1225 		 */
   1226 		if ((response = u->u_rxbuf[0]) == MAPLE_RESPONSE_AGAIN) {
   1227 			if (maple_retry(sc, u, u->u_dma_stat) == 0)
   1228 				continue;
   1229 			/* else pass error to upper layer */
   1230 		}
   1231 
   1232 		len = (u->u_rxbuf[0] >> 24);	/* length in long */
   1233 		len <<= 2;			/* length in byte */
   1234 
   1235 		/*
   1236 		 * call handler
   1237 		 */
   1238 		if (u->u_dma_stat == MAPLE_DMA_PERIODIC) {
   1239 			/*
   1240 			 * periodic GETCOND
   1241 			 */
   1242 			u->u_dma_stat = MAPLE_DMA_IDLE;
   1243 			func_code = u->u_dma_func;
   1244 			if (response == MAPLE_RESPONSE_DATATRF && len > 0 &&
   1245 			    be32toh(u->u_rxbuf[1]) == MAPLE_FUNC(func_code)) {
   1246 				fn = &u->u_func[func_code];
   1247 				if (fn->f_dev)
   1248 					(*fn->f_callback)(fn->f_arg,
   1249 					    (void *)u->u_rxbuf, len,
   1250 					    MAPLE_FLAG_PERIODIC);
   1251 			} else if (response == MAPLE_RESPONSE_NONE) {
   1252 				/* XXX OK? */
   1253 				/* detach */
   1254 #if defined(MAPLE_DEBUG) && MAPLE_DEBUG > 2
   1255 				printf("%s: func: %d: periodic response %d\n",
   1256 				    maple_unit_name(buf, u->port, u->subunit),
   1257 				    u->u_dma_func,
   1258 				    response);
   1259 #endif
   1260 				/*
   1261 				 * Some 3rd party devices sometimes
   1262 				 * do not respond.
   1263 				 */
   1264 				if (maple_retry(sc, u, MAPLE_DMA_PERIODIC))
   1265 					maple_detach_unit(sc, u);
   1266 			}
   1267 			/* XXX check unexpected conditions? */
   1268 
   1269 		} else if (u->u_dma_stat == MAPLE_DMA_PROBE) {
   1270 			KASSERT(u->u_queuestat == MAPLE_QUEUE_NONE);
   1271 			u->u_dma_stat = MAPLE_DMA_IDLE;
   1272 			switch (response) {
   1273 			default:
   1274 			case MAPLE_RESPONSE_NONE:
   1275 				/*
   1276 				 * Do not use maple_retry(), which conflicts
   1277 				 * with probe structure.
   1278 				 */
   1279 				if (u->subunit != 0 &&
   1280 				    ++u->u_proberetry > MAPLE_PROBERETRY_MAX) {
   1281 					printf("%s: no response\n",
   1282 					    maple_unit_name(buf,
   1283 						u->port, u->subunit));
   1284 				} else {
   1285 					/* probe again */
   1286 #if defined(MAPLE_DEBUG) && MAPLE_DEBUG > 2
   1287 					printf("%s: queued to probe 4\n",
   1288 					    maple_unit_name(buf, u->port, u->subunit));
   1289 #endif
   1290 					TAILQ_INSERT_TAIL(&sc->sc_probeq, u,
   1291 					    u_q);
   1292 					u->u_queuestat = MAPLE_QUEUE_PROBE;
   1293 				}
   1294 				break;
   1295 			case MAPLE_RESPONSE_DEVINFO:
   1296 				/* check if the unit is changed */
   1297 				maple_check_unit_change(sc, u);
   1298 				break;
   1299 			}
   1300 
   1301 		} else if (u->u_dma_stat == MAPLE_DMA_PING) {
   1302 			KASSERT(u->u_queuestat == MAPLE_QUEUE_NONE);
   1303 			u->u_dma_stat = MAPLE_DMA_IDLE;
   1304 			switch (response) {
   1305 			default:
   1306 			case MAPLE_RESPONSE_NONE:
   1307 				/*
   1308 				 * Some 3rd party devices sometimes
   1309 				 * do not respond.
   1310 				 */
   1311 				if (maple_retry(sc, u, MAPLE_DMA_PING)) {
   1312 					/* detach */
   1313 #if defined(MAPLE_DEBUG) && MAPLE_DEBUG > 1
   1314 					printf("%s: ping response %d\n",
   1315 					    maple_unit_name(buf, u->port,
   1316 						u->subunit),
   1317 					    response);
   1318 #endif
   1319 #ifdef MAPLE_MEMCARD_PING_HACK
   1320 					if (u->u_ping_stat
   1321 					    == MAPLE_PING_MEMCARD) {
   1322 						/*
   1323 						 * The unit claims itself to be
   1324 						 * a Visual Memory, and has
   1325 						 * never responded to GETCOND.
   1326 						 * Try again using MINFO, in
   1327 						 * case it is a poorly
   1328 						 * implemented 3rd party card.
   1329 						 */
   1330 #ifdef MAPLE_DEBUG
   1331 						printf("%s: switching ping method\n",
   1332 						    maple_unit_name(buf,
   1333 							u->port, u->subunit));
   1334 #endif
   1335 						u->u_ping_stat
   1336 						    = MAPLE_PING_MINFO;
   1337 						TAILQ_INSERT_TAIL(&sc->sc_pingq,
   1338 						    u, u_q);
   1339 						u->u_queuestat
   1340 						    = MAPLE_QUEUE_PING;
   1341 					} else
   1342 #endif	/* MAPLE_MEMCARD_PING_HACK */
   1343 					maple_detach_unit(sc, u);
   1344 				}
   1345 				break;
   1346 			case MAPLE_RESPONSE_BADCMD:
   1347 			case MAPLE_RESPONSE_BADFUNC:
   1348 			case MAPLE_RESPONSE_DATATRF:
   1349 				TAILQ_INSERT_TAIL(&sc->sc_pingq, u, u_q);
   1350 				u->u_queuestat = MAPLE_QUEUE_PING;
   1351 #ifdef MAPLE_MEMCARD_PING_HACK
   1352 				/*
   1353 				 * If the unit responds to GETCOND, it is a
   1354 				 * normal implementation.
   1355 				 */
   1356 				if (u->u_ping_stat == MAPLE_PING_MEMCARD)
   1357 					u->u_ping_stat = MAPLE_PING_NORMAL;
   1358 #endif
   1359 				break;
   1360 			}
   1361 
   1362 		} else {
   1363 			/*
   1364 			 * Note: Do not rely on the consistency of responses.
   1365 			 */
   1366 
   1367 			if (response == MAPLE_RESPONSE_NONE) {
   1368 				if (maple_retry(sc, u, u->u_dma_stat)) {
   1369 					/* detach */
   1370 #if defined(MAPLE_DEBUG) && MAPLE_DEBUG > 1
   1371 					printf("%s: command response %d\n",
   1372 					    maple_unit_name(buf, u->port,
   1373 						u->subunit),
   1374 					    response);
   1375 #endif
   1376 					maple_detach_unit(sc, u);
   1377 				}
   1378 				continue;
   1379 			}
   1380 
   1381 			flags = (u->u_dma_stat == MAPLE_DMA_PCMD) ?
   1382 			    MAPLE_FLAG_CMD_PERIODIC_TIMING : 0;
   1383 			u->u_dma_stat = MAPLE_DMA_IDLE;
   1384 
   1385 			func_code = u->u_dma_func;
   1386 			fn = &u->u_func[func_code];
   1387 			if (fn->f_dev == NULL) {
   1388 				/* detached right now */
   1389 #ifdef MAPLE_DEBUG
   1390 				printf("%s: unknown function: function %d, response %d\n",
   1391 				    maple_unit_name(buf, u->port, u->subunit),
   1392 				    func_code, response);
   1393 #endif
   1394 				continue;
   1395 			}
   1396 			if (fn->f_callback != NULL) {
   1397 				(*fn->f_callback)(fn->f_arg,
   1398 				    (void *)u->u_rxbuf, len, flags);
   1399 			}
   1400 		}
   1401 
   1402 		/*
   1403 		 * check for subunit change and schedule probing subunits
   1404 		 */
   1405 		if (u->subunit == 0 && response != MAPLE_RESPONSE_NONE &&
   1406 		    response != MAPLE_RESPONSE_AGAIN &&
   1407 		    ((int8_t *) u->u_rxbuf)[2] != sc->sc_port_unit_map[u->port])
   1408 			maple_check_subunit_change(sc, u);
   1409 	}
   1410 }
   1411 
   1412 /*
   1413  * Main Maple Bus thread
   1414  */
   1415 static void
   1416 maple_event_thread(void *arg)
   1417 {
   1418 	struct maple_softc *sc = arg;
   1419 	unsigned cnt = 1;	/* timing counter */
   1420 	int s;
   1421 #if defined(MAPLE_DEBUG) && MAPLE_DEBUG > 1
   1422 	int noreq = 0;
   1423 #endif
   1424 
   1425 #ifdef MAPLE_DEBUG
   1426 	printf("%s: forked event thread, pid %d\n",
   1427 	    device_xname(sc->sc_dev), sc->event_thread->l_proc->p_pid);
   1428 #endif
   1429 
   1430 	/* begin first DMA cycle */
   1431 	maple_begin_txbuf(sc);
   1432 
   1433 	sc->sc_event = 1;
   1434 
   1435 	/* OK, continue booting system */
   1436 	maple_polling = 0;
   1437 	config_pending_decr(sc->sc_dev);
   1438 
   1439 	for (;;) {
   1440 		/*
   1441 		 * queue requests
   1442 		 */
   1443 
   1444 		/* queue async commands */
   1445 		if (!TAILQ_EMPTY(&sc->sc_acmdq))
   1446 			maple_queue_cmds(sc, &sc->sc_acmdq);
   1447 
   1448 		/* send defered periodic command */
   1449 		if (!TAILQ_EMPTY(&sc->sc_periodicdeferq))
   1450 			maple_send_defered_periodic(sc);
   1451 
   1452 		/* queue periodic commands */
   1453 		if (sc->sc_event) {
   1454 			/* queue commands on periodic timing */
   1455 			if (!TAILQ_EMPTY(&sc->sc_pcmdq))
   1456 				maple_queue_cmds(sc, &sc->sc_pcmdq);
   1457 
   1458 			/* retry */
   1459 			if (!SIMPLEQ_EMPTY(&sc->sc_retryq))
   1460 				maple_queue_retry(sc);
   1461 
   1462 			if ((cnt & 31) == 0)	/* XXX */
   1463 				maple_unit_probe(sc);
   1464 			cnt++;
   1465 
   1466 			maple_send_periodic(sc);
   1467 			if ((cnt & 7) == 0)	/* XXX */
   1468 				maple_unit_ping(sc);
   1469 
   1470 			/*
   1471 			 * schedule periodic event
   1472 			 */
   1473 			sc->sc_event = 0;
   1474 			callout_reset(&sc->maple_callout_ch,
   1475 			    MAPLE_CALLOUT_TICKS, maple_callout, sc);
   1476 		}
   1477 
   1478 		if (maple_end_txbuf(sc)) {
   1479 
   1480 			/*
   1481 			 * start DMA
   1482 			 */
   1483 			s = splmaple();
   1484 			maple_start(sc);
   1485 
   1486 			/*
   1487 			 * wait until DMA done
   1488 			 */
   1489 			if (tsleep(&sc->sc_dmadone, PWAIT, "mdma", hz)
   1490 			    == EWOULDBLOCK) {
   1491 				/* was DDB active? */
   1492 				printf("%s: timed out\n",
   1493 				    device_xname(sc->sc_dev));
   1494 			}
   1495 			splx(s);
   1496 
   1497 			/*
   1498 			 * call handlers
   1499 			 */
   1500 			maple_check_responses(sc);
   1501 #if defined(MAPLE_DEBUG) && MAPLE_DEBUG > 1
   1502 			noreq = 0;
   1503 #endif
   1504 		}
   1505 #if defined(MAPLE_DEBUG) && MAPLE_DEBUG > 1
   1506 		else {
   1507 			/* weird if occurs in succession */
   1508 #if MAPLE_DEBUG <= 2
   1509 			if (noreq)	/* ignore first time */
   1510 #endif
   1511 				printf("%s: no request %d\n",
   1512 				    device_xname(sc->sc_dev), noreq);
   1513 			noreq++;
   1514 		}
   1515 #endif
   1516 
   1517 		/*
   1518 		 * wait for an event
   1519 		 */
   1520 		s = splsoftclock();
   1521 		if (TAILQ_EMPTY(&sc->sc_acmdq) && sc->sc_event == 0 &&
   1522 		    TAILQ_EMPTY(&sc->sc_periodicdeferq)) {
   1523 			if (tsleep(&sc->sc_event, PWAIT, "mslp", hz)
   1524 			    == EWOULDBLOCK) {
   1525 				printf("%s: event timed out\n",
   1526 				    device_xname(sc->sc_dev));
   1527 			}
   1528 
   1529 		}
   1530 		splx(s);
   1531 
   1532 	}
   1533 
   1534 #if 0	/* maple root device can't be detached */
   1535 	kthread_exit(0);
   1536 	/* NOTREACHED */
   1537 #endif
   1538 }
   1539 
   1540 static int
   1541 maple_intr(void *arg)
   1542 {
   1543 	struct maple_softc *sc = arg;
   1544 
   1545 	wakeup(&sc->sc_dmadone);
   1546 
   1547 	return 1;
   1548 }
   1549 
   1550 static void
   1551 maple_callout(void *ctx)
   1552 {
   1553 	struct maple_softc *sc = ctx;
   1554 
   1555 	sc->sc_event = 1;	/* mark as periodic event */
   1556 	wakeup(&sc->sc_event);
   1557 }
   1558 
   1559 /*
   1560  * Install callback handler (called by drivers)
   1561  */
   1562 /* ARGSUSED */
   1563 void
   1564 maple_set_callback(device_t dev, struct maple_unit *u, int func,
   1565 	void (*callback)(void *, struct maple_response *, int, int), void *arg)
   1566 {
   1567 #if 0	/* currently unused */
   1568 	struct maple_softc *sc = device_private(dev);
   1569 #endif
   1570 	struct maple_func *fn;
   1571 
   1572 	KASSERT(func >= 0 && func < MAPLE_NFUNC);
   1573 
   1574 	fn = &u->u_func[func];
   1575 
   1576 	fn->f_callback = callback;
   1577 	fn->f_arg = arg;
   1578 }
   1579 
   1580 /*
   1581  * Return function definition data (called by drivers)
   1582  */
   1583 uint32_t
   1584 maple_get_function_data(struct maple_devinfo *devinfo, int function_code)
   1585 {
   1586 	int i, p = 0;
   1587 	uint32_t func;
   1588 
   1589 	func = be32toh(devinfo->di_func);
   1590 	for (i = 31; i >= 0; --i)
   1591 		if (func & MAPLE_FUNC(i)) {
   1592 			if (function_code == i)
   1593 				return be32toh(devinfo->di_function_data[p]);
   1594 			else
   1595 				if (++p >= 3)
   1596 					break;
   1597 		}
   1598 
   1599 	return 0;
   1600 }
   1601 
   1602 /* Generic maple device interface */
   1603 
   1604 int
   1605 mapleopen(dev_t dev, int flag, int mode, struct lwp *l)
   1606 {
   1607 	struct maple_softc *sc;
   1608 
   1609 	sc = device_lookup_private(&maple_cd, MAPLEBUSUNIT(dev));
   1610 	if (sc == NULL)			/* make sure it was attached */
   1611 		return ENXIO;
   1612 
   1613 	if (MAPLEPORT(dev) >= MAPLE_PORTS)
   1614 		return ENXIO;
   1615 
   1616 	if (MAPLESUBUNIT(dev) >= MAPLE_SUBUNITS)
   1617 		return ENXIO;
   1618 
   1619 	if (!(sc->sc_port_units[MAPLEPORT(dev)] & (1 << MAPLESUBUNIT(dev))))
   1620 		return ENXIO;
   1621 
   1622 	sc->sc_port_units_open[MAPLEPORT(dev)] |= 1 << MAPLESUBUNIT(dev);
   1623 
   1624 	return 0;
   1625 }
   1626 
   1627 int
   1628 mapleclose(dev_t dev, int flag, int mode, struct lwp *l)
   1629 {
   1630 	struct maple_softc *sc;
   1631 
   1632 	sc = device_lookup_private(&maple_cd, MAPLEBUSUNIT(dev));
   1633 
   1634 	sc->sc_port_units_open[MAPLEPORT(dev)] &= ~(1 << MAPLESUBUNIT(dev));
   1635 
   1636 	return 0;
   1637 }
   1638 
   1639 int
   1640 maple_unit_ioctl(device_t dev, struct maple_unit *u, u_long cmd,
   1641     void *data, int flag, struct lwp *l)
   1642 {
   1643 	struct maple_softc *sc = device_private(dev);
   1644 
   1645 	if (!(sc->sc_port_units[u->port] & (1 << u->subunit)))
   1646 		return ENXIO;
   1647 
   1648 	switch(cmd) {
   1649 	case MAPLEIO_GDEVINFO:
   1650 		memcpy(data, &u->devinfo, sizeof(struct maple_devinfo));
   1651 		break;
   1652 	default:
   1653 		return EPASSTHROUGH;
   1654 	}
   1655 
   1656 	return 0;
   1657 }
   1658 
   1659 int
   1660 mapleioctl(dev_t dev, u_long cmd, void *data, int flag, struct lwp *l)
   1661 {
   1662 	struct maple_softc *sc;
   1663 	struct maple_unit *u;
   1664 
   1665 	sc = device_lookup_private(&maple_cd, MAPLEBUSUNIT(dev));
   1666 	u = &sc->sc_unit[MAPLEPORT(dev)][MAPLESUBUNIT(dev)];
   1667 
   1668 	return maple_unit_ioctl(sc->sc_dev, u, cmd, data, flag, l);
   1669 }
   1670