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