xref: /openbmc/linux/drivers/gpio/gpiolib.c (revision 384740dc)
1 #include <linux/kernel.h>
2 #include <linux/module.h>
3 #include <linux/irq.h>
4 #include <linux/spinlock.h>
5 #include <linux/device.h>
6 #include <linux/err.h>
7 #include <linux/debugfs.h>
8 #include <linux/seq_file.h>
9 #include <linux/gpio.h>
10 
11 
12 /* Optional implementation infrastructure for GPIO interfaces.
13  *
14  * Platforms may want to use this if they tend to use very many GPIOs
15  * that aren't part of a System-On-Chip core; or across I2C/SPI/etc.
16  *
17  * When kernel footprint or instruction count is an issue, simpler
18  * implementations may be preferred.  The GPIO programming interface
19  * allows for inlining speed-critical get/set operations for common
20  * cases, so that access to SOC-integrated GPIOs can sometimes cost
21  * only an instruction or two per bit.
22  */
23 
24 
25 /* When debugging, extend minimal trust to callers and platform code.
26  * Also emit diagnostic messages that may help initial bringup, when
27  * board setup or driver bugs are most common.
28  *
29  * Otherwise, minimize overhead in what may be bitbanging codepaths.
30  */
31 #ifdef	DEBUG
32 #define	extra_checks	1
33 #else
34 #define	extra_checks	0
35 #endif
36 
37 /* gpio_lock prevents conflicts during gpio_desc[] table updates.
38  * While any GPIO is requested, its gpio_chip is not removable;
39  * each GPIO's "requested" flag serves as a lock and refcount.
40  */
41 static DEFINE_SPINLOCK(gpio_lock);
42 
43 struct gpio_desc {
44 	struct gpio_chip	*chip;
45 	unsigned long		flags;
46 /* flag symbols are bit numbers */
47 #define FLAG_REQUESTED	0
48 #define FLAG_IS_OUT	1
49 #define FLAG_RESERVED	2
50 #define FLAG_EXPORT	3	/* protected by sysfs_lock */
51 #define FLAG_SYSFS	4	/* exported via /sys/class/gpio/control */
52 
53 #ifdef CONFIG_DEBUG_FS
54 	const char		*label;
55 #endif
56 };
57 static struct gpio_desc gpio_desc[ARCH_NR_GPIOS];
58 
59 static inline void desc_set_label(struct gpio_desc *d, const char *label)
60 {
61 #ifdef CONFIG_DEBUG_FS
62 	d->label = label;
63 #endif
64 }
65 
66 /* Warn when drivers omit gpio_request() calls -- legal but ill-advised
67  * when setting direction, and otherwise illegal.  Until board setup code
68  * and drivers use explicit requests everywhere (which won't happen when
69  * those calls have no teeth) we can't avoid autorequesting.  This nag
70  * message should motivate switching to explicit requests...
71  */
72 static void gpio_ensure_requested(struct gpio_desc *desc)
73 {
74 	if (test_and_set_bit(FLAG_REQUESTED, &desc->flags) == 0) {
75 		pr_warning("GPIO-%d autorequested\n", (int)(desc - gpio_desc));
76 		desc_set_label(desc, "[auto]");
77 		if (!try_module_get(desc->chip->owner))
78 			pr_err("GPIO-%d: module can't be gotten \n",
79 					(int)(desc - gpio_desc));
80 	}
81 }
82 
83 /* caller holds gpio_lock *OR* gpio is marked as requested */
84 static inline struct gpio_chip *gpio_to_chip(unsigned gpio)
85 {
86 	return gpio_desc[gpio].chip;
87 }
88 
89 /* dynamic allocation of GPIOs, e.g. on a hotplugged device */
90 static int gpiochip_find_base(int ngpio)
91 {
92 	int i;
93 	int spare = 0;
94 	int base = -ENOSPC;
95 
96 	for (i = ARCH_NR_GPIOS - 1; i >= 0 ; i--) {
97 		struct gpio_desc *desc = &gpio_desc[i];
98 		struct gpio_chip *chip = desc->chip;
99 
100 		if (!chip && !test_bit(FLAG_RESERVED, &desc->flags)) {
101 			spare++;
102 			if (spare == ngpio) {
103 				base = i;
104 				break;
105 			}
106 		} else {
107 			spare = 0;
108 			if (chip)
109 				i -= chip->ngpio - 1;
110 		}
111 	}
112 
113 	if (gpio_is_valid(base))
114 		pr_debug("%s: found new base at %d\n", __func__, base);
115 	return base;
116 }
117 
118 /**
119  * gpiochip_reserve() - reserve range of gpios to use with platform code only
120  * @start: starting gpio number
121  * @ngpio: number of gpios to reserve
122  * Context: platform init, potentially before irqs or kmalloc will work
123  *
124  * Returns a negative errno if any gpio within the range is already reserved
125  * or registered, else returns zero as a success code.  Use this function
126  * to mark a range of gpios as unavailable for dynamic gpio number allocation,
127  * for example because its driver support is not yet loaded.
128  */
129 int __init gpiochip_reserve(int start, int ngpio)
130 {
131 	int ret = 0;
132 	unsigned long flags;
133 	int i;
134 
135 	if (!gpio_is_valid(start) || !gpio_is_valid(start + ngpio - 1))
136 		return -EINVAL;
137 
138 	spin_lock_irqsave(&gpio_lock, flags);
139 
140 	for (i = start; i < start + ngpio; i++) {
141 		struct gpio_desc *desc = &gpio_desc[i];
142 
143 		if (desc->chip || test_bit(FLAG_RESERVED, &desc->flags)) {
144 			ret = -EBUSY;
145 			goto err;
146 		}
147 
148 		set_bit(FLAG_RESERVED, &desc->flags);
149 	}
150 
151 	pr_debug("%s: reserved gpios from %d to %d\n",
152 		 __func__, start, start + ngpio - 1);
153 err:
154 	spin_unlock_irqrestore(&gpio_lock, flags);
155 
156 	return ret;
157 }
158 
159 #ifdef CONFIG_GPIO_SYSFS
160 
161 /* lock protects against unexport_gpio() being called while
162  * sysfs files are active.
163  */
164 static DEFINE_MUTEX(sysfs_lock);
165 
166 /*
167  * /sys/class/gpio/gpioN... only for GPIOs that are exported
168  *   /direction
169  *      * MAY BE OMITTED if kernel won't allow direction changes
170  *      * is read/write as "in" or "out"
171  *      * may also be written as "high" or "low", initializing
172  *        output value as specified ("out" implies "low")
173  *   /value
174  *      * always readable, subject to hardware behavior
175  *      * may be writable, as zero/nonzero
176  *
177  * REVISIT there will likely be an attribute for configuring async
178  * notifications, e.g. to specify polling interval or IRQ trigger type
179  * that would for example trigger a poll() on the "value".
180  */
181 
182 static ssize_t gpio_direction_show(struct device *dev,
183 		struct device_attribute *attr, char *buf)
184 {
185 	const struct gpio_desc	*desc = dev_get_drvdata(dev);
186 	ssize_t			status;
187 
188 	mutex_lock(&sysfs_lock);
189 
190 	if (!test_bit(FLAG_EXPORT, &desc->flags))
191 		status = -EIO;
192 	else
193 		status = sprintf(buf, "%s\n",
194 			test_bit(FLAG_IS_OUT, &desc->flags)
195 				? "out" : "in");
196 
197 	mutex_unlock(&sysfs_lock);
198 	return status;
199 }
200 
201 static ssize_t gpio_direction_store(struct device *dev,
202 		struct device_attribute *attr, const char *buf, size_t size)
203 {
204 	const struct gpio_desc	*desc = dev_get_drvdata(dev);
205 	unsigned		gpio = desc - gpio_desc;
206 	ssize_t			status;
207 
208 	mutex_lock(&sysfs_lock);
209 
210 	if (!test_bit(FLAG_EXPORT, &desc->flags))
211 		status = -EIO;
212 	else if (sysfs_streq(buf, "high"))
213 		status = gpio_direction_output(gpio, 1);
214 	else if (sysfs_streq(buf, "out") || sysfs_streq(buf, "low"))
215 		status = gpio_direction_output(gpio, 0);
216 	else if (sysfs_streq(buf, "in"))
217 		status = gpio_direction_input(gpio);
218 	else
219 		status = -EINVAL;
220 
221 	mutex_unlock(&sysfs_lock);
222 	return status ? : size;
223 }
224 
225 static const DEVICE_ATTR(direction, 0644,
226 		gpio_direction_show, gpio_direction_store);
227 
228 static ssize_t gpio_value_show(struct device *dev,
229 		struct device_attribute *attr, char *buf)
230 {
231 	const struct gpio_desc	*desc = dev_get_drvdata(dev);
232 	unsigned		gpio = desc - gpio_desc;
233 	ssize_t			status;
234 
235 	mutex_lock(&sysfs_lock);
236 
237 	if (!test_bit(FLAG_EXPORT, &desc->flags))
238 		status = -EIO;
239 	else
240 		status = sprintf(buf, "%d\n", gpio_get_value_cansleep(gpio));
241 
242 	mutex_unlock(&sysfs_lock);
243 	return status;
244 }
245 
246 static ssize_t gpio_value_store(struct device *dev,
247 		struct device_attribute *attr, const char *buf, size_t size)
248 {
249 	const struct gpio_desc	*desc = dev_get_drvdata(dev);
250 	unsigned		gpio = desc - gpio_desc;
251 	ssize_t			status;
252 
253 	mutex_lock(&sysfs_lock);
254 
255 	if (!test_bit(FLAG_EXPORT, &desc->flags))
256 		status = -EIO;
257 	else if (!test_bit(FLAG_IS_OUT, &desc->flags))
258 		status = -EPERM;
259 	else {
260 		long		value;
261 
262 		status = strict_strtol(buf, 0, &value);
263 		if (status == 0) {
264 			gpio_set_value_cansleep(gpio, value != 0);
265 			status = size;
266 		}
267 	}
268 
269 	mutex_unlock(&sysfs_lock);
270 	return status;
271 }
272 
273 static /*const*/ DEVICE_ATTR(value, 0644,
274 		gpio_value_show, gpio_value_store);
275 
276 static const struct attribute *gpio_attrs[] = {
277 	&dev_attr_direction.attr,
278 	&dev_attr_value.attr,
279 	NULL,
280 };
281 
282 static const struct attribute_group gpio_attr_group = {
283 	.attrs = (struct attribute **) gpio_attrs,
284 };
285 
286 /*
287  * /sys/class/gpio/gpiochipN/
288  *   /base ... matching gpio_chip.base (N)
289  *   /label ... matching gpio_chip.label
290  *   /ngpio ... matching gpio_chip.ngpio
291  */
292 
293 static ssize_t chip_base_show(struct device *dev,
294 			       struct device_attribute *attr, char *buf)
295 {
296 	const struct gpio_chip	*chip = dev_get_drvdata(dev);
297 
298 	return sprintf(buf, "%d\n", chip->base);
299 }
300 static DEVICE_ATTR(base, 0444, chip_base_show, NULL);
301 
302 static ssize_t chip_label_show(struct device *dev,
303 			       struct device_attribute *attr, char *buf)
304 {
305 	const struct gpio_chip	*chip = dev_get_drvdata(dev);
306 
307 	return sprintf(buf, "%s\n", chip->label ? : "");
308 }
309 static DEVICE_ATTR(label, 0444, chip_label_show, NULL);
310 
311 static ssize_t chip_ngpio_show(struct device *dev,
312 			       struct device_attribute *attr, char *buf)
313 {
314 	const struct gpio_chip	*chip = dev_get_drvdata(dev);
315 
316 	return sprintf(buf, "%u\n", chip->ngpio);
317 }
318 static DEVICE_ATTR(ngpio, 0444, chip_ngpio_show, NULL);
319 
320 static const struct attribute *gpiochip_attrs[] = {
321 	&dev_attr_base.attr,
322 	&dev_attr_label.attr,
323 	&dev_attr_ngpio.attr,
324 	NULL,
325 };
326 
327 static const struct attribute_group gpiochip_attr_group = {
328 	.attrs = (struct attribute **) gpiochip_attrs,
329 };
330 
331 /*
332  * /sys/class/gpio/export ... write-only
333  *	integer N ... number of GPIO to export (full access)
334  * /sys/class/gpio/unexport ... write-only
335  *	integer N ... number of GPIO to unexport
336  */
337 static ssize_t export_store(struct class *class, const char *buf, size_t len)
338 {
339 	long	gpio;
340 	int	status;
341 
342 	status = strict_strtol(buf, 0, &gpio);
343 	if (status < 0)
344 		goto done;
345 
346 	/* No extra locking here; FLAG_SYSFS just signifies that the
347 	 * request and export were done by on behalf of userspace, so
348 	 * they may be undone on its behalf too.
349 	 */
350 
351 	status = gpio_request(gpio, "sysfs");
352 	if (status < 0)
353 		goto done;
354 
355 	status = gpio_export(gpio, true);
356 	if (status < 0)
357 		gpio_free(gpio);
358 	else
359 		set_bit(FLAG_SYSFS, &gpio_desc[gpio].flags);
360 
361 done:
362 	if (status)
363 		pr_debug("%s: status %d\n", __func__, status);
364 	return status ? : len;
365 }
366 
367 static ssize_t unexport_store(struct class *class, const char *buf, size_t len)
368 {
369 	long	gpio;
370 	int	status;
371 
372 	status = strict_strtol(buf, 0, &gpio);
373 	if (status < 0)
374 		goto done;
375 
376 	status = -EINVAL;
377 
378 	/* reject bogus commands (gpio_unexport ignores them) */
379 	if (!gpio_is_valid(gpio))
380 		goto done;
381 
382 	/* No extra locking here; FLAG_SYSFS just signifies that the
383 	 * request and export were done by on behalf of userspace, so
384 	 * they may be undone on its behalf too.
385 	 */
386 	if (test_and_clear_bit(FLAG_SYSFS, &gpio_desc[gpio].flags)) {
387 		status = 0;
388 		gpio_free(gpio);
389 	}
390 done:
391 	if (status)
392 		pr_debug("%s: status %d\n", __func__, status);
393 	return status ? : len;
394 }
395 
396 static struct class_attribute gpio_class_attrs[] = {
397 	__ATTR(export, 0200, NULL, export_store),
398 	__ATTR(unexport, 0200, NULL, unexport_store),
399 	__ATTR_NULL,
400 };
401 
402 static struct class gpio_class = {
403 	.name =		"gpio",
404 	.owner =	THIS_MODULE,
405 
406 	.class_attrs =	gpio_class_attrs,
407 };
408 
409 
410 /**
411  * gpio_export - export a GPIO through sysfs
412  * @gpio: gpio to make available, already requested
413  * @direction_may_change: true if userspace may change gpio direction
414  * Context: arch_initcall or later
415  *
416  * When drivers want to make a GPIO accessible to userspace after they
417  * have requested it -- perhaps while debugging, or as part of their
418  * public interface -- they may use this routine.  If the GPIO can
419  * change direction (some can't) and the caller allows it, userspace
420  * will see "direction" sysfs attribute which may be used to change
421  * the gpio's direction.  A "value" attribute will always be provided.
422  *
423  * Returns zero on success, else an error.
424  */
425 int gpio_export(unsigned gpio, bool direction_may_change)
426 {
427 	unsigned long		flags;
428 	struct gpio_desc	*desc;
429 	int			status = -EINVAL;
430 
431 	/* can't export until sysfs is available ... */
432 	if (!gpio_class.p) {
433 		pr_debug("%s: called too early!\n", __func__);
434 		return -ENOENT;
435 	}
436 
437 	if (!gpio_is_valid(gpio))
438 		goto done;
439 
440 	mutex_lock(&sysfs_lock);
441 
442 	spin_lock_irqsave(&gpio_lock, flags);
443 	desc = &gpio_desc[gpio];
444 	if (test_bit(FLAG_REQUESTED, &desc->flags)
445 			&& !test_bit(FLAG_EXPORT, &desc->flags)) {
446 		status = 0;
447 		if (!desc->chip->direction_input
448 				|| !desc->chip->direction_output)
449 			direction_may_change = false;
450 	}
451 	spin_unlock_irqrestore(&gpio_lock, flags);
452 
453 	if (status == 0) {
454 		struct device	*dev;
455 
456 		dev = device_create(&gpio_class, desc->chip->dev, MKDEV(0, 0),
457 					desc, "gpio%d", gpio);
458 		if (dev) {
459 			if (direction_may_change)
460 				status = sysfs_create_group(&dev->kobj,
461 						&gpio_attr_group);
462 			else
463 				status = device_create_file(dev,
464 						&dev_attr_value);
465 			if (status != 0)
466 				device_unregister(dev);
467 		} else
468 			status = -ENODEV;
469 		if (status == 0)
470 			set_bit(FLAG_EXPORT, &desc->flags);
471 	}
472 
473 	mutex_unlock(&sysfs_lock);
474 
475 done:
476 	if (status)
477 		pr_debug("%s: gpio%d status %d\n", __func__, gpio, status);
478 
479 	return status;
480 }
481 EXPORT_SYMBOL_GPL(gpio_export);
482 
483 static int match_export(struct device *dev, void *data)
484 {
485 	return dev_get_drvdata(dev) == data;
486 }
487 
488 /**
489  * gpio_unexport - reverse effect of gpio_export()
490  * @gpio: gpio to make unavailable
491  *
492  * This is implicit on gpio_free().
493  */
494 void gpio_unexport(unsigned gpio)
495 {
496 	struct gpio_desc	*desc;
497 	int			status = -EINVAL;
498 
499 	if (!gpio_is_valid(gpio))
500 		goto done;
501 
502 	mutex_lock(&sysfs_lock);
503 
504 	desc = &gpio_desc[gpio];
505 	if (test_bit(FLAG_EXPORT, &desc->flags)) {
506 		struct device	*dev = NULL;
507 
508 		dev = class_find_device(&gpio_class, NULL, desc, match_export);
509 		if (dev) {
510 			clear_bit(FLAG_EXPORT, &desc->flags);
511 			put_device(dev);
512 			device_unregister(dev);
513 			status = 0;
514 		} else
515 			status = -ENODEV;
516 	}
517 
518 	mutex_unlock(&sysfs_lock);
519 done:
520 	if (status)
521 		pr_debug("%s: gpio%d status %d\n", __func__, gpio, status);
522 }
523 EXPORT_SYMBOL_GPL(gpio_unexport);
524 
525 static int gpiochip_export(struct gpio_chip *chip)
526 {
527 	int		status;
528 	struct device	*dev;
529 
530 	/* Many systems register gpio chips for SOC support very early,
531 	 * before driver model support is available.  In those cases we
532 	 * export this later, in gpiolib_sysfs_init() ... here we just
533 	 * verify that _some_ field of gpio_class got initialized.
534 	 */
535 	if (!gpio_class.p)
536 		return 0;
537 
538 	/* use chip->base for the ID; it's already known to be unique */
539 	mutex_lock(&sysfs_lock);
540 	dev = device_create(&gpio_class, chip->dev, MKDEV(0, 0), chip,
541 				"gpiochip%d", chip->base);
542 	if (dev) {
543 		status = sysfs_create_group(&dev->kobj,
544 				&gpiochip_attr_group);
545 	} else
546 		status = -ENODEV;
547 	chip->exported = (status == 0);
548 	mutex_unlock(&sysfs_lock);
549 
550 	if (status) {
551 		unsigned long	flags;
552 		unsigned	gpio;
553 
554 		spin_lock_irqsave(&gpio_lock, flags);
555 		gpio = chip->base;
556 		while (gpio_desc[gpio].chip == chip)
557 			gpio_desc[gpio++].chip = NULL;
558 		spin_unlock_irqrestore(&gpio_lock, flags);
559 
560 		pr_debug("%s: chip %s status %d\n", __func__,
561 				chip->label, status);
562 	}
563 
564 	return status;
565 }
566 
567 static void gpiochip_unexport(struct gpio_chip *chip)
568 {
569 	int			status;
570 	struct device		*dev;
571 
572 	mutex_lock(&sysfs_lock);
573 	dev = class_find_device(&gpio_class, NULL, chip, match_export);
574 	if (dev) {
575 		put_device(dev);
576 		device_unregister(dev);
577 		chip->exported = 0;
578 		status = 0;
579 	} else
580 		status = -ENODEV;
581 	mutex_unlock(&sysfs_lock);
582 
583 	if (status)
584 		pr_debug("%s: chip %s status %d\n", __func__,
585 				chip->label, status);
586 }
587 
588 static int __init gpiolib_sysfs_init(void)
589 {
590 	int		status;
591 	unsigned long	flags;
592 	unsigned	gpio;
593 
594 	status = class_register(&gpio_class);
595 	if (status < 0)
596 		return status;
597 
598 	/* Scan and register the gpio_chips which registered very
599 	 * early (e.g. before the class_register above was called).
600 	 *
601 	 * We run before arch_initcall() so chip->dev nodes can have
602 	 * registered, and so arch_initcall() can always gpio_export().
603 	 */
604 	spin_lock_irqsave(&gpio_lock, flags);
605 	for (gpio = 0; gpio < ARCH_NR_GPIOS; gpio++) {
606 		struct gpio_chip	*chip;
607 
608 		chip = gpio_desc[gpio].chip;
609 		if (!chip || chip->exported)
610 			continue;
611 
612 		spin_unlock_irqrestore(&gpio_lock, flags);
613 		status = gpiochip_export(chip);
614 		spin_lock_irqsave(&gpio_lock, flags);
615 	}
616 	spin_unlock_irqrestore(&gpio_lock, flags);
617 
618 
619 	return status;
620 }
621 postcore_initcall(gpiolib_sysfs_init);
622 
623 #else
624 static inline int gpiochip_export(struct gpio_chip *chip)
625 {
626 	return 0;
627 }
628 
629 static inline void gpiochip_unexport(struct gpio_chip *chip)
630 {
631 }
632 
633 #endif /* CONFIG_GPIO_SYSFS */
634 
635 /**
636  * gpiochip_add() - register a gpio_chip
637  * @chip: the chip to register, with chip->base initialized
638  * Context: potentially before irqs or kmalloc will work
639  *
640  * Returns a negative errno if the chip can't be registered, such as
641  * because the chip->base is invalid or already associated with a
642  * different chip.  Otherwise it returns zero as a success code.
643  *
644  * When gpiochip_add() is called very early during boot, so that GPIOs
645  * can be freely used, the chip->dev device must be registered before
646  * the gpio framework's arch_initcall().  Otherwise sysfs initialization
647  * for GPIOs will fail rudely.
648  *
649  * If chip->base is negative, this requests dynamic assignment of
650  * a range of valid GPIOs.
651  */
652 int gpiochip_add(struct gpio_chip *chip)
653 {
654 	unsigned long	flags;
655 	int		status = 0;
656 	unsigned	id;
657 	int		base = chip->base;
658 
659 	if ((!gpio_is_valid(base) || !gpio_is_valid(base + chip->ngpio - 1))
660 			&& base >= 0) {
661 		status = -EINVAL;
662 		goto fail;
663 	}
664 
665 	spin_lock_irqsave(&gpio_lock, flags);
666 
667 	if (base < 0) {
668 		base = gpiochip_find_base(chip->ngpio);
669 		if (base < 0) {
670 			status = base;
671 			goto unlock;
672 		}
673 		chip->base = base;
674 	}
675 
676 	/* these GPIO numbers must not be managed by another gpio_chip */
677 	for (id = base; id < base + chip->ngpio; id++) {
678 		if (gpio_desc[id].chip != NULL) {
679 			status = -EBUSY;
680 			break;
681 		}
682 	}
683 	if (status == 0) {
684 		for (id = base; id < base + chip->ngpio; id++) {
685 			gpio_desc[id].chip = chip;
686 
687 			/* REVISIT:  most hardware initializes GPIOs as
688 			 * inputs (often with pullups enabled) so power
689 			 * usage is minimized.  Linux code should set the
690 			 * gpio direction first thing; but until it does,
691 			 * we may expose the wrong direction in sysfs.
692 			 */
693 			gpio_desc[id].flags = !chip->direction_input
694 				? (1 << FLAG_IS_OUT)
695 				: 0;
696 		}
697 	}
698 
699 unlock:
700 	spin_unlock_irqrestore(&gpio_lock, flags);
701 	if (status == 0)
702 		status = gpiochip_export(chip);
703 fail:
704 	/* failures here can mean systems won't boot... */
705 	if (status)
706 		pr_err("gpiochip_add: gpios %d..%d (%s) not registered\n",
707 			chip->base, chip->base + chip->ngpio - 1,
708 			chip->label ? : "generic");
709 	return status;
710 }
711 EXPORT_SYMBOL_GPL(gpiochip_add);
712 
713 /**
714  * gpiochip_remove() - unregister a gpio_chip
715  * @chip: the chip to unregister
716  *
717  * A gpio_chip with any GPIOs still requested may not be removed.
718  */
719 int gpiochip_remove(struct gpio_chip *chip)
720 {
721 	unsigned long	flags;
722 	int		status = 0;
723 	unsigned	id;
724 
725 	spin_lock_irqsave(&gpio_lock, flags);
726 
727 	for (id = chip->base; id < chip->base + chip->ngpio; id++) {
728 		if (test_bit(FLAG_REQUESTED, &gpio_desc[id].flags)) {
729 			status = -EBUSY;
730 			break;
731 		}
732 	}
733 	if (status == 0) {
734 		for (id = chip->base; id < chip->base + chip->ngpio; id++)
735 			gpio_desc[id].chip = NULL;
736 	}
737 
738 	spin_unlock_irqrestore(&gpio_lock, flags);
739 
740 	if (status == 0)
741 		gpiochip_unexport(chip);
742 
743 	return status;
744 }
745 EXPORT_SYMBOL_GPL(gpiochip_remove);
746 
747 
748 /* These "optional" allocation calls help prevent drivers from stomping
749  * on each other, and help provide better diagnostics in debugfs.
750  * They're called even less than the "set direction" calls.
751  */
752 int gpio_request(unsigned gpio, const char *label)
753 {
754 	struct gpio_desc	*desc;
755 	int			status = -EINVAL;
756 	unsigned long		flags;
757 
758 	spin_lock_irqsave(&gpio_lock, flags);
759 
760 	if (!gpio_is_valid(gpio))
761 		goto done;
762 	desc = &gpio_desc[gpio];
763 	if (desc->chip == NULL)
764 		goto done;
765 
766 	if (!try_module_get(desc->chip->owner))
767 		goto done;
768 
769 	/* NOTE:  gpio_request() can be called in early boot,
770 	 * before IRQs are enabled.
771 	 */
772 
773 	if (test_and_set_bit(FLAG_REQUESTED, &desc->flags) == 0) {
774 		desc_set_label(desc, label ? : "?");
775 		status = 0;
776 	} else {
777 		status = -EBUSY;
778 		module_put(desc->chip->owner);
779 	}
780 
781 done:
782 	if (status)
783 		pr_debug("gpio_request: gpio-%d (%s) status %d\n",
784 			gpio, label ? : "?", status);
785 	spin_unlock_irqrestore(&gpio_lock, flags);
786 	return status;
787 }
788 EXPORT_SYMBOL_GPL(gpio_request);
789 
790 void gpio_free(unsigned gpio)
791 {
792 	unsigned long		flags;
793 	struct gpio_desc	*desc;
794 
795 	if (!gpio_is_valid(gpio)) {
796 		WARN_ON(extra_checks);
797 		return;
798 	}
799 
800 	gpio_unexport(gpio);
801 
802 	spin_lock_irqsave(&gpio_lock, flags);
803 
804 	desc = &gpio_desc[gpio];
805 	if (desc->chip && test_and_clear_bit(FLAG_REQUESTED, &desc->flags)) {
806 		desc_set_label(desc, NULL);
807 		module_put(desc->chip->owner);
808 	} else
809 		WARN_ON(extra_checks);
810 
811 	spin_unlock_irqrestore(&gpio_lock, flags);
812 }
813 EXPORT_SYMBOL_GPL(gpio_free);
814 
815 
816 /**
817  * gpiochip_is_requested - return string iff signal was requested
818  * @chip: controller managing the signal
819  * @offset: of signal within controller's 0..(ngpio - 1) range
820  *
821  * Returns NULL if the GPIO is not currently requested, else a string.
822  * If debugfs support is enabled, the string returned is the label passed
823  * to gpio_request(); otherwise it is a meaningless constant.
824  *
825  * This function is for use by GPIO controller drivers.  The label can
826  * help with diagnostics, and knowing that the signal is used as a GPIO
827  * can help avoid accidentally multiplexing it to another controller.
828  */
829 const char *gpiochip_is_requested(struct gpio_chip *chip, unsigned offset)
830 {
831 	unsigned gpio = chip->base + offset;
832 
833 	if (!gpio_is_valid(gpio) || gpio_desc[gpio].chip != chip)
834 		return NULL;
835 	if (test_bit(FLAG_REQUESTED, &gpio_desc[gpio].flags) == 0)
836 		return NULL;
837 #ifdef CONFIG_DEBUG_FS
838 	return gpio_desc[gpio].label;
839 #else
840 	return "?";
841 #endif
842 }
843 EXPORT_SYMBOL_GPL(gpiochip_is_requested);
844 
845 
846 /* Drivers MUST set GPIO direction before making get/set calls.  In
847  * some cases this is done in early boot, before IRQs are enabled.
848  *
849  * As a rule these aren't called more than once (except for drivers
850  * using the open-drain emulation idiom) so these are natural places
851  * to accumulate extra debugging checks.  Note that we can't (yet)
852  * rely on gpio_request() having been called beforehand.
853  */
854 
855 int gpio_direction_input(unsigned gpio)
856 {
857 	unsigned long		flags;
858 	struct gpio_chip	*chip;
859 	struct gpio_desc	*desc = &gpio_desc[gpio];
860 	int			status = -EINVAL;
861 
862 	spin_lock_irqsave(&gpio_lock, flags);
863 
864 	if (!gpio_is_valid(gpio))
865 		goto fail;
866 	chip = desc->chip;
867 	if (!chip || !chip->get || !chip->direction_input)
868 		goto fail;
869 	gpio -= chip->base;
870 	if (gpio >= chip->ngpio)
871 		goto fail;
872 	gpio_ensure_requested(desc);
873 
874 	/* now we know the gpio is valid and chip won't vanish */
875 
876 	spin_unlock_irqrestore(&gpio_lock, flags);
877 
878 	might_sleep_if(extra_checks && chip->can_sleep);
879 
880 	status = chip->direction_input(chip, gpio);
881 	if (status == 0)
882 		clear_bit(FLAG_IS_OUT, &desc->flags);
883 	return status;
884 fail:
885 	spin_unlock_irqrestore(&gpio_lock, flags);
886 	if (status)
887 		pr_debug("%s: gpio-%d status %d\n",
888 			__func__, gpio, status);
889 	return status;
890 }
891 EXPORT_SYMBOL_GPL(gpio_direction_input);
892 
893 int gpio_direction_output(unsigned gpio, int value)
894 {
895 	unsigned long		flags;
896 	struct gpio_chip	*chip;
897 	struct gpio_desc	*desc = &gpio_desc[gpio];
898 	int			status = -EINVAL;
899 
900 	spin_lock_irqsave(&gpio_lock, flags);
901 
902 	if (!gpio_is_valid(gpio))
903 		goto fail;
904 	chip = desc->chip;
905 	if (!chip || !chip->set || !chip->direction_output)
906 		goto fail;
907 	gpio -= chip->base;
908 	if (gpio >= chip->ngpio)
909 		goto fail;
910 	gpio_ensure_requested(desc);
911 
912 	/* now we know the gpio is valid and chip won't vanish */
913 
914 	spin_unlock_irqrestore(&gpio_lock, flags);
915 
916 	might_sleep_if(extra_checks && chip->can_sleep);
917 
918 	status = chip->direction_output(chip, gpio, value);
919 	if (status == 0)
920 		set_bit(FLAG_IS_OUT, &desc->flags);
921 	return status;
922 fail:
923 	spin_unlock_irqrestore(&gpio_lock, flags);
924 	if (status)
925 		pr_debug("%s: gpio-%d status %d\n",
926 			__func__, gpio, status);
927 	return status;
928 }
929 EXPORT_SYMBOL_GPL(gpio_direction_output);
930 
931 
932 /* I/O calls are only valid after configuration completed; the relevant
933  * "is this a valid GPIO" error checks should already have been done.
934  *
935  * "Get" operations are often inlinable as reading a pin value register,
936  * and masking the relevant bit in that register.
937  *
938  * When "set" operations are inlinable, they involve writing that mask to
939  * one register to set a low value, or a different register to set it high.
940  * Otherwise locking is needed, so there may be little value to inlining.
941  *
942  *------------------------------------------------------------------------
943  *
944  * IMPORTANT!!!  The hot paths -- get/set value -- assume that callers
945  * have requested the GPIO.  That can include implicit requesting by
946  * a direction setting call.  Marking a gpio as requested locks its chip
947  * in memory, guaranteeing that these table lookups need no more locking
948  * and that gpiochip_remove() will fail.
949  *
950  * REVISIT when debugging, consider adding some instrumentation to ensure
951  * that the GPIO was actually requested.
952  */
953 
954 /**
955  * __gpio_get_value() - return a gpio's value
956  * @gpio: gpio whose value will be returned
957  * Context: any
958  *
959  * This is used directly or indirectly to implement gpio_get_value().
960  * It returns the zero or nonzero value provided by the associated
961  * gpio_chip.get() method; or zero if no such method is provided.
962  */
963 int __gpio_get_value(unsigned gpio)
964 {
965 	struct gpio_chip	*chip;
966 
967 	chip = gpio_to_chip(gpio);
968 	WARN_ON(extra_checks && chip->can_sleep);
969 	return chip->get ? chip->get(chip, gpio - chip->base) : 0;
970 }
971 EXPORT_SYMBOL_GPL(__gpio_get_value);
972 
973 /**
974  * __gpio_set_value() - assign a gpio's value
975  * @gpio: gpio whose value will be assigned
976  * @value: value to assign
977  * Context: any
978  *
979  * This is used directly or indirectly to implement gpio_set_value().
980  * It invokes the associated gpio_chip.set() method.
981  */
982 void __gpio_set_value(unsigned gpio, int value)
983 {
984 	struct gpio_chip	*chip;
985 
986 	chip = gpio_to_chip(gpio);
987 	WARN_ON(extra_checks && chip->can_sleep);
988 	chip->set(chip, gpio - chip->base, value);
989 }
990 EXPORT_SYMBOL_GPL(__gpio_set_value);
991 
992 /**
993  * __gpio_cansleep() - report whether gpio value access will sleep
994  * @gpio: gpio in question
995  * Context: any
996  *
997  * This is used directly or indirectly to implement gpio_cansleep().  It
998  * returns nonzero if access reading or writing the GPIO value can sleep.
999  */
1000 int __gpio_cansleep(unsigned gpio)
1001 {
1002 	struct gpio_chip	*chip;
1003 
1004 	/* only call this on GPIOs that are valid! */
1005 	chip = gpio_to_chip(gpio);
1006 
1007 	return chip->can_sleep;
1008 }
1009 EXPORT_SYMBOL_GPL(__gpio_cansleep);
1010 
1011 
1012 
1013 /* There's no value in making it easy to inline GPIO calls that may sleep.
1014  * Common examples include ones connected to I2C or SPI chips.
1015  */
1016 
1017 int gpio_get_value_cansleep(unsigned gpio)
1018 {
1019 	struct gpio_chip	*chip;
1020 
1021 	might_sleep_if(extra_checks);
1022 	chip = gpio_to_chip(gpio);
1023 	return chip->get(chip, gpio - chip->base);
1024 }
1025 EXPORT_SYMBOL_GPL(gpio_get_value_cansleep);
1026 
1027 void gpio_set_value_cansleep(unsigned gpio, int value)
1028 {
1029 	struct gpio_chip	*chip;
1030 
1031 	might_sleep_if(extra_checks);
1032 	chip = gpio_to_chip(gpio);
1033 	chip->set(chip, gpio - chip->base, value);
1034 }
1035 EXPORT_SYMBOL_GPL(gpio_set_value_cansleep);
1036 
1037 
1038 #ifdef CONFIG_DEBUG_FS
1039 
1040 static void gpiolib_dbg_show(struct seq_file *s, struct gpio_chip *chip)
1041 {
1042 	unsigned		i;
1043 	unsigned		gpio = chip->base;
1044 	struct gpio_desc	*gdesc = &gpio_desc[gpio];
1045 	int			is_out;
1046 
1047 	for (i = 0; i < chip->ngpio; i++, gpio++, gdesc++) {
1048 		if (!test_bit(FLAG_REQUESTED, &gdesc->flags))
1049 			continue;
1050 
1051 		is_out = test_bit(FLAG_IS_OUT, &gdesc->flags);
1052 		seq_printf(s, " gpio-%-3d (%-12s) %s %s",
1053 			gpio, gdesc->label,
1054 			is_out ? "out" : "in ",
1055 			chip->get
1056 				? (chip->get(chip, i) ? "hi" : "lo")
1057 				: "?  ");
1058 
1059 		if (!is_out) {
1060 			int		irq = gpio_to_irq(gpio);
1061 			struct irq_desc	*desc = irq_desc + irq;
1062 
1063 			/* This races with request_irq(), set_irq_type(),
1064 			 * and set_irq_wake() ... but those are "rare".
1065 			 *
1066 			 * More significantly, trigger type flags aren't
1067 			 * currently maintained by genirq.
1068 			 */
1069 			if (irq >= 0 && desc->action) {
1070 				char *trigger;
1071 
1072 				switch (desc->status & IRQ_TYPE_SENSE_MASK) {
1073 				case IRQ_TYPE_NONE:
1074 					trigger = "(default)";
1075 					break;
1076 				case IRQ_TYPE_EDGE_FALLING:
1077 					trigger = "edge-falling";
1078 					break;
1079 				case IRQ_TYPE_EDGE_RISING:
1080 					trigger = "edge-rising";
1081 					break;
1082 				case IRQ_TYPE_EDGE_BOTH:
1083 					trigger = "edge-both";
1084 					break;
1085 				case IRQ_TYPE_LEVEL_HIGH:
1086 					trigger = "level-high";
1087 					break;
1088 				case IRQ_TYPE_LEVEL_LOW:
1089 					trigger = "level-low";
1090 					break;
1091 				default:
1092 					trigger = "?trigger?";
1093 					break;
1094 				}
1095 
1096 				seq_printf(s, " irq-%d %s%s",
1097 					irq, trigger,
1098 					(desc->status & IRQ_WAKEUP)
1099 						? " wakeup" : "");
1100 			}
1101 		}
1102 
1103 		seq_printf(s, "\n");
1104 	}
1105 }
1106 
1107 static int gpiolib_show(struct seq_file *s, void *unused)
1108 {
1109 	struct gpio_chip	*chip = NULL;
1110 	unsigned		gpio;
1111 	int			started = 0;
1112 
1113 	/* REVISIT this isn't locked against gpio_chip removal ... */
1114 
1115 	for (gpio = 0; gpio_is_valid(gpio); gpio++) {
1116 		struct device *dev;
1117 
1118 		if (chip == gpio_desc[gpio].chip)
1119 			continue;
1120 		chip = gpio_desc[gpio].chip;
1121 		if (!chip)
1122 			continue;
1123 
1124 		seq_printf(s, "%sGPIOs %d-%d",
1125 				started ? "\n" : "",
1126 				chip->base, chip->base + chip->ngpio - 1);
1127 		dev = chip->dev;
1128 		if (dev)
1129 			seq_printf(s, ", %s/%s",
1130 				dev->bus ? dev->bus->name : "no-bus",
1131 				dev->bus_id);
1132 		if (chip->label)
1133 			seq_printf(s, ", %s", chip->label);
1134 		if (chip->can_sleep)
1135 			seq_printf(s, ", can sleep");
1136 		seq_printf(s, ":\n");
1137 
1138 		started = 1;
1139 		if (chip->dbg_show)
1140 			chip->dbg_show(s, chip);
1141 		else
1142 			gpiolib_dbg_show(s, chip);
1143 	}
1144 	return 0;
1145 }
1146 
1147 static int gpiolib_open(struct inode *inode, struct file *file)
1148 {
1149 	return single_open(file, gpiolib_show, NULL);
1150 }
1151 
1152 static struct file_operations gpiolib_operations = {
1153 	.open		= gpiolib_open,
1154 	.read		= seq_read,
1155 	.llseek		= seq_lseek,
1156 	.release	= single_release,
1157 };
1158 
1159 static int __init gpiolib_debugfs_init(void)
1160 {
1161 	/* /sys/kernel/debug/gpio */
1162 	(void) debugfs_create_file("gpio", S_IFREG | S_IRUGO,
1163 				NULL, NULL, &gpiolib_operations);
1164 	return 0;
1165 }
1166 subsys_initcall(gpiolib_debugfs_init);
1167 
1168 #endif	/* DEBUG_FS */
1169