Home | History | Annotate | Line # | Download | only in gpio
gpio.c revision 1.71
      1 /* $NetBSD: gpio.c,v 1.71 2022/04/27 23:15:30 brad Exp $ */
      2 /*	$OpenBSD: gpio.c,v 1.6 2006/01/14 12:33:49 grange Exp $	*/
      3 
      4 /*
      5  * Copyright (c) 2008, 2009, 2010, 2011 Marc Balmer <marc (at) msys.ch>
      6  * Copyright (c) 2004, 2006 Alexander Yurchenko <grange (at) openbsd.org>
      7  *
      8  * Permission to use, copy, modify, and distribute this software for any
      9  * purpose with or without fee is hereby granted, provided that the above
     10  * copyright notice and this permission notice appear in all copies.
     11  *
     12  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
     13  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
     14  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
     15  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     16  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
     17  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
     18  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     19  */
     20 
     21 #ifdef _KERNEL_OPT
     22 #include "opt_fdt.h"
     23 #endif
     24 
     25 #include <sys/cdefs.h>
     26 __KERNEL_RCSID(0, "$NetBSD: gpio.c,v 1.71 2022/04/27 23:15:30 brad Exp $");
     27 
     28 /*
     29  * General Purpose Input/Output framework.
     30  */
     31 
     32 #include <sys/param.h>
     33 #include <sys/callout.h>
     34 #include <sys/systm.h>
     35 #include <sys/conf.h>
     36 #include <sys/device.h>
     37 #include <sys/fcntl.h>
     38 #include <sys/ioctl.h>
     39 #include <sys/gpio.h>
     40 #include <sys/kernel.h>
     41 #include <sys/vnode.h>
     42 #include <sys/kmem.h>
     43 #include <sys/mutex.h>
     44 #include <sys/condvar.h>
     45 #include <sys/queue.h>
     46 #include <sys/kauth.h>
     47 #include <sys/module.h>
     48 
     49 #include <dev/gpio/gpiovar.h>
     50 
     51 #ifdef FDT
     52 #include <dev/fdt/fdtvar.h>
     53 #endif
     54 
     55 #include "ioconf.h"
     56 #include "locators.h"
     57 
     58 #ifdef GPIO_DEBUG
     59 #define DPRINTFN(n, x)	do { if (gpiodebug > (n)) printf x; } while (0)
     60 int gpiodebug = 0;
     61 #else
     62 #define DPRINTFN(n, x)
     63 #endif
     64 #define DPRINTF(x)	DPRINTFN(0, x)
     65 
     66 struct gpio_softc {
     67 	device_t		 sc_dev;
     68 
     69 	gpio_chipset_tag_t	 sc_gc;		/* GPIO controller */
     70 	gpio_pin_t		*sc_pins;	/* pins array */
     71 	int			 sc_npins;	/* number of pins */
     72 
     73 	kmutex_t		 sc_mtx;
     74 	kcondvar_t		 sc_ioctl;	/* ioctl in progress */
     75 	int			 sc_ioctl_busy;	/* ioctl is busy */
     76 	kcondvar_t		 sc_attach;	/* attach/detach in progress */
     77 	int			 sc_attach_busy;/* busy in attach/detach */
     78 #ifdef COMPAT_50
     79 	LIST_HEAD(, gpio_dev)	 sc_devs;	/* devices */
     80 #endif
     81 	LIST_HEAD(, gpio_name)	 sc_names;	/* named pins */
     82 };
     83 
     84 static int	gpio_match(device_t, cfdata_t, void *);
     85 int		gpio_submatch(device_t, cfdata_t, const int *, void *);
     86 static void	gpio_attach(device_t, device_t, void *);
     87 static int	gpio_rescan(device_t, const char *, const int *);
     88 static void	gpio_childdetached(device_t, device_t);
     89 static bool	gpio_resume(device_t, const pmf_qual_t *);
     90 static int	gpio_detach(device_t, int);
     91 static int	gpio_search(device_t, cfdata_t, const int *, void *);
     92 static int	gpio_print(void *, const char *);
     93 static int	gpio_pinbyname(struct gpio_softc *, char *);
     94 static int	gpio_ioctl(struct gpio_softc *, u_long, void *, int,
     95     struct lwp *);
     96 
     97 #ifdef COMPAT_50
     98 /* Old API */
     99 static int	gpio_ioctl_oapi(struct gpio_softc *, u_long, void *, int,
    100     struct lwp *);
    101 #endif
    102 
    103 CFATTACH_DECL3_NEW(gpio, sizeof(struct gpio_softc),
    104     gpio_match, gpio_attach, gpio_detach, NULL, gpio_rescan,
    105     gpio_childdetached, DVF_DETACH_SHUTDOWN);
    106 
    107 dev_type_open(gpioopen);
    108 dev_type_close(gpioclose);
    109 dev_type_ioctl(gpioioctl);
    110 dev_type_ioctl(gpioioctl_locked);
    111 
    112 const struct cdevsw gpio_cdevsw = {
    113 	.d_open = gpioopen,
    114 	.d_close = gpioclose,
    115 	.d_read = noread,
    116 	.d_write = nowrite,
    117 	.d_ioctl = gpioioctl,
    118 	.d_stop = nostop,
    119 	.d_tty = notty,
    120 	.d_poll = nopoll,
    121 	.d_mmap = nommap,
    122 	.d_kqfilter = nokqfilter,
    123 	.d_discard = nodiscard,
    124 	.d_flag = D_OTHER | D_MPSAFE
    125 };
    126 
    127 static int
    128 gpio_match(device_t parent, cfdata_t cf, void *aux)
    129 {
    130 	return 1;
    131 }
    132 
    133 int
    134 gpio_submatch(device_t parent, cfdata_t cf, const int *ip, void *aux)
    135 {
    136 	struct gpio_attach_args *ga = aux;
    137 
    138 	if (ga->ga_offset == -1)
    139 		return 0;
    140 
    141 	return strcmp(ga->ga_dvname, cf->cf_name) == 0;
    142 }
    143 
    144 static bool
    145 gpio_resume(device_t self, const pmf_qual_t *qual)
    146 {
    147 	struct gpio_softc *sc = device_private(self);
    148 	int pin;
    149 
    150 	for (pin = 0; pin < sc->sc_npins; pin++) {
    151 		gpiobus_pin_ctl(sc->sc_gc, pin, sc->sc_pins[pin].pin_flags);
    152 		gpiobus_pin_write(sc->sc_gc, pin, sc->sc_pins[pin].pin_state);
    153 	}
    154 	return true;
    155 }
    156 
    157 static void
    158 gpio_childdetached(device_t self, device_t child)
    159 {
    160 #ifdef COMPAT_50
    161 	struct gpio_dev *gdev;
    162 	struct gpio_softc *sc;
    163 	int error;
    164 
    165 	/*
    166 	 * gpio_childetached is serialized because it can be entered in
    167 	 * different ways concurrently, e.g. via the GPIODETACH ioctl and
    168 	 * drvctl(8) or modunload(8).
    169 	 */
    170 	sc = device_private(self);
    171 	error = 0;
    172 	mutex_enter(&sc->sc_mtx);
    173 	while (sc->sc_attach_busy) {
    174 		error = cv_wait_sig(&sc->sc_attach, &sc->sc_mtx);
    175 		if (error)
    176 			break;
    177 	}
    178 	if (!error)
    179 		sc->sc_attach_busy = 1;
    180 	mutex_exit(&sc->sc_mtx);
    181 	if (error)
    182 		return;
    183 
    184 	KERNEL_LOCK(1, NULL);
    185 	LIST_FOREACH(gdev, &sc->sc_devs, sc_next)
    186 		if (gdev->sc_dev == child) {
    187 			LIST_REMOVE(gdev, sc_next);
    188 			kmem_free(gdev, sizeof(struct gpio_dev));
    189 			break;
    190 		}
    191 	KERNEL_UNLOCK_ONE(NULL);
    192 
    193 	mutex_enter(&sc->sc_mtx);
    194 	sc->sc_attach_busy = 0;
    195 	cv_signal(&sc->sc_attach);
    196 	mutex_exit(&sc->sc_mtx);
    197 #endif
    198 }
    199 
    200 static int
    201 gpio_rescan(device_t self, const char *ifattr, const int *locators)
    202 {
    203 
    204 	KERNEL_LOCK(1, NULL);
    205 	config_search(self, NULL,
    206 	    CFARGS(.search = gpio_search));
    207 	KERNEL_UNLOCK_ONE(NULL);
    208 
    209 	return 0;
    210 }
    211 
    212 static const char *
    213 gpio_pin_defname(struct gpio_softc *sc, int pin)
    214 {
    215 	KASSERT(pin >= 0);
    216 
    217 #ifdef FDT
    218 	devhandle_t devhandle = device_handle(sc->sc_dev);
    219 
    220 	if (devhandle_type(devhandle) == DEVHANDLE_TYPE_OF) {
    221 		return fdtbus_get_string_index(devhandle_to_of(devhandle),
    222 		    "gpio-line-names", pin);
    223 	}
    224 #endif /* FDT */
    225 
    226 	return NULL;
    227 }
    228 
    229 static void
    230 gpio_attach(device_t parent, device_t self, void *aux)
    231 {
    232 	struct gpio_softc *sc = device_private(self);
    233 	struct gpiobus_attach_args *gba = aux;
    234 	struct gpio_name *nm;
    235 	int pin;
    236 
    237 	sc->sc_dev = self;
    238 	sc->sc_gc = gba->gba_gc;
    239 	sc->sc_pins = gba->gba_pins;
    240 	sc->sc_npins = gba->gba_npins;
    241 
    242 	aprint_normal(": %d pins\n", sc->sc_npins);
    243 	aprint_naive("\n");
    244 
    245 	/* Configure default pin names */
    246 	for (pin = 0; pin < sc->sc_npins; pin++) {
    247 		const char *defname;
    248 
    249 		defname = gpio_pin_defname(sc, pin);
    250 		if (defname == NULL &&
    251 		    sc->sc_pins[pin].pin_defname[0] != '\0') {
    252 			defname = sc->sc_pins[pin].pin_defname;
    253 		}
    254 		if (defname == NULL) {
    255 			continue;
    256 		}
    257 		nm = kmem_alloc(sizeof(*nm), KM_SLEEP);
    258 		strlcpy(nm->gp_name, defname, sizeof(nm->gp_name));
    259 		nm->gp_pin = pin;
    260 		LIST_INSERT_HEAD(&sc->sc_names, nm, gp_next);
    261 	}
    262 
    263 	if (!pmf_device_register(self, NULL, gpio_resume))
    264 		aprint_error_dev(self, "couldn't establish power handler\n");
    265 	mutex_init(&sc->sc_mtx, MUTEX_DEFAULT, IPL_VM);
    266 	cv_init(&sc->sc_ioctl, "gpioctl");
    267 	cv_init(&sc->sc_attach, "gpioatch");
    268 	/*
    269 	 * Attach all devices that can be connected to the GPIO pins
    270 	 * described in the kernel configuration file.
    271 	 */
    272 	gpio_rescan(self, "gpio", NULL);
    273 }
    274 
    275 static int
    276 gpio_detach(device_t self, int flags)
    277 {
    278 	struct gpio_softc *sc;
    279 	int rc;
    280 
    281 	sc = device_private(self);
    282 
    283 	if ((rc = config_detach_children(self, flags)) != 0)
    284 		return rc;
    285 	mutex_destroy(&sc->sc_mtx);
    286 	cv_destroy(&sc->sc_ioctl);
    287 #if 0
    288 	int maj, mn;
    289 
    290 	/* Locate the major number */
    291 	for (maj = 0; maj < nchrdev; maj++)
    292 		if (cdevsw[maj].d_open == gpioopen)
    293 			break;
    294 
    295 	/* Nuke the vnodes for any open instances (calls close) */
    296 	mn = device_unit(self);
    297 	vdevgone(maj, mn, mn, VCHR);
    298 #endif
    299 	return 0;
    300 }
    301 
    302 static int
    303 gpio_search(device_t parent, cfdata_t cf, const int *ldesc, void *aux)
    304 {
    305 	struct gpio_attach_args ga;
    306 	size_t namlen;
    307 
    308 	ga.ga_gpio = device_private(parent);
    309 	ga.ga_offset = cf->cf_loc[GPIOCF_OFFSET];
    310 	ga.ga_mask = cf->cf_loc[GPIOCF_MASK];
    311 	ga.ga_flags = cf->cf_loc[GPIOCF_FLAG];
    312 	namlen = strlen(cf->cf_name) + 1;
    313 	ga.ga_dvname = kmem_alloc(namlen, KM_SLEEP);
    314 	strcpy(ga.ga_dvname, cf->cf_name);
    315 
    316 	if (config_probe(parent, cf, &ga))
    317 		config_attach(parent, cf, &ga, gpio_print, CFARGS_NONE);
    318 	kmem_free(ga.ga_dvname, namlen);
    319 	return 0;
    320 }
    321 
    322 int
    323 gpio_print(void *aux, const char *pnp)
    324 {
    325 	struct gpio_attach_args *ga = aux;
    326 	int i;
    327 
    328 	aprint_normal(" pins");
    329 	for (i = 0; i < 32; i++)
    330 		if (ga->ga_mask & (1 << i))
    331 			aprint_normal(" %d", ga->ga_offset + i);
    332 
    333 	return UNCONF;
    334 }
    335 
    336 int
    337 gpiobus_print(void *aux, const char *pnp)
    338 {
    339 #if 0
    340 	struct gpiobus_attach_args *gba = aux;
    341 #endif
    342 	if (pnp != NULL)
    343 		aprint_normal("gpiobus at %s", pnp);
    344 
    345 	return UNCONF;
    346 }
    347 
    348 void *
    349 gpio_find_device(const char *name)
    350 {
    351 	device_t gpio_dev;
    352 	gpio_dev = device_find_by_xname(name);
    353 	if (gpio_dev == NULL)
    354 		return NULL;
    355 	return device_private(gpio_dev);
    356 }
    357 
    358 const char *
    359 gpio_get_name(void *gpio)
    360 {
    361 	struct gpio_softc *sc = gpio;
    362 	return device_xname(sc->sc_dev);
    363 }
    364 
    365 /* return 1 if all pins can be mapped, 0 if not */
    366 int
    367 gpio_pin_can_map(void *gpio, int offset, uint32_t mask)
    368 {
    369 	struct gpio_softc *sc = gpio;
    370 	int npins, pin, i;
    371 
    372 	npins = gpio_npins(mask);
    373 	if (npins > sc->sc_npins)
    374 		return 0;
    375 
    376 	for (npins = 0, i = 0; i < 32; i++)
    377 		if (mask & (1 << i)) {
    378 			pin = offset + i;
    379 			if (pin < 0 || pin >= sc->sc_npins)
    380 				return 0;
    381 			if (sc->sc_pins[pin].pin_mapped)
    382 				return 0;
    383 		}
    384 
    385 	return 1;
    386 }
    387 
    388 int
    389 gpio_pin_map(void *gpio, int offset, uint32_t mask, struct gpio_pinmap *map)
    390 {
    391 	struct gpio_softc *sc = gpio;
    392 	int npins, pin, i;
    393 
    394 	npins = gpio_npins(mask);
    395 	if (npins > sc->sc_npins)
    396 		return 1;
    397 
    398 	for (npins = 0, i = 0; i < 32; i++)
    399 		if (mask & (1 << i)) {
    400 			pin = offset + i;
    401 			if (pin < 0 || pin >= sc->sc_npins)
    402 				return 1;
    403 			if (sc->sc_pins[pin].pin_mapped)
    404 				return 1;
    405 			sc->sc_pins[pin].pin_mapped = 1;
    406 			map->pm_map[npins++] = pin;
    407 		}
    408 	map->pm_size = npins;
    409 
    410 	return 0;
    411 }
    412 
    413 void
    414 gpio_pin_unmap(void *gpio, struct gpio_pinmap *map)
    415 {
    416 	struct gpio_softc *sc = gpio;
    417 	int pin, i;
    418 
    419 	for (i = 0; i < map->pm_size; i++) {
    420 		pin = map->pm_map[i];
    421 		sc->sc_pins[pin].pin_mapped = 0;
    422 	}
    423 }
    424 
    425 int
    426 gpio_pin_read(void *gpio, struct gpio_pinmap *map, int pin)
    427 {
    428 	struct gpio_softc *sc = gpio;
    429 
    430 	return gpiobus_pin_read(sc->sc_gc, map->pm_map[pin]);
    431 }
    432 
    433 void
    434 gpio_pin_write(void *gpio, struct gpio_pinmap *map, int pin, int value)
    435 {
    436 	struct gpio_softc *sc = gpio;
    437 
    438 	gpiobus_pin_write(sc->sc_gc, map->pm_map[pin], value);
    439 	sc->sc_pins[map->pm_map[pin]].pin_state = value;
    440 }
    441 
    442 int
    443 gpio_pin_get_conf(void *gpio, struct gpio_pinmap *map, int pin)
    444 {
    445 	struct gpio_softc *sc = gpio;
    446 	int rv;
    447 
    448 	mutex_enter(&sc->sc_mtx);
    449 	rv = sc->sc_pins[map->pm_map[pin]].pin_flags;
    450 	mutex_exit(&sc->sc_mtx);
    451 
    452 	return (rv);
    453 }
    454 
    455 bool
    456 gpio_pin_set_conf(void *gpio, struct gpio_pinmap *map, int pin, int flags)
    457 {
    458 	struct gpio_softc *sc = gpio;
    459 	int checkflags = flags & GPIO_PIN_HWCAPS;
    460 
    461 	if ((sc->sc_pins[map->pm_map[pin]].pin_caps & checkflags) != checkflags)
    462 		return (false);
    463 
    464 	gpio_pin_ctl(gpio, map, pin, flags);
    465 
    466 	return (true);
    467 }
    468 
    469 void
    470 gpio_pin_ctl(void *gpio, struct gpio_pinmap *map, int pin, int flags)
    471 {
    472 	struct gpio_softc *sc = gpio;
    473 
    474 	/* loosey-goosey version of gpio_pin_set_conf(). */
    475 
    476 	mutex_enter(&sc->sc_mtx);
    477 	gpiobus_pin_ctl(sc->sc_gc, map->pm_map[pin], flags);
    478 	sc->sc_pins[map->pm_map[pin]].pin_flags = flags;
    479 	mutex_exit(&sc->sc_mtx);
    480 }
    481 
    482 int
    483 gpio_pin_caps(void *gpio, struct gpio_pinmap *map, int pin)
    484 {
    485 	struct gpio_softc *sc = gpio;
    486 
    487 	return sc->sc_pins[map->pm_map[pin]].pin_caps;
    488 }
    489 
    490 int
    491 gpio_pin_intrcaps(void *gpio, struct gpio_pinmap *map, int pin)
    492 {
    493 	struct gpio_softc *sc = gpio;
    494 
    495 	return sc->sc_pins[map->pm_map[pin]].pin_intrcaps;
    496 }
    497 
    498 static int
    499 gpio_irqmode_sanitize(int irqmode)
    500 {
    501 	int has_edge, has_level;
    502 
    503 	has_edge  = irqmode & GPIO_INTR_EDGE_MASK;
    504 	has_level = irqmode & GPIO_INTR_LEVEL_MASK;
    505 
    506 	/* Must specify an interrupt mode. */
    507 	if ((irqmode & GPIO_INTR_MODE_MASK) == 0)
    508 		return (0);
    509 
    510 	/* Can't specify edge and level together */
    511 	if (has_level && has_edge)
    512 		return (0);
    513 
    514 	/* "Be liberal in what you accept..." */
    515 	if (has_edge) {
    516 		if (irqmode & GPIO_INTR_DOUBLE_EDGE) {
    517 			/* if DOUBLE is set, just pass through DOUBLE */
    518 			irqmode = (irqmode & ~GPIO_INTR_EDGE_MASK) |
    519 			    GPIO_INTR_DOUBLE_EDGE;
    520 		} else if ((irqmode ^
    521 			    (GPIO_INTR_POS_EDGE | GPIO_INTR_NEG_EDGE)) == 0) {
    522 			/* both POS and NEG set; treat as DOUBLE */
    523 			irqmode = (irqmode & ~GPIO_INTR_EDGE_MASK) |
    524 			    GPIO_INTR_DOUBLE_EDGE;
    525 		}
    526 	} else {
    527 		/* Can't specify both levels together. */
    528 		if (has_level == GPIO_INTR_LEVEL_MASK)
    529 			return (0);
    530 	}
    531 
    532 	return (irqmode);
    533 }
    534 
    535 bool
    536 gpio_pin_irqmode_issupported(void *gpio, struct gpio_pinmap *map,
    537 			     int pin, int irqmode)
    538 {
    539 	struct gpio_softc *sc = gpio;
    540 	int match;
    541 
    542 	irqmode = gpio_irqmode_sanitize(irqmode) & GPIO_INTR_MODE_MASK;
    543 
    544 	/* Make sure the pin can do what is being asked. */
    545 	match = sc->sc_pins[map->pm_map[pin]].pin_intrcaps & irqmode;
    546 
    547 	return (irqmode && irqmode == match);
    548 }
    549 
    550 void *
    551 gpio_intr_establish(void *gpio, struct gpio_pinmap *map, int pin, int ipl,
    552 		    int irqmode, int (*func)(void *), void *arg)
    553 {
    554 	struct gpio_softc *sc = gpio;
    555 
    556 	if (sc->sc_gc->gp_intr_establish == NULL)
    557 		return (NULL);
    558 
    559 	irqmode = gpio_irqmode_sanitize(irqmode);
    560 	if (irqmode == 0)
    561 		return (NULL);
    562 
    563 	if (! gpio_pin_irqmode_issupported(gpio, map, pin, irqmode))
    564 		return (NULL);
    565 
    566 	/* XXX Right now, everything has to be at IPL_VM. */
    567 	if (ipl != IPL_VM)
    568 		return (NULL);
    569 
    570 	return ((*sc->sc_gc->gp_intr_establish)(sc->sc_gc->gp_cookie,
    571 	    sc->sc_pins[map->pm_map[pin]].pin_num, ipl, irqmode, func, arg));
    572 }
    573 
    574 void
    575 gpio_intr_disestablish(void *gpio, void *ih)
    576 {
    577 	struct gpio_softc *sc = gpio;
    578 
    579 	if (sc->sc_gc->gp_intr_disestablish != NULL && ih != NULL)
    580 		(*sc->sc_gc->gp_intr_disestablish)(sc->sc_gc->gp_cookie, ih);
    581 }
    582 
    583 bool
    584 gpio_intr_str(void *gpio, struct gpio_pinmap *map, int pin, int irqmode,
    585 	      char *intrstr, size_t intrstrlen)
    586 {
    587 	struct gpio_softc *sc = gpio;
    588 	const char *mode;
    589 	char hwstr[64];
    590 
    591 	if (sc->sc_gc->gp_intr_str == NULL)
    592 		return (false);
    593 
    594 	irqmode = gpio_irqmode_sanitize(irqmode);
    595 	if (irqmode == 0)
    596 		return (false);
    597 
    598 	if (irqmode & GPIO_INTR_DOUBLE_EDGE)
    599 		mode = "double edge";
    600 	else if (irqmode & GPIO_INTR_POS_EDGE)
    601 		mode = "positive edge";
    602 	else if (irqmode & GPIO_INTR_NEG_EDGE)
    603 		mode = "negative edge";
    604 	else if (irqmode & GPIO_INTR_HIGH_LEVEL)
    605 		mode = "high level";
    606 	else if (irqmode & GPIO_INTR_LOW_LEVEL)
    607 		mode = "low level";
    608 	else
    609 		return (false);
    610 
    611 	if (! (*sc->sc_gc->gp_intr_str)(sc->sc_gc->gp_cookie,
    612 					sc->sc_pins[map->pm_map[pin]].pin_num,
    613 					irqmode, hwstr, sizeof(hwstr)))
    614 		return (false);
    615 
    616 	(void) snprintf(intrstr, intrstrlen, "%s (%s)", hwstr, mode);
    617 
    618 	return (true);
    619 }
    620 
    621 int
    622 gpio_npins(uint32_t mask)
    623 {
    624 	int npins, i;
    625 
    626 	for (npins = 0, i = 0; i < 32; i++)
    627 		if (mask & (1 << i))
    628 			npins++;
    629 
    630 	return npins;
    631 }
    632 
    633 int
    634 gpio_lock(void *data)
    635 {
    636 	struct gpio_softc *sc;
    637 	int error;
    638 
    639 	error = 0;
    640 	sc = data;
    641 	mutex_enter(&sc->sc_mtx);
    642 	while (sc->sc_ioctl_busy) {
    643 		error = cv_wait_sig(&sc->sc_ioctl, &sc->sc_mtx);
    644 		if (error)
    645 			break;
    646 	}
    647 	if (!error)
    648 		sc->sc_ioctl_busy = 1;
    649 	mutex_exit(&sc->sc_mtx);
    650 	return error;
    651 }
    652 
    653 void
    654 gpio_unlock(void *data)
    655 {
    656 	struct gpio_softc *sc;
    657 
    658 	sc = data;
    659 	mutex_enter(&sc->sc_mtx);
    660 	sc->sc_ioctl_busy = 0;
    661 	cv_signal(&sc->sc_ioctl);
    662 	mutex_exit(&sc->sc_mtx);
    663 }
    664 
    665 int
    666 gpioopen(dev_t dev, int flag, int mode, struct lwp *l)
    667 {
    668 	struct gpio_softc *sc;
    669 
    670 	sc = device_lookup_private(&gpio_cd, minor(dev));
    671 	if (sc == NULL)
    672 		return ENXIO;
    673 
    674 	return gpiobus_open(sc->sc_gc, sc->sc_dev);
    675 }
    676 
    677 int
    678 gpioclose(dev_t dev, int flag, int mode, struct lwp *l)
    679 {
    680 	struct gpio_softc *sc;
    681 
    682 	sc = device_lookup_private(&gpio_cd, minor(dev));
    683 	return gpiobus_close(sc->sc_gc, sc->sc_dev);
    684 }
    685 
    686 static int
    687 gpio_pinbyname(struct gpio_softc *sc, char *gp_name)
    688 {
    689         struct gpio_name *nm;
    690 
    691         LIST_FOREACH(nm, &sc->sc_names, gp_next)
    692                 if (!strcmp(nm->gp_name, gp_name))
    693                         return nm->gp_pin;
    694         return -1;
    695 }
    696 
    697 int
    698 gpioioctl(dev_t dev, u_long cmd, void *data, int flag, struct lwp *l)
    699 {
    700 	int error;
    701 	struct gpio_softc *sc;
    702 
    703 	sc = device_lookup_private(&gpio_cd, minor(dev));
    704 
    705 	error = gpio_lock(sc);
    706 	if (error)
    707 		return error;
    708 
    709 	error = gpio_ioctl(sc, cmd, data, flag, l);
    710 	gpio_unlock(sc);
    711 	return error;
    712 }
    713 
    714 static int
    715 gpio_ioctl(struct gpio_softc *sc, u_long cmd, void *data, int flag,
    716     struct lwp *l)
    717 {
    718 	gpio_chipset_tag_t gc;
    719 	struct gpio_info *info;
    720 	struct gpio_attach *attach;
    721 	struct gpio_attach_args ga;
    722 	struct gpio_req *req;
    723 	struct gpio_name *nm;
    724 	struct gpio_set *set;
    725 #ifdef COMPAT_50
    726 	struct gpio_dev *gdev;
    727 #endif
    728 	device_t dv;
    729 	cfdata_t cf;
    730 	int locs[GPIOCF_NLOCS];
    731 	int error, pin, value, flags, npins;
    732 
    733 	gc = sc->sc_gc;
    734 	ga.ga_flags = 0;
    735 
    736 	if (cmd != GPIOINFO && !device_is_active(sc->sc_dev)) {
    737 		DPRINTF(("%s: device is not active\n",
    738 		    device_xname(sc->sc_dev)));
    739 		return EBUSY;
    740 	}
    741 
    742 	switch (cmd) {
    743 	case GPIOINFO:
    744 		info = data;
    745 		if (!kauth_authorize_device(l->l_cred,
    746 		    KAUTH_DEVICE_GPIO_PINSET, NULL, NULL, NULL, NULL))
    747 			info->gpio_npins = sc->sc_npins;
    748 		else {
    749 			for (pin = npins = 0; pin < sc->sc_npins; pin++)
    750 				if (sc->sc_pins[pin].pin_flags & GPIO_PIN_SET)
    751 					++npins;
    752 			info->gpio_npins = npins;
    753 		}
    754 		break;
    755 	case GPIOREAD:
    756 		req = data;
    757 
    758 		if (req->gp_name[0] != '\0')
    759 			req->gp_pin = gpio_pinbyname(sc, req->gp_name);
    760 		pin = req->gp_pin;
    761 
    762 		if (pin < 0 || pin >= sc->sc_npins)
    763 			return EINVAL;
    764 
    765 		if (!(sc->sc_pins[pin].pin_flags & GPIO_PIN_SET) &&
    766 		    kauth_authorize_device(l->l_cred,
    767 		    KAUTH_DEVICE_GPIO_PINSET, NULL, NULL, NULL, NULL))
    768 			return EPERM;
    769 
    770 		/* return read value */
    771 		req->gp_value = gpiobus_pin_read(gc, pin);
    772 		LIST_FOREACH(nm, &sc->sc_names, gp_next)
    773 			if (nm->gp_pin == pin) {
    774 				strlcpy(req->gp_name, nm->gp_name, GPIOMAXNAME);
    775 				break;
    776 			}
    777 		break;
    778 	case GPIOWRITE:
    779 		if ((flag & FWRITE) == 0)
    780 			return EBADF;
    781 
    782 		req = data;
    783 
    784 		if (req->gp_name[0] != '\0')
    785 			pin = gpio_pinbyname(sc, req->gp_name);
    786 		else
    787 			pin = req->gp_pin;
    788 
    789 		if (pin < 0 || pin >= sc->sc_npins)
    790 			return EINVAL;
    791 
    792 		if (sc->sc_pins[pin].pin_mapped)
    793 			return EBUSY;
    794 
    795 		if (!(sc->sc_pins[pin].pin_flags & GPIO_PIN_SET) &&
    796 		    kauth_authorize_device(l->l_cred,
    797 		    KAUTH_DEVICE_GPIO_PINSET, NULL, NULL, NULL, NULL))
    798 			return EPERM;
    799 
    800 		value = req->gp_value;
    801 		if (value != GPIO_PIN_LOW && value != GPIO_PIN_HIGH)
    802 			return EINVAL;
    803 
    804 		/* return old value */
    805 		req->gp_value = gpiobus_pin_read(gc, pin);
    806 		gpiobus_pin_write(gc, pin, value);
    807 		/* update current value */
    808 		sc->sc_pins[pin].pin_state = value;
    809 		break;
    810 	case GPIOTOGGLE:
    811 		if ((flag & FWRITE) == 0)
    812 			return EBADF;
    813 
    814 		req = data;
    815 
    816 		if (req->gp_name[0] != '\0')
    817 			pin = gpio_pinbyname(sc, req->gp_name);
    818 		else
    819 			pin = req->gp_pin;
    820 
    821 		if (pin < 0 || pin >= sc->sc_npins)
    822 			return EINVAL;
    823 
    824 		if (sc->sc_pins[pin].pin_mapped)
    825 			return EBUSY;
    826 
    827 		if (!(sc->sc_pins[pin].pin_flags & GPIO_PIN_SET) &&
    828 		    kauth_authorize_device(l->l_cred,
    829 		    KAUTH_DEVICE_GPIO_PINSET, NULL, NULL, NULL, NULL))
    830 			return EPERM;
    831 
    832 		value = (sc->sc_pins[pin].pin_state == GPIO_PIN_LOW ?
    833 		    GPIO_PIN_HIGH : GPIO_PIN_LOW);
    834 		gpiobus_pin_write(gc, pin, value);
    835 		/* return old value */
    836 		req->gp_value = sc->sc_pins[pin].pin_state;
    837 		/* update current value */
    838 		sc->sc_pins[pin].pin_state = value;
    839 		break;
    840 	case GPIOATTACH:
    841 		attach = data;
    842 		ga.ga_flags = attach->ga_flags;
    843 #ifdef COMPAT_50
    844 		/* FALLTHROUGH */
    845 	case GPIOATTACH50:
    846 		/*
    847 		 * The double assignment to 'attach' in case of GPIOATTACH
    848 		 * and COMPAT_50 is on purpose. It ensures backward
    849 		 * compatibility in case we are called through the old
    850 		 * GPIOATTACH50 ioctl(2), which had not the ga_flags field
    851 		 * in struct gpio_attach.
    852 		 */
    853 		attach = data;
    854 #endif
    855 		if (kauth_authorize_device(l->l_cred,
    856 		    KAUTH_DEVICE_GPIO_PINSET, NULL, NULL, NULL, NULL))
    857 			return EPERM;
    858 
    859 		/* do not try to attach if the pins are already mapped */
    860 		if (!gpio_pin_can_map(sc, attach->ga_offset, attach->ga_mask))
    861 			return EBUSY;
    862 
    863 		error = 0;
    864 		mutex_enter(&sc->sc_mtx);
    865 		while (sc->sc_attach_busy) {
    866 			error = cv_wait_sig(&sc->sc_attach, &sc->sc_mtx);
    867 			if (error)
    868 				break;
    869 		}
    870 		if (!error)
    871 			sc->sc_attach_busy = 1;
    872 		mutex_exit(&sc->sc_mtx);
    873 		if (error)
    874 			return EBUSY;
    875 
    876 		ga.ga_gpio = sc;
    877 		/* Don't access attach->ga_flags here. */
    878 		ga.ga_dvname = attach->ga_dvname;
    879 		ga.ga_offset = attach->ga_offset;
    880 		ga.ga_mask = attach->ga_mask;
    881 		DPRINTF(("%s: attach %s with offset %d, mask "
    882 		    "0x%02x, and flags 0x%02x\n", device_xname(sc->sc_dev),
    883 		    ga.ga_dvname, ga.ga_offset, ga.ga_mask, ga.ga_flags));
    884 
    885 		locs[GPIOCF_OFFSET] = ga.ga_offset;
    886 		locs[GPIOCF_MASK] = ga.ga_mask;
    887 		locs[GPIOCF_FLAG] = ga.ga_flags;
    888 
    889 		KERNEL_LOCK(1, NULL);
    890 		cf = config_search(sc->sc_dev, &ga,
    891 		    CFARGS(.locators = locs));
    892 		if (cf != NULL) {
    893 			dv = config_attach(sc->sc_dev, cf, &ga,
    894 			    gpiobus_print,
    895 			    CFARGS(.locators = locs));
    896 #ifdef COMPAT_50
    897 			if (dv != NULL) {
    898 				gdev = kmem_alloc(sizeof(struct gpio_dev),
    899 				    KM_SLEEP);
    900 				gdev->sc_dev = dv;
    901 				LIST_INSERT_HEAD(&sc->sc_devs, gdev, sc_next);
    902 			} else
    903 				error = EINVAL;
    904 #else
    905 			if (dv == NULL)
    906 				error = EINVAL;
    907 #endif
    908 		} else
    909 			error = EINVAL;
    910 		KERNEL_UNLOCK_ONE(NULL);
    911 
    912 		mutex_enter(&sc->sc_mtx);
    913 		sc->sc_attach_busy = 0;
    914 		cv_signal(&sc->sc_attach);
    915 		mutex_exit(&sc->sc_mtx);
    916 		return error;
    917 	case GPIOSET:
    918 		if (kauth_authorize_device(l->l_cred,
    919 		    KAUTH_DEVICE_GPIO_PINSET, NULL, NULL, NULL, NULL))
    920 			return EPERM;
    921 
    922 		set = data;
    923 
    924 		if (set->gp_name[0] != '\0')
    925 			pin = gpio_pinbyname(sc, set->gp_name);
    926 		else
    927 			pin = set->gp_pin;
    928 
    929 		if (pin < 0 || pin >= sc->sc_npins)
    930 			return EINVAL;
    931 		flags = set->gp_flags;
    932 
    933 		/* check that the controller supports all requested flags */
    934 		if ((flags & sc->sc_pins[pin].pin_caps) != flags)
    935 			return ENODEV;
    936 		flags = set->gp_flags;
    937 
    938 		set->gp_caps = sc->sc_pins[pin].pin_caps;
    939 		/* return old value */
    940 		set->gp_flags = sc->sc_pins[pin].pin_flags;
    941 
    942 		if (flags > 0) {
    943 			flags |= GPIO_PIN_SET;
    944 			gpiobus_pin_ctl(gc, pin, flags);
    945 			/* update current value */
    946 			sc->sc_pins[pin].pin_flags = flags;
    947 		}
    948 
    949 		/* rename pin or new pin? */
    950 		if (set->gp_name2[0] != '\0') {
    951 			struct gpio_name *gnm;
    952 
    953 			gnm = NULL;
    954 			LIST_FOREACH(nm, &sc->sc_names, gp_next) {
    955 				if (!strcmp(nm->gp_name, set->gp_name2) &&
    956 				    nm->gp_pin != pin)
    957 					return EINVAL;	/* duplicate name */
    958 				if (nm->gp_pin == pin)
    959 					gnm = nm;
    960 			}
    961 			if (gnm != NULL)
    962 				strlcpy(gnm->gp_name, set->gp_name2,
    963 				    sizeof(gnm->gp_name));
    964 			else  {
    965 				nm = kmem_alloc(sizeof(struct gpio_name),
    966 				    KM_SLEEP);
    967 				strlcpy(nm->gp_name, set->gp_name2,
    968 				    sizeof(nm->gp_name));
    969 				nm->gp_pin = set->gp_pin;
    970 				LIST_INSERT_HEAD(&sc->sc_names, nm, gp_next);
    971 			}
    972 		}
    973 		break;
    974 	case GPIOUNSET:
    975 		if (kauth_authorize_device(l->l_cred,
    976 		    KAUTH_DEVICE_GPIO_PINSET, NULL, NULL, NULL, NULL))
    977 			return EPERM;
    978 
    979 		set = data;
    980 		if (set->gp_name[0] != '\0')
    981 			pin = gpio_pinbyname(sc, set->gp_name);
    982 		else
    983 			pin = set->gp_pin;
    984 
    985 		if (pin < 0 || pin >= sc->sc_npins)
    986 			return EINVAL;
    987 		if (sc->sc_pins[pin].pin_mapped)
    988 			return EBUSY;
    989 		if (!(sc->sc_pins[pin].pin_flags & GPIO_PIN_SET))
    990 			return EINVAL;
    991 
    992 		LIST_FOREACH(nm, &sc->sc_names, gp_next) {
    993 			if (nm->gp_pin == pin) {
    994 				LIST_REMOVE(nm, gp_next);
    995 				kmem_free(nm, sizeof(struct gpio_name));
    996 				break;
    997 			}
    998 		}
    999 		sc->sc_pins[pin].pin_flags &= ~GPIO_PIN_SET;
   1000 		break;
   1001 	default:
   1002 #ifdef COMPAT_50
   1003 		/* Try the old API */
   1004 		DPRINTF(("%s: trying the old API\n", device_xname(sc->sc_dev)));
   1005 		return gpio_ioctl_oapi(sc, cmd, data, flag, l);
   1006 #else
   1007 		return ENOTTY;
   1008 #endif
   1009 	}
   1010 	return 0;
   1011 }
   1012 
   1013 #ifdef COMPAT_50
   1014 static int
   1015 gpio_ioctl_oapi(struct gpio_softc *sc, u_long cmd, void *data, int flag,
   1016     struct lwp *l)
   1017 {
   1018 	gpio_chipset_tag_t gc;
   1019 	struct gpio_pin_op *op;
   1020 	struct gpio_pin_ctl *ctl;
   1021 	struct gpio_attach *attach;
   1022 	struct gpio_dev *gdev;
   1023 
   1024 	int error, pin, value, flags;
   1025 
   1026 	gc = sc->sc_gc;
   1027 
   1028 	switch (cmd) {
   1029 	case GPIOPINREAD:
   1030 		op = data;
   1031 
   1032 		pin = op->gp_pin;
   1033 
   1034 		if (pin < 0 || pin >= sc->sc_npins)
   1035 			return EINVAL;
   1036 
   1037 		if (!(sc->sc_pins[pin].pin_flags & GPIO_PIN_SET) &&
   1038 		    kauth_authorize_device(l->l_cred,
   1039 		    KAUTH_DEVICE_GPIO_PINSET, NULL, NULL, NULL, NULL))
   1040 			return EPERM;
   1041 
   1042 		/* return read value */
   1043 		op->gp_value = gpiobus_pin_read(gc, pin);
   1044 		break;
   1045 	case GPIOPINWRITE:
   1046 		if ((flag & FWRITE) == 0)
   1047 			return EBADF;
   1048 
   1049 		op = data;
   1050 
   1051 		pin = op->gp_pin;
   1052 
   1053 		if (pin < 0 || pin >= sc->sc_npins)
   1054 			return EINVAL;
   1055 
   1056 		if (sc->sc_pins[pin].pin_mapped)
   1057 			return EBUSY;
   1058 
   1059 		if (!(sc->sc_pins[pin].pin_flags & GPIO_PIN_SET) &&
   1060 		    kauth_authorize_device(l->l_cred,
   1061 		    KAUTH_DEVICE_GPIO_PINSET, NULL, NULL, NULL, NULL))
   1062 			return EPERM;
   1063 
   1064 		value = op->gp_value;
   1065 		if (value != GPIO_PIN_LOW && value != GPIO_PIN_HIGH)
   1066 			return EINVAL;
   1067 
   1068 		gpiobus_pin_write(gc, pin, value);
   1069 		/* return old value */
   1070 		op->gp_value = sc->sc_pins[pin].pin_state;
   1071 		/* update current value */
   1072 		sc->sc_pins[pin].pin_state = value;
   1073 		break;
   1074 	case GPIOPINTOGGLE:
   1075 		if ((flag & FWRITE) == 0)
   1076 			return EBADF;
   1077 
   1078 		op = data;
   1079 
   1080 		pin = op->gp_pin;
   1081 
   1082 		if (pin < 0 || pin >= sc->sc_npins)
   1083 			return EINVAL;
   1084 
   1085 		if (sc->sc_pins[pin].pin_mapped)
   1086 			return EBUSY;
   1087 
   1088 		if (!(sc->sc_pins[pin].pin_flags & GPIO_PIN_SET) &&
   1089 		    kauth_authorize_device(l->l_cred,
   1090 		    KAUTH_DEVICE_GPIO_PINSET, NULL, NULL, NULL, NULL))
   1091 			return EPERM;
   1092 
   1093 		value = (sc->sc_pins[pin].pin_state == GPIO_PIN_LOW ?
   1094 		    GPIO_PIN_HIGH : GPIO_PIN_LOW);
   1095 		gpiobus_pin_write(gc, pin, value);
   1096 		/* return old value */
   1097 		op->gp_value = sc->sc_pins[pin].pin_state;
   1098 		/* update current value */
   1099 		sc->sc_pins[pin].pin_state = value;
   1100 		break;
   1101 	case GPIOPINCTL:
   1102 		ctl = data;
   1103 
   1104 		if (kauth_authorize_device(l->l_cred,
   1105 		    KAUTH_DEVICE_GPIO_PINSET, NULL, NULL, NULL, NULL))
   1106 			return EPERM;
   1107 
   1108 		pin = ctl->gp_pin;
   1109 
   1110 		if (pin < 0 || pin >= sc->sc_npins)
   1111 			return EINVAL;
   1112 		if (sc->sc_pins[pin].pin_mapped)
   1113 			return EBUSY;
   1114 		flags = ctl->gp_flags;
   1115 
   1116 		/* check that the controller supports all requested flags */
   1117 		if ((flags & sc->sc_pins[pin].pin_caps) != flags)
   1118 			return ENODEV;
   1119 
   1120 		ctl->gp_caps = sc->sc_pins[pin].pin_caps;
   1121 		/* return old value */
   1122 		ctl->gp_flags = sc->sc_pins[pin].pin_flags;
   1123 		if (flags > 0) {
   1124 			gpiobus_pin_ctl(gc, pin, flags);
   1125 			/* update current value */
   1126 			sc->sc_pins[pin].pin_flags = flags;
   1127 		}
   1128 		break;
   1129 	case GPIODETACH50:
   1130 		/* FALLTHOUGH */
   1131 	case GPIODETACH:
   1132 		if (kauth_authorize_device(l->l_cred,
   1133 		    KAUTH_DEVICE_GPIO_PINSET, NULL, NULL, NULL, NULL))
   1134 			return EPERM;
   1135 
   1136 		error = 0;
   1137 		mutex_enter(&sc->sc_mtx);
   1138 		while (sc->sc_attach_busy) {
   1139 			error = cv_wait_sig(&sc->sc_attach, &sc->sc_mtx);
   1140 			if (error)
   1141 				break;
   1142 		}
   1143 		if (!error)
   1144 			sc->sc_attach_busy = 1;
   1145 		mutex_exit(&sc->sc_mtx);
   1146 		if (error)
   1147 			return EBUSY;
   1148 
   1149 		KERNEL_LOCK(1, NULL);
   1150 		attach = data;
   1151 		LIST_FOREACH(gdev, &sc->sc_devs, sc_next) {
   1152 			if (strcmp(device_xname(gdev->sc_dev),
   1153 			    attach->ga_dvname) == 0) {
   1154 				mutex_enter(&sc->sc_mtx);
   1155 				sc->sc_attach_busy = 0;
   1156 				cv_signal(&sc->sc_attach);
   1157 				mutex_exit(&sc->sc_mtx);
   1158 
   1159 				if (config_detach(gdev->sc_dev, 0) == 0) {
   1160 					KERNEL_UNLOCK_ONE(NULL);
   1161 					return 0;
   1162 				}
   1163 				break;
   1164 			}
   1165 		}
   1166 		KERNEL_UNLOCK_ONE(NULL);
   1167 
   1168 		if (gdev == NULL) {
   1169 			mutex_enter(&sc->sc_mtx);
   1170 			sc->sc_attach_busy = 0;
   1171 			cv_signal(&sc->sc_attach);
   1172 			mutex_exit(&sc->sc_mtx);
   1173 		}
   1174 		return EINVAL;
   1175 
   1176 	default:
   1177 		return ENOTTY;
   1178 	}
   1179 	return 0;
   1180 }
   1181 #endif	/* COMPAT_50 */
   1182 
   1183 MODULE(MODULE_CLASS_DRIVER, gpio, NULL);
   1184 
   1185 #ifdef _MODULE
   1186 #include "ioconf.c"
   1187 #endif
   1188 
   1189 static int
   1190 gpio_modcmd(modcmd_t cmd, void *opaque)
   1191 {
   1192 #ifdef _MODULE
   1193 	devmajor_t cmajor = NODEVMAJOR, bmajor = NODEVMAJOR;
   1194 	int error;
   1195 #endif
   1196 	switch (cmd) {
   1197 	case MODULE_CMD_INIT:
   1198 #ifdef _MODULE
   1199 		error = devsw_attach(gpio_cd.cd_name, NULL, &bmajor,
   1200 		    &gpio_cdevsw, &cmajor);
   1201 		if (error) {
   1202 			aprint_error("%s: unable to register devsw\n",
   1203 			    gpio_cd.cd_name);
   1204 			return error;
   1205 		}
   1206 		error = config_init_component(cfdriver_ioconf_gpio,
   1207 		    cfattach_ioconf_gpio, cfdata_ioconf_gpio);
   1208 		if (error) {
   1209 			aprint_error("%s: unable to init component\n",
   1210 			    gpio_cd.cd_name);
   1211 			devsw_detach(NULL, &gpio_cdevsw);
   1212 			return error;
   1213 		}
   1214 #endif
   1215 		return 0;
   1216 	case MODULE_CMD_FINI:
   1217 #ifdef _MODULE
   1218 		config_fini_component(cfdriver_ioconf_gpio,
   1219 		    cfattach_ioconf_gpio, cfdata_ioconf_gpio);
   1220 		devsw_detach(NULL, &gpio_cdevsw);
   1221 #endif
   1222 		return 0;
   1223 	default:
   1224 		return ENOTTY;
   1225 	}
   1226 }
   1227