xref: /freebsd/sys/dev/gpio/gpiobus.c (revision f5463265955b829775bbb32e1fd0bc11dafc36ce)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2009 Oleksandr Tymoshenko <gonzo@freebsd.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/param.h>
30 #include <sys/systm.h>
31 #include <sys/bus.h>
32 #include <sys/gpio.h>
33 #ifdef INTRNG
34 #include <sys/intr.h>
35 #endif
36 #include <sys/kernel.h>
37 #include <sys/malloc.h>
38 #include <sys/module.h>
39 #include <sys/sbuf.h>
40 
41 #include <dev/gpio/gpiobusvar.h>
42 
43 #include "gpiobus_if.h"
44 
45 #undef GPIOBUS_DEBUG
46 #ifdef GPIOBUS_DEBUG
47 #define	dprintf printf
48 #else
49 #define	dprintf(x, arg...)
50 #endif
51 
52 static void gpiobus_print_pins(struct gpiobus_ivar *, struct sbuf *);
53 static int gpiobus_parse_pins(struct gpiobus_softc *, device_t, int);
54 static int gpiobus_probe(device_t);
55 static int gpiobus_attach(device_t);
56 static int gpiobus_detach(device_t);
57 static int gpiobus_suspend(device_t);
58 static int gpiobus_resume(device_t);
59 static void gpiobus_probe_nomatch(device_t, device_t);
60 static int gpiobus_print_child(device_t, device_t);
61 static int gpiobus_child_location(device_t, device_t, struct sbuf *);
62 static device_t gpiobus_add_child(device_t, u_int, const char *, int);
63 static void gpiobus_hinted_child(device_t, const char *, int);
64 
65 /*
66  * GPIOBUS interface
67  */
68 static int gpiobus_acquire_bus(device_t, device_t, int);
69 static void gpiobus_release_bus(device_t, device_t);
70 static int gpiobus_pin_setflags(device_t, device_t, uint32_t, uint32_t);
71 static int gpiobus_pin_getflags(device_t, device_t, uint32_t, uint32_t*);
72 static int gpiobus_pin_getcaps(device_t, device_t, uint32_t, uint32_t*);
73 static int gpiobus_pin_set(device_t, device_t, uint32_t, unsigned int);
74 static int gpiobus_pin_get(device_t, device_t, uint32_t, unsigned int*);
75 static int gpiobus_pin_toggle(device_t, device_t, uint32_t);
76 
77 /*
78  * gpiobus_pin flags
79  *  The flags in struct gpiobus_pin are not related to the flags used by the
80  *  low-level controller driver in struct gpio_pin.  Currently, only pins
81  *  acquired via FDT data have gpiobus_pin.flags set, sourced from the flags in
82  *  the FDT properties.  In theory, these flags are defined per-platform.  In
83  *  practice they are always the flags from the dt-bindings/gpio/gpio.h file.
84  *  The only one of those flags we currently support is for handling active-low
85  *  pins, so we just define that flag here instead of including a GPL'd header.
86  */
87 #define	GPIO_ACTIVE_LOW 1
88 
89 /*
90  * XXX -> Move me to better place - gpio_subr.c?
91  * Also, this function must be changed when interrupt configuration
92  * data will be moved into struct resource.
93  */
94 #ifdef INTRNG
95 
96 struct resource *
97 gpio_alloc_intr_resource(device_t consumer_dev, int *rid, u_int alloc_flags,
98     gpio_pin_t pin, uint32_t intr_mode)
99 {
100 	u_int irq;
101 	struct intr_map_data_gpio *gpio_data;
102 	struct resource *res;
103 
104 	gpio_data = (struct intr_map_data_gpio *)intr_alloc_map_data(
105 	    INTR_MAP_DATA_GPIO, sizeof(*gpio_data), M_WAITOK | M_ZERO);
106 	gpio_data->gpio_pin_num = pin->pin;
107 	gpio_data->gpio_pin_flags = pin->flags;
108 	gpio_data->gpio_intr_mode = intr_mode;
109 
110 	irq = intr_map_irq(pin->dev, 0, (struct intr_map_data *)gpio_data);
111 	res = bus_alloc_resource(consumer_dev, SYS_RES_IRQ, rid, irq, irq, 1,
112 	    alloc_flags);
113 	if (res == NULL) {
114 		intr_free_intr_map_data((struct intr_map_data *)gpio_data);
115 		return (NULL);
116 	}
117 	rman_set_virtual(res, gpio_data);
118 	return (res);
119 }
120 #else
121 struct resource *
122 gpio_alloc_intr_resource(device_t consumer_dev, int *rid, u_int alloc_flags,
123     gpio_pin_t pin, uint32_t intr_mode)
124 {
125 
126 	return (NULL);
127 }
128 #endif
129 
130 int
131 gpio_check_flags(uint32_t caps, uint32_t flags)
132 {
133 
134 	/* Filter unwanted flags. */
135 	flags &= caps;
136 
137 	/* Cannot mix input/output together. */
138 	if (flags & GPIO_PIN_INPUT && flags & GPIO_PIN_OUTPUT)
139 		return (EINVAL);
140 	/* Cannot mix pull-up/pull-down together. */
141 	if (flags & GPIO_PIN_PULLUP && flags & GPIO_PIN_PULLDOWN)
142 		return (EINVAL);
143 	/* Cannot mix output and interrupt flags together */
144 	if (flags & GPIO_PIN_OUTPUT && flags & GPIO_INTR_MASK)
145 		return (EINVAL);
146 	/* Only one interrupt flag can be defined at once */
147 	if ((flags & GPIO_INTR_MASK) & ((flags & GPIO_INTR_MASK) - 1))
148 		return (EINVAL);
149 	/* The interrupt attached flag cannot be set */
150 	if (flags & GPIO_INTR_ATTACHED)
151 		return (EINVAL);
152 
153 	return (0);
154 }
155 
156 int
157 gpio_pin_get_by_bus_pinnum(device_t busdev, uint32_t pinnum, gpio_pin_t *ppin)
158 {
159 	gpio_pin_t pin;
160 	int err;
161 
162 	err = gpiobus_acquire_pin(busdev, pinnum);
163 	if (err != 0)
164 		return (EBUSY);
165 
166 	pin = malloc(sizeof(*pin), M_DEVBUF, M_WAITOK | M_ZERO);
167 
168 	pin->dev = device_get_parent(busdev);
169 	pin->pin = pinnum;
170 	pin->flags = 0;
171 
172 	*ppin = pin;
173 	return (0);
174 }
175 
176 int
177 gpio_pin_get_by_child_index(device_t childdev, uint32_t idx, gpio_pin_t *ppin)
178 {
179 	struct gpiobus_ivar *devi;
180 
181 	devi = GPIOBUS_IVAR(childdev);
182 	if (idx >= devi->npins)
183 		return (EINVAL);
184 
185 	return (gpio_pin_get_by_bus_pinnum(device_get_parent(childdev),
186 	    devi->pins[idx], ppin));
187 }
188 
189 int
190 gpio_pin_getcaps(gpio_pin_t pin, uint32_t *caps)
191 {
192 
193 	KASSERT(pin != NULL, ("GPIO pin is NULL."));
194 	KASSERT(pin->dev != NULL, ("GPIO pin device is NULL."));
195 	return (GPIO_PIN_GETCAPS(pin->dev, pin->pin, caps));
196 }
197 
198 int
199 gpio_pin_is_active(gpio_pin_t pin, bool *active)
200 {
201 	int rv;
202 	uint32_t tmp;
203 
204 	KASSERT(pin != NULL, ("GPIO pin is NULL."));
205 	KASSERT(pin->dev != NULL, ("GPIO pin device is NULL."));
206 	rv = GPIO_PIN_GET(pin->dev, pin->pin, &tmp);
207 	if (rv  != 0) {
208 		return (rv);
209 	}
210 
211 	if (pin->flags & GPIO_ACTIVE_LOW)
212 		*active = tmp == 0;
213 	else
214 		*active = tmp != 0;
215 	return (0);
216 }
217 
218 void
219 gpio_pin_release(gpio_pin_t gpio)
220 {
221 	device_t busdev;
222 
223 	if (gpio == NULL)
224 		return;
225 
226 	KASSERT(gpio->dev != NULL, ("GPIO pin device is NULL."));
227 
228 	busdev = GPIO_GET_BUS(gpio->dev);
229 	if (busdev != NULL)
230 		gpiobus_release_pin(busdev, gpio->pin);
231 
232 	free(gpio, M_DEVBUF);
233 }
234 
235 int
236 gpio_pin_set_active(gpio_pin_t pin, bool active)
237 {
238 	int rv;
239 	uint32_t tmp;
240 
241 	if (pin->flags & GPIO_ACTIVE_LOW)
242 		tmp = active ? 0 : 1;
243 	else
244 		tmp = active ? 1 : 0;
245 
246 	KASSERT(pin != NULL, ("GPIO pin is NULL."));
247 	KASSERT(pin->dev != NULL, ("GPIO pin device is NULL."));
248 	rv = GPIO_PIN_SET(pin->dev, pin->pin, tmp);
249 	return (rv);
250 }
251 
252 int
253 gpio_pin_setflags(gpio_pin_t pin, uint32_t flags)
254 {
255 	int rv;
256 
257 	KASSERT(pin != NULL, ("GPIO pin is NULL."));
258 	KASSERT(pin->dev != NULL, ("GPIO pin device is NULL."));
259 
260 	rv = GPIO_PIN_SETFLAGS(pin->dev, pin->pin, flags);
261 	return (rv);
262 }
263 
264 static void
265 gpiobus_print_pins(struct gpiobus_ivar *devi, struct sbuf *sb)
266 {
267 	int i, range_start, range_stop, need_coma;
268 
269 	if (devi->npins == 0)
270 		return;
271 
272 	need_coma = 0;
273 	range_start = range_stop = devi->pins[0];
274 	for (i = 1; i < devi->npins; i++) {
275 		if (devi->pins[i] != (range_stop + 1)) {
276 			if (need_coma)
277 				sbuf_cat(sb, ",");
278 			if (range_start != range_stop)
279 				sbuf_printf(sb, "%d-%d", range_start, range_stop);
280 			else
281 				sbuf_printf(sb, "%d", range_start);
282 			range_start = range_stop = devi->pins[i];
283 			need_coma = 1;
284 		}
285 		else
286 			range_stop++;
287 	}
288 
289 	if (need_coma)
290 		sbuf_cat(sb, ",");
291 	if (range_start != range_stop)
292 		sbuf_printf(sb, "%d-%d", range_start, range_stop);
293 	else
294 		sbuf_printf(sb, "%d", range_start);
295 }
296 
297 device_t
298 gpiobus_attach_bus(device_t dev)
299 {
300 	device_t busdev;
301 
302 	busdev = device_add_child(dev, "gpiobus", -1);
303 	if (busdev == NULL)
304 		return (NULL);
305 	if (device_add_child(dev, "gpioc", -1) == NULL) {
306 		device_delete_child(dev, busdev);
307 		return (NULL);
308 	}
309 #ifdef FDT
310 	ofw_gpiobus_register_provider(dev);
311 #endif
312 	bus_generic_attach(dev);
313 
314 	return (busdev);
315 }
316 
317 int
318 gpiobus_detach_bus(device_t dev)
319 {
320 	int err;
321 
322 #ifdef FDT
323 	ofw_gpiobus_unregister_provider(dev);
324 #endif
325 	err = bus_generic_detach(dev);
326 	if (err != 0)
327 		return (err);
328 
329 	return (device_delete_children(dev));
330 }
331 
332 int
333 gpiobus_init_softc(device_t dev)
334 {
335 	struct gpiobus_softc *sc;
336 
337 	sc = GPIOBUS_SOFTC(dev);
338 	sc->sc_busdev = dev;
339 	sc->sc_dev = device_get_parent(dev);
340 	sc->sc_intr_rman.rm_type = RMAN_ARRAY;
341 	sc->sc_intr_rman.rm_descr = "GPIO Interrupts";
342 	if (rman_init(&sc->sc_intr_rman) != 0 ||
343 	    rman_manage_region(&sc->sc_intr_rman, 0, ~0) != 0)
344 		panic("%s: failed to set up rman.", __func__);
345 
346 	if (GPIO_PIN_MAX(sc->sc_dev, &sc->sc_npins) != 0)
347 		return (ENXIO);
348 
349 	KASSERT(sc->sc_npins >= 0, ("GPIO device with no pins"));
350 
351 	/* Pins = GPIO_PIN_MAX() + 1 */
352 	sc->sc_npins++;
353 
354 	sc->sc_pins = malloc(sizeof(*sc->sc_pins) * sc->sc_npins, M_DEVBUF,
355 	    M_NOWAIT | M_ZERO);
356 	if (sc->sc_pins == NULL)
357 		return (ENOMEM);
358 
359 	/* Initialize the bus lock. */
360 	GPIOBUS_LOCK_INIT(sc);
361 
362 	return (0);
363 }
364 
365 int
366 gpiobus_alloc_ivars(struct gpiobus_ivar *devi)
367 {
368 
369 	/* Allocate pins and flags memory. */
370 	devi->pins = malloc(sizeof(uint32_t) * devi->npins, M_DEVBUF,
371 	    M_NOWAIT | M_ZERO);
372 	if (devi->pins == NULL)
373 		return (ENOMEM);
374 	return (0);
375 }
376 
377 void
378 gpiobus_free_ivars(struct gpiobus_ivar *devi)
379 {
380 
381 	if (devi->pins) {
382 		free(devi->pins, M_DEVBUF);
383 		devi->pins = NULL;
384 	}
385 	devi->npins = 0;
386 }
387 
388 int
389 gpiobus_acquire_pin(device_t bus, uint32_t pin)
390 {
391 	struct gpiobus_softc *sc;
392 
393 	sc = device_get_softc(bus);
394 	/* Consistency check. */
395 	if (pin >= sc->sc_npins) {
396 		device_printf(bus,
397 		    "invalid pin %d, max: %d\n", pin, sc->sc_npins - 1);
398 		return (-1);
399 	}
400 	/* Mark pin as mapped and give warning if it's already mapped. */
401 	if (sc->sc_pins[pin].mapped) {
402 		device_printf(bus, "warning: pin %d is already mapped\n", pin);
403 		return (-1);
404 	}
405 	sc->sc_pins[pin].mapped = 1;
406 
407 	return (0);
408 }
409 
410 /* Release mapped pin */
411 int
412 gpiobus_release_pin(device_t bus, uint32_t pin)
413 {
414 	struct gpiobus_softc *sc;
415 
416 	sc = device_get_softc(bus);
417 	/* Consistency check. */
418 	if (pin >= sc->sc_npins) {
419 		device_printf(bus,
420 		    "invalid pin %d, max=%d\n",
421 		    pin, sc->sc_npins - 1);
422 		return (-1);
423 	}
424 
425 	if (!sc->sc_pins[pin].mapped) {
426 		device_printf(bus, "pin %d is not mapped\n", pin);
427 		return (-1);
428 	}
429 	sc->sc_pins[pin].mapped = 0;
430 
431 	return (0);
432 }
433 
434 static int
435 gpiobus_acquire_child_pins(device_t dev, device_t child)
436 {
437 	struct gpiobus_ivar *devi = GPIOBUS_IVAR(child);
438 	int i;
439 
440 	for (i = 0; i < devi->npins; i++) {
441 		/* Reserve the GPIO pin. */
442 		if (gpiobus_acquire_pin(dev, devi->pins[i]) != 0) {
443 			device_printf(child, "cannot acquire pin %d\n",
444 			    devi->pins[i]);
445 			while (--i >= 0) {
446 				(void)gpiobus_release_pin(dev,
447 				    devi->pins[i]);
448 			}
449 			gpiobus_free_ivars(devi);
450 			return (EBUSY);
451 		}
452 	}
453 	for (i = 0; i < devi->npins; i++) {
454 		/* Use the child name as pin name. */
455 		GPIOBUS_PIN_SETNAME(dev, devi->pins[i],
456 		    device_get_nameunit(child));
457 
458 	}
459 	return (0);
460 }
461 
462 static int
463 gpiobus_parse_pins(struct gpiobus_softc *sc, device_t child, int mask)
464 {
465 	struct gpiobus_ivar *devi = GPIOBUS_IVAR(child);
466 	int i, npins;
467 
468 	npins = 0;
469 	for (i = 0; i < 32; i++) {
470 		if (mask & (1 << i))
471 			npins++;
472 	}
473 	if (npins == 0) {
474 		device_printf(child, "empty pin mask\n");
475 		return (EINVAL);
476 	}
477 	devi->npins = npins;
478 	if (gpiobus_alloc_ivars(devi) != 0) {
479 		device_printf(child, "cannot allocate device ivars\n");
480 		return (EINVAL);
481 	}
482 	npins = 0;
483 	for (i = 0; i < 32; i++) {
484 		if ((mask & (1 << i)) == 0)
485 			continue;
486 		devi->pins[npins++] = i;
487 	}
488 
489 	return (0);
490 }
491 
492 static int
493 gpiobus_parse_pin_list(struct gpiobus_softc *sc, device_t child,
494     const char *pins)
495 {
496 	struct gpiobus_ivar *devi = GPIOBUS_IVAR(child);
497 	const char *p;
498 	char *endp;
499 	unsigned long pin;
500 	int i, npins;
501 
502 	npins = 0;
503 	p = pins;
504 	for (;;) {
505 		pin = strtoul(p, &endp, 0);
506 		if (endp == p)
507 			break;
508 		npins++;
509 		if (*endp == '\0')
510 			break;
511 		p = endp + 1;
512 	}
513 
514 	if (*endp != '\0') {
515 		device_printf(child, "garbage in the pin list: %s\n", endp);
516 		return (EINVAL);
517 	}
518 	if (npins == 0) {
519 		device_printf(child, "empty pin list\n");
520 		return (EINVAL);
521 	}
522 
523 	devi->npins = npins;
524 	if (gpiobus_alloc_ivars(devi) != 0) {
525 		device_printf(child, "cannot allocate device ivars\n");
526 		return (EINVAL);
527 	}
528 
529 	i = 0;
530 	p = pins;
531 	for (;;) {
532 		pin = strtoul(p, &endp, 0);
533 
534 		devi->pins[i] = pin;
535 
536 		if (*endp == '\0')
537 			break;
538 		i++;
539 		p = endp + 1;
540 	}
541 
542 	return (0);
543 }
544 
545 static int
546 gpiobus_probe(device_t dev)
547 {
548 	device_set_desc(dev, "GPIO bus");
549 
550 	return (BUS_PROBE_GENERIC);
551 }
552 
553 static int
554 gpiobus_attach(device_t dev)
555 {
556 	int err;
557 
558 	err = gpiobus_init_softc(dev);
559 	if (err != 0)
560 		return (err);
561 
562 	/*
563 	 * Get parent's pins and mark them as unmapped
564 	 */
565 	bus_generic_probe(dev);
566 	bus_enumerate_hinted_children(dev);
567 
568 	return (bus_generic_attach(dev));
569 }
570 
571 /*
572  * Since this is not a self-enumerating bus, and since we always add
573  * children in attach, we have to always delete children here.
574  */
575 static int
576 gpiobus_detach(device_t dev)
577 {
578 	struct gpiobus_softc *sc;
579 	struct gpiobus_ivar *devi;
580 	device_t *devlist;
581 	int i, err, ndevs;
582 
583 	sc = GPIOBUS_SOFTC(dev);
584 	KASSERT(mtx_initialized(&sc->sc_mtx),
585 	    ("gpiobus mutex not initialized"));
586 	GPIOBUS_LOCK_DESTROY(sc);
587 
588 	if ((err = bus_generic_detach(dev)) != 0)
589 		return (err);
590 
591 	if ((err = device_get_children(dev, &devlist, &ndevs)) != 0)
592 		return (err);
593 	for (i = 0; i < ndevs; i++) {
594 		devi = GPIOBUS_IVAR(devlist[i]);
595 		gpiobus_free_ivars(devi);
596 		resource_list_free(&devi->rl);
597 		free(devi, M_DEVBUF);
598 		device_delete_child(dev, devlist[i]);
599 	}
600 	free(devlist, M_TEMP);
601 	rman_fini(&sc->sc_intr_rman);
602 	if (sc->sc_pins) {
603 		for (i = 0; i < sc->sc_npins; i++) {
604 			if (sc->sc_pins[i].name != NULL)
605 				free(sc->sc_pins[i].name, M_DEVBUF);
606 			sc->sc_pins[i].name = NULL;
607 		}
608 		free(sc->sc_pins, M_DEVBUF);
609 		sc->sc_pins = NULL;
610 	}
611 
612 	return (0);
613 }
614 
615 static int
616 gpiobus_suspend(device_t dev)
617 {
618 
619 	return (bus_generic_suspend(dev));
620 }
621 
622 static int
623 gpiobus_resume(device_t dev)
624 {
625 
626 	return (bus_generic_resume(dev));
627 }
628 
629 static void
630 gpiobus_probe_nomatch(device_t dev, device_t child)
631 {
632 	char pins[128];
633 	struct sbuf sb;
634 	struct gpiobus_ivar *devi;
635 
636 	devi = GPIOBUS_IVAR(child);
637 	sbuf_new(&sb, pins, sizeof(pins), SBUF_FIXEDLEN);
638 	gpiobus_print_pins(devi, &sb);
639 	sbuf_finish(&sb);
640 	device_printf(dev, "<unknown device> at pin%s %s",
641 	    devi->npins > 1 ? "s" : "", sbuf_data(&sb));
642 	resource_list_print_type(&devi->rl, "irq", SYS_RES_IRQ, "%jd");
643 	printf("\n");
644 }
645 
646 static int
647 gpiobus_print_child(device_t dev, device_t child)
648 {
649 	char pins[128];
650 	struct sbuf sb;
651 	int retval = 0;
652 	struct gpiobus_ivar *devi;
653 
654 	devi = GPIOBUS_IVAR(child);
655 	retval += bus_print_child_header(dev, child);
656 	if (devi->npins > 0) {
657 		if (devi->npins > 1)
658 			retval += printf(" at pins ");
659 		else
660 			retval += printf(" at pin ");
661 		sbuf_new(&sb, pins, sizeof(pins), SBUF_FIXEDLEN);
662 		gpiobus_print_pins(devi, &sb);
663 		sbuf_finish(&sb);
664 		retval += printf("%s", sbuf_data(&sb));
665 	}
666 	resource_list_print_type(&devi->rl, "irq", SYS_RES_IRQ, "%jd");
667 	retval += bus_print_child_footer(dev, child);
668 
669 	return (retval);
670 }
671 
672 static int
673 gpiobus_child_location(device_t bus, device_t child, struct sbuf *sb)
674 {
675 	struct gpiobus_ivar *devi;
676 
677 	devi = GPIOBUS_IVAR(child);
678 	sbuf_printf(sb, "pins=");
679 	gpiobus_print_pins(devi, sb);
680 
681 	return (0);
682 }
683 
684 static device_t
685 gpiobus_add_child(device_t dev, u_int order, const char *name, int unit)
686 {
687 	device_t child;
688 	struct gpiobus_ivar *devi;
689 
690 	child = device_add_child_ordered(dev, order, name, unit);
691 	if (child == NULL)
692 		return (child);
693 	devi = malloc(sizeof(struct gpiobus_ivar), M_DEVBUF, M_NOWAIT | M_ZERO);
694 	if (devi == NULL) {
695 		device_delete_child(dev, child);
696 		return (NULL);
697 	}
698 	resource_list_init(&devi->rl);
699 	device_set_ivars(child, devi);
700 
701 	return (child);
702 }
703 
704 static int
705 gpiobus_rescan(device_t dev)
706 {
707 
708 	/*
709 	 * Re-scan is supposed to remove and add children, but if someone has
710 	 * deleted the hints for a child we attached earlier, we have no easy
711 	 * way to handle that.  So this just attaches new children for whom new
712 	 * hints or drivers have arrived since we last tried.
713 	 */
714 	bus_enumerate_hinted_children(dev);
715 	bus_generic_attach(dev);
716 	return (0);
717 }
718 
719 static void
720 gpiobus_hinted_child(device_t bus, const char *dname, int dunit)
721 {
722 	struct gpiobus_softc *sc = GPIOBUS_SOFTC(bus);
723 	struct gpiobus_ivar *devi;
724 	device_t child;
725 	const char *pins;
726 	int irq, pinmask;
727 
728 	if (device_find_child(bus, dname, dunit) != NULL) {
729 		return;
730 	}
731 
732 	child = BUS_ADD_CHILD(bus, 0, dname, dunit);
733 	devi = GPIOBUS_IVAR(child);
734 	if (resource_int_value(dname, dunit, "pins", &pinmask) == 0) {
735 		if (gpiobus_parse_pins(sc, child, pinmask)) {
736 			resource_list_free(&devi->rl);
737 			free(devi, M_DEVBUF);
738 			device_delete_child(bus, child);
739 			return;
740 		}
741 	}
742 	else if (resource_string_value(dname, dunit, "pin_list", &pins) == 0) {
743 		if (gpiobus_parse_pin_list(sc, child, pins)) {
744 			resource_list_free(&devi->rl);
745 			free(devi, M_DEVBUF);
746 			device_delete_child(bus, child);
747 			return;
748 		}
749 	}
750 	if (resource_int_value(dname, dunit, "irq", &irq) == 0) {
751 		if (bus_set_resource(child, SYS_RES_IRQ, 0, irq, 1) != 0)
752 			device_printf(bus,
753 			    "warning: bus_set_resource() failed\n");
754 	}
755 }
756 
757 static int
758 gpiobus_read_ivar(device_t dev, device_t child, int which, uintptr_t *result)
759 {
760 	struct gpiobus_ivar *devi;
761 
762 	devi = GPIOBUS_IVAR(child);
763         switch (which) {
764 	case GPIOBUS_IVAR_NPINS:
765 		*result = devi->npins;
766 		break;
767 	case GPIOBUS_IVAR_PINS:
768 		/* Children do not ever need to directly examine this. */
769 		return (ENOTSUP);
770         default:
771                 return (ENOENT);
772         }
773 
774 	return (0);
775 }
776 
777 static int
778 gpiobus_write_ivar(device_t dev, device_t child, int which, uintptr_t value)
779 {
780 	struct gpiobus_ivar *devi;
781 	const uint32_t *ptr;
782 	int i;
783 
784 	devi = GPIOBUS_IVAR(child);
785         switch (which) {
786 	case GPIOBUS_IVAR_NPINS:
787 		/* GPIO ivars are set once. */
788 		if (devi->npins != 0) {
789 			return (EBUSY);
790 		}
791 		devi->npins = value;
792 		if (gpiobus_alloc_ivars(devi) != 0) {
793 			device_printf(child, "cannot allocate device ivars\n");
794 			devi->npins = 0;
795 			return (ENOMEM);
796 		}
797 		break;
798 	case GPIOBUS_IVAR_PINS:
799 		ptr = (const uint32_t *)value;
800 		for (i = 0; i < devi->npins; i++)
801 			devi->pins[i] = ptr[i];
802 		if (gpiobus_acquire_child_pins(dev, child) != 0)
803 			return (EBUSY);
804 		break;
805         default:
806                 return (ENOENT);
807         }
808 
809         return (0);
810 }
811 
812 static struct resource *
813 gpiobus_alloc_resource(device_t bus, device_t child, int type, int *rid,
814     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
815 {
816 	struct gpiobus_softc *sc;
817 	struct resource *rv;
818 	struct resource_list *rl;
819 	struct resource_list_entry *rle;
820 	int isdefault;
821 
822 	if (type != SYS_RES_IRQ)
823 		return (NULL);
824 	isdefault = (RMAN_IS_DEFAULT_RANGE(start, end) && count == 1);
825 	rle = NULL;
826 	if (isdefault) {
827 		rl = BUS_GET_RESOURCE_LIST(bus, child);
828 		if (rl == NULL)
829 			return (NULL);
830 		rle = resource_list_find(rl, type, *rid);
831 		if (rle == NULL)
832 			return (NULL);
833 		if (rle->res != NULL)
834 			panic("%s: resource entry is busy", __func__);
835 		start = rle->start;
836 		count = rle->count;
837 		end = rle->end;
838 	}
839 	sc = device_get_softc(bus);
840 	rv = rman_reserve_resource(&sc->sc_intr_rman, start, end, count, flags,
841 	    child);
842 	if (rv == NULL)
843 		return (NULL);
844 	rman_set_rid(rv, *rid);
845 	if ((flags & RF_ACTIVE) != 0 &&
846 	    bus_activate_resource(child, type, *rid, rv) != 0) {
847 		rman_release_resource(rv);
848 		return (NULL);
849 	}
850 
851 	return (rv);
852 }
853 
854 static int
855 gpiobus_release_resource(device_t bus __unused, device_t child, int type,
856     int rid, struct resource *r)
857 {
858 	int error;
859 
860 	if (rman_get_flags(r) & RF_ACTIVE) {
861 		error = bus_deactivate_resource(child, type, rid, r);
862 		if (error)
863 			return (error);
864 	}
865 
866 	return (rman_release_resource(r));
867 }
868 
869 static struct resource_list *
870 gpiobus_get_resource_list(device_t bus __unused, device_t child)
871 {
872 	struct gpiobus_ivar *ivar;
873 
874 	ivar = GPIOBUS_IVAR(child);
875 
876 	return (&ivar->rl);
877 }
878 
879 static int
880 gpiobus_acquire_bus(device_t busdev, device_t child, int how)
881 {
882 	struct gpiobus_softc *sc;
883 
884 	sc = device_get_softc(busdev);
885 	GPIOBUS_ASSERT_UNLOCKED(sc);
886 	GPIOBUS_LOCK(sc);
887 	if (sc->sc_owner != NULL) {
888 		if (sc->sc_owner == child)
889 			panic("%s: %s still owns the bus.",
890 			    device_get_nameunit(busdev),
891 			    device_get_nameunit(child));
892 		if (how == GPIOBUS_DONTWAIT) {
893 			GPIOBUS_UNLOCK(sc);
894 			return (EWOULDBLOCK);
895 		}
896 		while (sc->sc_owner != NULL)
897 			mtx_sleep(sc, &sc->sc_mtx, 0, "gpiobuswait", 0);
898 	}
899 	sc->sc_owner = child;
900 	GPIOBUS_UNLOCK(sc);
901 
902 	return (0);
903 }
904 
905 static void
906 gpiobus_release_bus(device_t busdev, device_t child)
907 {
908 	struct gpiobus_softc *sc;
909 
910 	sc = device_get_softc(busdev);
911 	GPIOBUS_ASSERT_UNLOCKED(sc);
912 	GPIOBUS_LOCK(sc);
913 	if (sc->sc_owner == NULL)
914 		panic("%s: %s releasing unowned bus.",
915 		    device_get_nameunit(busdev),
916 		    device_get_nameunit(child));
917 	if (sc->sc_owner != child)
918 		panic("%s: %s trying to release bus owned by %s",
919 		    device_get_nameunit(busdev),
920 		    device_get_nameunit(child),
921 		    device_get_nameunit(sc->sc_owner));
922 	sc->sc_owner = NULL;
923 	wakeup(sc);
924 	GPIOBUS_UNLOCK(sc);
925 }
926 
927 static int
928 gpiobus_pin_setflags(device_t dev, device_t child, uint32_t pin,
929     uint32_t flags)
930 {
931 	struct gpiobus_softc *sc = GPIOBUS_SOFTC(dev);
932 	struct gpiobus_ivar *devi = GPIOBUS_IVAR(child);
933 	uint32_t caps;
934 
935 	if (pin >= devi->npins)
936 		return (EINVAL);
937 	if (GPIO_PIN_GETCAPS(sc->sc_dev, devi->pins[pin], &caps) != 0)
938 		return (EINVAL);
939 	if (gpio_check_flags(caps, flags) != 0)
940 		return (EINVAL);
941 
942 	return (GPIO_PIN_SETFLAGS(sc->sc_dev, devi->pins[pin], flags));
943 }
944 
945 static int
946 gpiobus_pin_getflags(device_t dev, device_t child, uint32_t pin,
947     uint32_t *flags)
948 {
949 	struct gpiobus_softc *sc = GPIOBUS_SOFTC(dev);
950 	struct gpiobus_ivar *devi = GPIOBUS_IVAR(child);
951 
952 	if (pin >= devi->npins)
953 		return (EINVAL);
954 
955 	return GPIO_PIN_GETFLAGS(sc->sc_dev, devi->pins[pin], flags);
956 }
957 
958 static int
959 gpiobus_pin_getcaps(device_t dev, device_t child, uint32_t pin,
960     uint32_t *caps)
961 {
962 	struct gpiobus_softc *sc = GPIOBUS_SOFTC(dev);
963 	struct gpiobus_ivar *devi = GPIOBUS_IVAR(child);
964 
965 	if (pin >= devi->npins)
966 		return (EINVAL);
967 
968 	return GPIO_PIN_GETCAPS(sc->sc_dev, devi->pins[pin], caps);
969 }
970 
971 static int
972 gpiobus_pin_set(device_t dev, device_t child, uint32_t pin,
973     unsigned int value)
974 {
975 	struct gpiobus_softc *sc = GPIOBUS_SOFTC(dev);
976 	struct gpiobus_ivar *devi = GPIOBUS_IVAR(child);
977 
978 	if (pin >= devi->npins)
979 		return (EINVAL);
980 
981 	return GPIO_PIN_SET(sc->sc_dev, devi->pins[pin], value);
982 }
983 
984 static int
985 gpiobus_pin_get(device_t dev, device_t child, uint32_t pin,
986     unsigned int *value)
987 {
988 	struct gpiobus_softc *sc = GPIOBUS_SOFTC(dev);
989 	struct gpiobus_ivar *devi = GPIOBUS_IVAR(child);
990 
991 	if (pin >= devi->npins)
992 		return (EINVAL);
993 
994 	return GPIO_PIN_GET(sc->sc_dev, devi->pins[pin], value);
995 }
996 
997 static int
998 gpiobus_pin_toggle(device_t dev, device_t child, uint32_t pin)
999 {
1000 	struct gpiobus_softc *sc = GPIOBUS_SOFTC(dev);
1001 	struct gpiobus_ivar *devi = GPIOBUS_IVAR(child);
1002 
1003 	if (pin >= devi->npins)
1004 		return (EINVAL);
1005 
1006 	return GPIO_PIN_TOGGLE(sc->sc_dev, devi->pins[pin]);
1007 }
1008 
1009 static int
1010 gpiobus_pin_getname(device_t dev, uint32_t pin, char *name)
1011 {
1012 	struct gpiobus_softc *sc;
1013 
1014 	sc = GPIOBUS_SOFTC(dev);
1015 	if (pin > sc->sc_npins)
1016 		return (EINVAL);
1017 	/* Did we have a name for this pin ? */
1018 	if (sc->sc_pins[pin].name != NULL) {
1019 		memcpy(name, sc->sc_pins[pin].name, GPIOMAXNAME);
1020 		return (0);
1021 	}
1022 
1023 	/* Return the default pin name. */
1024 	return (GPIO_PIN_GETNAME(device_get_parent(dev), pin, name));
1025 }
1026 
1027 static int
1028 gpiobus_pin_setname(device_t dev, uint32_t pin, const char *name)
1029 {
1030 	struct gpiobus_softc *sc;
1031 
1032 	sc = GPIOBUS_SOFTC(dev);
1033 	if (pin > sc->sc_npins)
1034 		return (EINVAL);
1035 	if (name == NULL)
1036 		return (EINVAL);
1037 	/* Save the pin name. */
1038 	if (sc->sc_pins[pin].name == NULL)
1039 		sc->sc_pins[pin].name = malloc(GPIOMAXNAME, M_DEVBUF,
1040 		    M_WAITOK | M_ZERO);
1041 	strlcpy(sc->sc_pins[pin].name, name, GPIOMAXNAME);
1042 
1043 	return (0);
1044 }
1045 
1046 static device_method_t gpiobus_methods[] = {
1047 	/* Device interface */
1048 	DEVMETHOD(device_probe,		gpiobus_probe),
1049 	DEVMETHOD(device_attach,	gpiobus_attach),
1050 	DEVMETHOD(device_detach,	gpiobus_detach),
1051 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
1052 	DEVMETHOD(device_suspend,	gpiobus_suspend),
1053 	DEVMETHOD(device_resume,	gpiobus_resume),
1054 
1055 	/* Bus interface */
1056 	DEVMETHOD(bus_setup_intr,	bus_generic_setup_intr),
1057 	DEVMETHOD(bus_config_intr,	bus_generic_config_intr),
1058 	DEVMETHOD(bus_teardown_intr,	bus_generic_teardown_intr),
1059 	DEVMETHOD(bus_delete_resource,	bus_generic_rl_delete_resource),
1060 	DEVMETHOD(bus_get_resource,	bus_generic_rl_get_resource),
1061 	DEVMETHOD(bus_set_resource,	bus_generic_rl_set_resource),
1062 	DEVMETHOD(bus_alloc_resource,	gpiobus_alloc_resource),
1063 	DEVMETHOD(bus_release_resource,	gpiobus_release_resource),
1064 	DEVMETHOD(bus_activate_resource,	bus_generic_activate_resource),
1065 	DEVMETHOD(bus_deactivate_resource,	bus_generic_deactivate_resource),
1066 	DEVMETHOD(bus_get_resource_list,	gpiobus_get_resource_list),
1067 	DEVMETHOD(bus_add_child,	gpiobus_add_child),
1068 	DEVMETHOD(bus_rescan,		gpiobus_rescan),
1069 	DEVMETHOD(bus_probe_nomatch,	gpiobus_probe_nomatch),
1070 	DEVMETHOD(bus_print_child,	gpiobus_print_child),
1071 	DEVMETHOD(bus_child_location,	gpiobus_child_location),
1072 	DEVMETHOD(bus_hinted_child,	gpiobus_hinted_child),
1073 	DEVMETHOD(bus_read_ivar,        gpiobus_read_ivar),
1074 	DEVMETHOD(bus_write_ivar,       gpiobus_write_ivar),
1075 
1076 	/* GPIO protocol */
1077 	DEVMETHOD(gpiobus_acquire_bus,	gpiobus_acquire_bus),
1078 	DEVMETHOD(gpiobus_release_bus,	gpiobus_release_bus),
1079 	DEVMETHOD(gpiobus_pin_getflags,	gpiobus_pin_getflags),
1080 	DEVMETHOD(gpiobus_pin_getcaps,	gpiobus_pin_getcaps),
1081 	DEVMETHOD(gpiobus_pin_setflags,	gpiobus_pin_setflags),
1082 	DEVMETHOD(gpiobus_pin_get,	gpiobus_pin_get),
1083 	DEVMETHOD(gpiobus_pin_set,	gpiobus_pin_set),
1084 	DEVMETHOD(gpiobus_pin_toggle,	gpiobus_pin_toggle),
1085 	DEVMETHOD(gpiobus_pin_getname,	gpiobus_pin_getname),
1086 	DEVMETHOD(gpiobus_pin_setname,	gpiobus_pin_setname),
1087 
1088 	DEVMETHOD_END
1089 };
1090 
1091 driver_t gpiobus_driver = {
1092 	"gpiobus",
1093 	gpiobus_methods,
1094 	sizeof(struct gpiobus_softc)
1095 };
1096 
1097 EARLY_DRIVER_MODULE(gpiobus, gpio, gpiobus_driver, 0, 0,
1098     BUS_PASS_BUS + BUS_PASS_ORDER_MIDDLE);
1099 MODULE_VERSION(gpiobus, 1);
1100