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