1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/bitmap.h>
3 #include <linux/kernel.h>
4 #include <linux/module.h>
5 #include <linux/interrupt.h>
7 #include <linux/spinlock.h>
8 #include <linux/list.h>
9 #include <linux/device.h>
10 #include <linux/err.h>
11 #include <linux/debugfs.h>
12 #include <linux/seq_file.h>
13 #include <linux/gpio.h>
14 #include <linux/idr.h>
15 #include <linux/slab.h>
16 #include <linux/acpi.h>
17 #include <linux/gpio/driver.h>
18 #include <linux/gpio/machine.h>
19 #include <linux/pinctrl/consumer.h>
20 #include <linux/cdev.h>
22 #include <linux/uaccess.h>
23 #include <linux/compat.h>
24 #include <linux/anon_inodes.h>
25 #include <linux/file.h>
26 #include <linux/kfifo.h>
27 #include <linux/poll.h>
28 #include <linux/timekeeping.h>
29 #include <uapi/linux/gpio.h>
32 #include "gpiolib-of.h"
33 #include "gpiolib-acpi.h"
35 #define CREATE_TRACE_POINTS
36 #include <trace/events/gpio.h>
38 /* Implementation infrastructure for GPIO interfaces.
40 * The GPIO programming interface allows for inlining speed-critical
41 * get/set operations for common cases, so that access to SOC-integrated
42 * GPIOs can sometimes cost only an instruction or two per bit.
46 /* When debugging, extend minimal trust to callers and platform code.
47 * Also emit diagnostic messages that may help initial bringup, when
48 * board setup or driver bugs are most common.
50 * Otherwise, minimize overhead in what may be bitbanging codepaths.
53 #define extra_checks 1
55 #define extra_checks 0
58 /* Device and char device-related information */
59 static DEFINE_IDA(gpio_ida);
60 static dev_t gpio_devt;
61 #define GPIO_DEV_MAX 256 /* 256 GPIO chip devices supported */
62 static struct bus_type gpio_bus_type = {
67 * Number of GPIOs to use for the fast path in set array
69 #define FASTPATH_NGPIO CONFIG_GPIOLIB_FASTPATH_LIMIT
71 /* gpio_lock prevents conflicts during gpio_desc[] table updates.
72 * While any GPIO is requested, its gpio_chip is not removable;
73 * each GPIO's "requested" flag serves as a lock and refcount.
75 DEFINE_SPINLOCK(gpio_lock);
77 static DEFINE_MUTEX(gpio_lookup_lock);
78 static LIST_HEAD(gpio_lookup_list);
79 LIST_HEAD(gpio_devices);
81 static DEFINE_MUTEX(gpio_machine_hogs_mutex);
82 static LIST_HEAD(gpio_machine_hogs);
84 static void gpiochip_free_hogs(struct gpio_chip *chip);
85 static int gpiochip_add_irqchip(struct gpio_chip *gpiochip,
86 struct lock_class_key *lock_key,
87 struct lock_class_key *request_key);
88 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip);
89 static int gpiochip_irqchip_init_hw(struct gpio_chip *gpiochip);
90 static int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gpiochip);
91 static void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gpiochip);
93 static bool gpiolib_initialized;
95 static inline void desc_set_label(struct gpio_desc *d, const char *label)
101 * gpio_to_desc - Convert a GPIO number to its descriptor
102 * @gpio: global GPIO number
105 * The GPIO descriptor associated with the given GPIO, or %NULL if no GPIO
106 * with the given number exists in the system.
108 struct gpio_desc *gpio_to_desc(unsigned gpio)
110 struct gpio_device *gdev;
113 spin_lock_irqsave(&gpio_lock, flags);
115 list_for_each_entry(gdev, &gpio_devices, list) {
116 if (gdev->base <= gpio &&
117 gdev->base + gdev->ngpio > gpio) {
118 spin_unlock_irqrestore(&gpio_lock, flags);
119 return &gdev->descs[gpio - gdev->base];
123 spin_unlock_irqrestore(&gpio_lock, flags);
125 if (!gpio_is_valid(gpio))
126 WARN(1, "invalid GPIO %d\n", gpio);
130 EXPORT_SYMBOL_GPL(gpio_to_desc);
133 * gpiochip_get_desc - get the GPIO descriptor corresponding to the given
134 * hardware number for this chip
136 * @hwnum: hardware number of the GPIO for this chip
139 * A pointer to the GPIO descriptor or %ERR_PTR(-EINVAL) if no GPIO exists
140 * in the given chip for the specified hardware number.
142 struct gpio_desc *gpiochip_get_desc(struct gpio_chip *chip,
145 struct gpio_device *gdev = chip->gpiodev;
147 if (hwnum >= gdev->ngpio)
148 return ERR_PTR(-EINVAL);
150 return &gdev->descs[hwnum];
154 * desc_to_gpio - convert a GPIO descriptor to the integer namespace
155 * @desc: GPIO descriptor
157 * This should disappear in the future but is needed since we still
158 * use GPIO numbers for error messages and sysfs nodes.
161 * The global GPIO number for the GPIO specified by its descriptor.
163 int desc_to_gpio(const struct gpio_desc *desc)
165 return desc->gdev->base + (desc - &desc->gdev->descs[0]);
167 EXPORT_SYMBOL_GPL(desc_to_gpio);
171 * gpiod_to_chip - Return the GPIO chip to which a GPIO descriptor belongs
172 * @desc: descriptor to return the chip of
174 struct gpio_chip *gpiod_to_chip(const struct gpio_desc *desc)
176 if (!desc || !desc->gdev)
178 return desc->gdev->chip;
180 EXPORT_SYMBOL_GPL(gpiod_to_chip);
182 /* dynamic allocation of GPIOs, e.g. on a hotplugged device */
183 static int gpiochip_find_base(int ngpio)
185 struct gpio_device *gdev;
186 int base = ARCH_NR_GPIOS - ngpio;
188 list_for_each_entry_reverse(gdev, &gpio_devices, list) {
189 /* found a free space? */
190 if (gdev->base + gdev->ngpio <= base)
193 /* nope, check the space right before the chip */
194 base = gdev->base - ngpio;
197 if (gpio_is_valid(base)) {
198 pr_debug("%s: found new base at %d\n", __func__, base);
201 pr_err("%s: cannot find free range\n", __func__);
207 * gpiod_get_direction - return the current direction of a GPIO
208 * @desc: GPIO to get the direction of
210 * Returns 0 for output, 1 for input, or an error code in case of error.
212 * This function may sleep if gpiod_cansleep() is true.
214 int gpiod_get_direction(struct gpio_desc *desc)
216 struct gpio_chip *chip;
220 chip = gpiod_to_chip(desc);
221 offset = gpio_chip_hwgpio(desc);
224 * Open drain emulation using input mode may incorrectly report
225 * input here, fix that up.
227 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags) &&
228 test_bit(FLAG_IS_OUT, &desc->flags))
231 if (!chip->get_direction)
234 ret = chip->get_direction(chip, offset);
236 /* GPIOF_DIR_IN, or other positive */
238 clear_bit(FLAG_IS_OUT, &desc->flags);
242 set_bit(FLAG_IS_OUT, &desc->flags);
246 EXPORT_SYMBOL_GPL(gpiod_get_direction);
249 * Add a new chip to the global chips list, keeping the list of chips sorted
250 * by range(means [base, base + ngpio - 1]) order.
252 * Return -EBUSY if the new chip overlaps with some other chip's integer
255 static int gpiodev_add_to_list(struct gpio_device *gdev)
257 struct gpio_device *prev, *next;
259 if (list_empty(&gpio_devices)) {
260 /* initial entry in list */
261 list_add_tail(&gdev->list, &gpio_devices);
265 next = list_entry(gpio_devices.next, struct gpio_device, list);
266 if (gdev->base + gdev->ngpio <= next->base) {
267 /* add before first entry */
268 list_add(&gdev->list, &gpio_devices);
272 prev = list_entry(gpio_devices.prev, struct gpio_device, list);
273 if (prev->base + prev->ngpio <= gdev->base) {
274 /* add behind last entry */
275 list_add_tail(&gdev->list, &gpio_devices);
279 list_for_each_entry_safe(prev, next, &gpio_devices, list) {
280 /* at the end of the list */
281 if (&next->list == &gpio_devices)
284 /* add between prev and next */
285 if (prev->base + prev->ngpio <= gdev->base
286 && gdev->base + gdev->ngpio <= next->base) {
287 list_add(&gdev->list, &prev->list);
292 dev_err(&gdev->dev, "GPIO integer space overlap, cannot add chip\n");
297 * Convert a GPIO name to its descriptor
299 static struct gpio_desc *gpio_name_to_desc(const char * const name)
301 struct gpio_device *gdev;
304 spin_lock_irqsave(&gpio_lock, flags);
306 list_for_each_entry(gdev, &gpio_devices, list) {
309 for (i = 0; i != gdev->ngpio; ++i) {
310 struct gpio_desc *desc = &gdev->descs[i];
312 if (!desc->name || !name)
315 if (!strcmp(desc->name, name)) {
316 spin_unlock_irqrestore(&gpio_lock, flags);
322 spin_unlock_irqrestore(&gpio_lock, flags);
328 * Takes the names from gc->names and checks if they are all unique. If they
329 * are, they are assigned to their gpio descriptors.
331 * Warning if one of the names is already used for a different GPIO.
333 static int gpiochip_set_desc_names(struct gpio_chip *gc)
335 struct gpio_device *gdev = gc->gpiodev;
341 /* First check all names if they are unique */
342 for (i = 0; i != gc->ngpio; ++i) {
343 struct gpio_desc *gpio;
345 gpio = gpio_name_to_desc(gc->names[i]);
348 "Detected name collision for GPIO name '%s'\n",
352 /* Then add all names to the GPIO descriptors */
353 for (i = 0; i != gc->ngpio; ++i)
354 gdev->descs[i].name = gc->names[i];
359 static unsigned long *gpiochip_allocate_mask(struct gpio_chip *chip)
363 p = bitmap_alloc(chip->ngpio, GFP_KERNEL);
367 /* Assume by default all GPIOs are valid */
368 bitmap_fill(p, chip->ngpio);
373 static int gpiochip_alloc_valid_mask(struct gpio_chip *gc)
375 if (!(of_gpio_need_valid_mask(gc) || gc->init_valid_mask))
378 gc->valid_mask = gpiochip_allocate_mask(gc);
385 static int gpiochip_init_valid_mask(struct gpio_chip *gc)
387 if (gc->init_valid_mask)
388 return gc->init_valid_mask(gc,
395 static void gpiochip_free_valid_mask(struct gpio_chip *gpiochip)
397 bitmap_free(gpiochip->valid_mask);
398 gpiochip->valid_mask = NULL;
401 static int gpiochip_add_pin_ranges(struct gpio_chip *gc)
403 if (gc->add_pin_ranges)
404 return gc->add_pin_ranges(gc);
409 bool gpiochip_line_is_valid(const struct gpio_chip *gpiochip,
412 /* No mask means all valid */
413 if (likely(!gpiochip->valid_mask))
415 return test_bit(offset, gpiochip->valid_mask);
417 EXPORT_SYMBOL_GPL(gpiochip_line_is_valid);
420 * GPIO line handle management
424 * struct linehandle_state - contains the state of a userspace handle
425 * @gdev: the GPIO device the handle pertains to
426 * @label: consumer label used to tag descriptors
427 * @descs: the GPIO descriptors held by this handle
428 * @numdescs: the number of descriptors held in the descs array
430 struct linehandle_state {
431 struct gpio_device *gdev;
433 struct gpio_desc *descs[GPIOHANDLES_MAX];
437 #define GPIOHANDLE_REQUEST_VALID_FLAGS \
438 (GPIOHANDLE_REQUEST_INPUT | \
439 GPIOHANDLE_REQUEST_OUTPUT | \
440 GPIOHANDLE_REQUEST_ACTIVE_LOW | \
441 GPIOHANDLE_REQUEST_BIAS_PULL_UP | \
442 GPIOHANDLE_REQUEST_BIAS_PULL_DOWN | \
443 GPIOHANDLE_REQUEST_BIAS_DISABLE | \
444 GPIOHANDLE_REQUEST_OPEN_DRAIN | \
445 GPIOHANDLE_REQUEST_OPEN_SOURCE)
447 static int linehandle_validate_flags(u32 flags)
449 /* Return an error if an unknown flag is set */
450 if (flags & ~GPIOHANDLE_REQUEST_VALID_FLAGS)
454 * Do not allow both INPUT & OUTPUT flags to be set as they are
457 if ((flags & GPIOHANDLE_REQUEST_INPUT) &&
458 (flags & GPIOHANDLE_REQUEST_OUTPUT))
462 * Do not allow OPEN_SOURCE & OPEN_DRAIN flags in a single request. If
463 * the hardware actually supports enabling both at the same time the
464 * electrical result would be disastrous.
466 if ((flags & GPIOHANDLE_REQUEST_OPEN_DRAIN) &&
467 (flags & GPIOHANDLE_REQUEST_OPEN_SOURCE))
470 /* OPEN_DRAIN and OPEN_SOURCE flags only make sense for output mode. */
471 if (!(flags & GPIOHANDLE_REQUEST_OUTPUT) &&
472 ((flags & GPIOHANDLE_REQUEST_OPEN_DRAIN) ||
473 (flags & GPIOHANDLE_REQUEST_OPEN_SOURCE)))
476 /* Bias flags only allowed for input or output mode. */
477 if (!((flags & GPIOHANDLE_REQUEST_INPUT) ||
478 (flags & GPIOHANDLE_REQUEST_OUTPUT)) &&
479 ((flags & GPIOHANDLE_REQUEST_BIAS_DISABLE) ||
480 (flags & GPIOHANDLE_REQUEST_BIAS_PULL_UP) ||
481 (flags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN)))
484 /* Only one bias flag can be set. */
485 if (((flags & GPIOHANDLE_REQUEST_BIAS_DISABLE) &&
486 (flags & (GPIOHANDLE_REQUEST_BIAS_PULL_DOWN |
487 GPIOHANDLE_REQUEST_BIAS_PULL_UP))) ||
488 ((flags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN) &&
489 (flags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)))
495 static void linehandle_configure_flag(unsigned long *flagsp,
496 u32 bit, bool active)
499 set_bit(bit, flagsp);
501 clear_bit(bit, flagsp);
504 static long linehandle_set_config(struct linehandle_state *lh,
507 struct gpiohandle_config gcnf;
508 struct gpio_desc *desc;
511 unsigned long *flagsp;
513 if (copy_from_user(&gcnf, ip, sizeof(gcnf)))
517 ret = linehandle_validate_flags(lflags);
521 for (i = 0; i < lh->numdescs; i++) {
523 flagsp = &desc->flags;
525 linehandle_configure_flag(flagsp, FLAG_ACTIVE_LOW,
526 lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW);
528 linehandle_configure_flag(flagsp, FLAG_OPEN_DRAIN,
529 lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN);
531 linehandle_configure_flag(flagsp, FLAG_OPEN_SOURCE,
532 lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE);
534 linehandle_configure_flag(flagsp, FLAG_PULL_UP,
535 lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP);
537 linehandle_configure_flag(flagsp, FLAG_PULL_DOWN,
538 lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN);
540 linehandle_configure_flag(flagsp, FLAG_BIAS_DISABLE,
541 lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE);
544 * Lines have to be requested explicitly for input
545 * or output, else the line will be treated "as is".
547 if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
548 int val = !!gcnf.default_values[i];
550 ret = gpiod_direction_output(desc, val);
553 } else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
554 ret = gpiod_direction_input(desc);
562 static long linehandle_ioctl(struct file *filep, unsigned int cmd,
565 struct linehandle_state *lh = filep->private_data;
566 void __user *ip = (void __user *)arg;
567 struct gpiohandle_data ghd;
568 DECLARE_BITMAP(vals, GPIOHANDLES_MAX);
571 if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
572 /* NOTE: It's ok to read values of output lines. */
573 int ret = gpiod_get_array_value_complex(false,
582 memset(&ghd, 0, sizeof(ghd));
583 for (i = 0; i < lh->numdescs; i++)
584 ghd.values[i] = test_bit(i, vals);
586 if (copy_to_user(ip, &ghd, sizeof(ghd)))
590 } else if (cmd == GPIOHANDLE_SET_LINE_VALUES_IOCTL) {
592 * All line descriptors were created at once with the same
593 * flags so just check if the first one is really output.
595 if (!test_bit(FLAG_IS_OUT, &lh->descs[0]->flags))
598 if (copy_from_user(&ghd, ip, sizeof(ghd)))
601 /* Clamp all values to [0,1] */
602 for (i = 0; i < lh->numdescs; i++)
603 __assign_bit(i, vals, ghd.values[i]);
605 /* Reuse the array setting function */
606 return gpiod_set_array_value_complex(false,
612 } else if (cmd == GPIOHANDLE_SET_CONFIG_IOCTL) {
613 return linehandle_set_config(lh, ip);
619 static long linehandle_ioctl_compat(struct file *filep, unsigned int cmd,
622 return linehandle_ioctl(filep, cmd, (unsigned long)compat_ptr(arg));
626 static int linehandle_release(struct inode *inode, struct file *filep)
628 struct linehandle_state *lh = filep->private_data;
629 struct gpio_device *gdev = lh->gdev;
632 for (i = 0; i < lh->numdescs; i++)
633 gpiod_free(lh->descs[i]);
636 put_device(&gdev->dev);
640 static const struct file_operations linehandle_fileops = {
641 .release = linehandle_release,
642 .owner = THIS_MODULE,
643 .llseek = noop_llseek,
644 .unlocked_ioctl = linehandle_ioctl,
646 .compat_ioctl = linehandle_ioctl_compat,
650 static int linehandle_create(struct gpio_device *gdev, void __user *ip)
652 struct gpiohandle_request handlereq;
653 struct linehandle_state *lh;
655 int fd, i, count = 0, ret;
658 if (copy_from_user(&handlereq, ip, sizeof(handlereq)))
660 if ((handlereq.lines == 0) || (handlereq.lines > GPIOHANDLES_MAX))
663 lflags = handlereq.flags;
665 ret = linehandle_validate_flags(lflags);
669 lh = kzalloc(sizeof(*lh), GFP_KERNEL);
673 get_device(&gdev->dev);
675 /* Make sure this is terminated */
676 handlereq.consumer_label[sizeof(handlereq.consumer_label)-1] = '\0';
677 if (strlen(handlereq.consumer_label)) {
678 lh->label = kstrdup(handlereq.consumer_label,
686 /* Request each GPIO */
687 for (i = 0; i < handlereq.lines; i++) {
688 u32 offset = handlereq.lineoffsets[i];
689 struct gpio_desc *desc;
691 if (offset >= gdev->ngpio) {
696 desc = &gdev->descs[offset];
697 ret = gpiod_request(desc, lh->label);
703 if (lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW)
704 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
705 if (lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN)
706 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
707 if (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE)
708 set_bit(FLAG_OPEN_SOURCE, &desc->flags);
709 if (lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE)
710 set_bit(FLAG_BIAS_DISABLE, &desc->flags);
711 if (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN)
712 set_bit(FLAG_PULL_DOWN, &desc->flags);
713 if (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)
714 set_bit(FLAG_PULL_UP, &desc->flags);
716 ret = gpiod_set_transitory(desc, false);
721 * Lines have to be requested explicitly for input
722 * or output, else the line will be treated "as is".
724 if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
725 int val = !!handlereq.default_values[i];
727 ret = gpiod_direction_output(desc, val);
730 } else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
731 ret = gpiod_direction_input(desc);
735 dev_dbg(&gdev->dev, "registered chardev handle for line %d\n",
738 /* Let i point at the last handle */
740 lh->numdescs = handlereq.lines;
742 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
748 file = anon_inode_getfile("gpio-linehandle",
751 O_RDONLY | O_CLOEXEC);
754 goto out_put_unused_fd;
758 if (copy_to_user(ip, &handlereq, sizeof(handlereq))) {
760 * fput() will trigger the release() callback, so do not go onto
761 * the regular error cleanup path here.
768 fd_install(fd, file);
770 dev_dbg(&gdev->dev, "registered chardev handle for %d lines\n",
778 for (i = 0; i < count; i++)
779 gpiod_free(lh->descs[i]);
783 put_device(&gdev->dev);
788 * GPIO line event management
792 * struct lineevent_state - contains the state of a userspace event
793 * @gdev: the GPIO device the event pertains to
794 * @label: consumer label used to tag descriptors
795 * @desc: the GPIO descriptor held by this event
796 * @eflags: the event flags this line was requested with
797 * @irq: the interrupt that trigger in response to events on this GPIO
798 * @wait: wait queue that handles blocking reads of events
799 * @events: KFIFO for the GPIO events
800 * @read_lock: mutex lock to protect reads from colliding with adding
801 * new events to the FIFO
802 * @timestamp: cache for the timestamp storing it between hardirq
803 * and IRQ thread, used to bring the timestamp close to the actual
806 struct lineevent_state {
807 struct gpio_device *gdev;
809 struct gpio_desc *desc;
812 wait_queue_head_t wait;
813 DECLARE_KFIFO(events, struct gpioevent_data, 16);
814 struct mutex read_lock;
818 #define GPIOEVENT_REQUEST_VALID_FLAGS \
819 (GPIOEVENT_REQUEST_RISING_EDGE | \
820 GPIOEVENT_REQUEST_FALLING_EDGE)
822 static __poll_t lineevent_poll(struct file *filep,
823 struct poll_table_struct *wait)
825 struct lineevent_state *le = filep->private_data;
828 poll_wait(filep, &le->wait, wait);
830 if (!kfifo_is_empty(&le->events))
831 events = EPOLLIN | EPOLLRDNORM;
837 static ssize_t lineevent_read(struct file *filep,
842 struct lineevent_state *le = filep->private_data;
846 if (count < sizeof(struct gpioevent_data))
850 if (kfifo_is_empty(&le->events)) {
851 if (filep->f_flags & O_NONBLOCK)
854 ret = wait_event_interruptible(le->wait,
855 !kfifo_is_empty(&le->events));
860 if (mutex_lock_interruptible(&le->read_lock))
862 ret = kfifo_to_user(&le->events, buf, count, &copied);
863 mutex_unlock(&le->read_lock);
869 * If we couldn't read anything from the fifo (a different
870 * thread might have been faster) we either return -EAGAIN if
871 * the file descriptor is non-blocking, otherwise we go back to
872 * sleep and wait for more data to arrive.
874 if (copied == 0 && (filep->f_flags & O_NONBLOCK))
877 } while (copied == 0);
882 static int lineevent_release(struct inode *inode, struct file *filep)
884 struct lineevent_state *le = filep->private_data;
885 struct gpio_device *gdev = le->gdev;
887 free_irq(le->irq, le);
888 gpiod_free(le->desc);
891 put_device(&gdev->dev);
895 static long lineevent_ioctl(struct file *filep, unsigned int cmd,
898 struct lineevent_state *le = filep->private_data;
899 void __user *ip = (void __user *)arg;
900 struct gpiohandle_data ghd;
903 * We can get the value for an event line but not set it,
904 * because it is input by definition.
906 if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
909 memset(&ghd, 0, sizeof(ghd));
911 val = gpiod_get_value_cansleep(le->desc);
916 if (copy_to_user(ip, &ghd, sizeof(ghd)))
925 static long lineevent_ioctl_compat(struct file *filep, unsigned int cmd,
928 return lineevent_ioctl(filep, cmd, (unsigned long)compat_ptr(arg));
932 static const struct file_operations lineevent_fileops = {
933 .release = lineevent_release,
934 .read = lineevent_read,
935 .poll = lineevent_poll,
936 .owner = THIS_MODULE,
937 .llseek = noop_llseek,
938 .unlocked_ioctl = lineevent_ioctl,
940 .compat_ioctl = lineevent_ioctl_compat,
944 static irqreturn_t lineevent_irq_thread(int irq, void *p)
946 struct lineevent_state *le = p;
947 struct gpioevent_data ge;
950 /* Do not leak kernel stack to userspace */
951 memset(&ge, 0, sizeof(ge));
954 * We may be running from a nested threaded interrupt in which case
955 * we didn't get the timestamp from lineevent_irq_handler().
958 ge.timestamp = ktime_get_real_ns();
960 ge.timestamp = le->timestamp;
962 if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE
963 && le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
964 int level = gpiod_get_value_cansleep(le->desc);
966 /* Emit low-to-high event */
967 ge.id = GPIOEVENT_EVENT_RISING_EDGE;
969 /* Emit high-to-low event */
970 ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
971 } else if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE) {
972 /* Emit low-to-high event */
973 ge.id = GPIOEVENT_EVENT_RISING_EDGE;
974 } else if (le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
975 /* Emit high-to-low event */
976 ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
981 ret = kfifo_put(&le->events, ge);
983 wake_up_poll(&le->wait, EPOLLIN);
988 static irqreturn_t lineevent_irq_handler(int irq, void *p)
990 struct lineevent_state *le = p;
993 * Just store the timestamp in hardirq context so we get it as
994 * close in time as possible to the actual event.
996 le->timestamp = ktime_get_real_ns();
998 return IRQ_WAKE_THREAD;
1001 static int lineevent_create(struct gpio_device *gdev, void __user *ip)
1003 struct gpioevent_request eventreq;
1004 struct lineevent_state *le;
1005 struct gpio_desc *desc;
1014 if (copy_from_user(&eventreq, ip, sizeof(eventreq)))
1017 offset = eventreq.lineoffset;
1018 lflags = eventreq.handleflags;
1019 eflags = eventreq.eventflags;
1021 if (offset >= gdev->ngpio)
1024 /* Return an error if a unknown flag is set */
1025 if ((lflags & ~GPIOHANDLE_REQUEST_VALID_FLAGS) ||
1026 (eflags & ~GPIOEVENT_REQUEST_VALID_FLAGS))
1029 /* This is just wrong: we don't look for events on output lines */
1030 if ((lflags & GPIOHANDLE_REQUEST_OUTPUT) ||
1031 (lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN) ||
1032 (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE))
1035 /* Only one bias flag can be set. */
1036 if (((lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE) &&
1037 (lflags & (GPIOHANDLE_REQUEST_BIAS_PULL_DOWN |
1038 GPIOHANDLE_REQUEST_BIAS_PULL_UP))) ||
1039 ((lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN) &&
1040 (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)))
1043 le = kzalloc(sizeof(*le), GFP_KERNEL);
1047 get_device(&gdev->dev);
1049 /* Make sure this is terminated */
1050 eventreq.consumer_label[sizeof(eventreq.consumer_label)-1] = '\0';
1051 if (strlen(eventreq.consumer_label)) {
1052 le->label = kstrdup(eventreq.consumer_label,
1060 desc = &gdev->descs[offset];
1061 ret = gpiod_request(desc, le->label);
1063 goto out_free_label;
1065 le->eflags = eflags;
1067 if (lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW)
1068 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
1069 if (lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE)
1070 set_bit(FLAG_BIAS_DISABLE, &desc->flags);
1071 if (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN)
1072 set_bit(FLAG_PULL_DOWN, &desc->flags);
1073 if (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)
1074 set_bit(FLAG_PULL_UP, &desc->flags);
1076 ret = gpiod_direction_input(desc);
1080 le->irq = gpiod_to_irq(desc);
1086 if (eflags & GPIOEVENT_REQUEST_RISING_EDGE)
1087 irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
1088 IRQF_TRIGGER_FALLING : IRQF_TRIGGER_RISING;
1089 if (eflags & GPIOEVENT_REQUEST_FALLING_EDGE)
1090 irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
1091 IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING;
1092 irqflags |= IRQF_ONESHOT;
1094 INIT_KFIFO(le->events);
1095 init_waitqueue_head(&le->wait);
1096 mutex_init(&le->read_lock);
1098 /* Request a thread to read the events */
1099 ret = request_threaded_irq(le->irq,
1100 lineevent_irq_handler,
1101 lineevent_irq_thread,
1108 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
1114 file = anon_inode_getfile("gpio-event",
1117 O_RDONLY | O_CLOEXEC);
1119 ret = PTR_ERR(file);
1120 goto out_put_unused_fd;
1124 if (copy_to_user(ip, &eventreq, sizeof(eventreq))) {
1126 * fput() will trigger the release() callback, so do not go onto
1127 * the regular error cleanup path here.
1134 fd_install(fd, file);
1141 free_irq(le->irq, le);
1143 gpiod_free(le->desc);
1148 put_device(&gdev->dev);
1153 * gpio_ioctl() - ioctl handler for the GPIO chardev
1155 static long gpio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1157 struct gpio_device *gdev = filp->private_data;
1158 struct gpio_chip *chip = gdev->chip;
1159 void __user *ip = (void __user *)arg;
1161 /* We fail any subsequent ioctl():s when the chip is gone */
1165 /* Fill in the struct and pass to userspace */
1166 if (cmd == GPIO_GET_CHIPINFO_IOCTL) {
1167 struct gpiochip_info chipinfo;
1169 memset(&chipinfo, 0, sizeof(chipinfo));
1171 strncpy(chipinfo.name, dev_name(&gdev->dev),
1172 sizeof(chipinfo.name));
1173 chipinfo.name[sizeof(chipinfo.name)-1] = '\0';
1174 strncpy(chipinfo.label, gdev->label,
1175 sizeof(chipinfo.label));
1176 chipinfo.label[sizeof(chipinfo.label)-1] = '\0';
1177 chipinfo.lines = gdev->ngpio;
1178 if (copy_to_user(ip, &chipinfo, sizeof(chipinfo)))
1181 } else if (cmd == GPIO_GET_LINEINFO_IOCTL) {
1182 struct gpioline_info lineinfo;
1183 struct gpio_desc *desc;
1185 if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
1187 if (lineinfo.line_offset >= gdev->ngpio)
1190 desc = &gdev->descs[lineinfo.line_offset];
1192 strncpy(lineinfo.name, desc->name,
1193 sizeof(lineinfo.name));
1194 lineinfo.name[sizeof(lineinfo.name)-1] = '\0';
1196 lineinfo.name[0] = '\0';
1199 strncpy(lineinfo.consumer, desc->label,
1200 sizeof(lineinfo.consumer));
1201 lineinfo.consumer[sizeof(lineinfo.consumer)-1] = '\0';
1203 lineinfo.consumer[0] = '\0';
1207 * Userspace only need to know that the kernel is using
1208 * this GPIO so it can't use it.
1211 if (test_bit(FLAG_REQUESTED, &desc->flags) ||
1212 test_bit(FLAG_IS_HOGGED, &desc->flags) ||
1213 test_bit(FLAG_USED_AS_IRQ, &desc->flags) ||
1214 test_bit(FLAG_EXPORT, &desc->flags) ||
1215 test_bit(FLAG_SYSFS, &desc->flags) ||
1216 !pinctrl_gpio_can_use_line(chip->base + lineinfo.line_offset))
1217 lineinfo.flags |= GPIOLINE_FLAG_KERNEL;
1218 if (test_bit(FLAG_IS_OUT, &desc->flags))
1219 lineinfo.flags |= GPIOLINE_FLAG_IS_OUT;
1220 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
1221 lineinfo.flags |= GPIOLINE_FLAG_ACTIVE_LOW;
1222 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
1223 lineinfo.flags |= (GPIOLINE_FLAG_OPEN_DRAIN |
1224 GPIOLINE_FLAG_IS_OUT);
1225 if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
1226 lineinfo.flags |= (GPIOLINE_FLAG_OPEN_SOURCE |
1227 GPIOLINE_FLAG_IS_OUT);
1228 if (test_bit(FLAG_BIAS_DISABLE, &desc->flags))
1229 lineinfo.flags |= GPIOLINE_FLAG_BIAS_DISABLE;
1230 if (test_bit(FLAG_PULL_DOWN, &desc->flags))
1231 lineinfo.flags |= GPIOLINE_FLAG_BIAS_PULL_DOWN;
1232 if (test_bit(FLAG_PULL_UP, &desc->flags))
1233 lineinfo.flags |= GPIOLINE_FLAG_BIAS_PULL_UP;
1235 if (copy_to_user(ip, &lineinfo, sizeof(lineinfo)))
1238 } else if (cmd == GPIO_GET_LINEHANDLE_IOCTL) {
1239 return linehandle_create(gdev, ip);
1240 } else if (cmd == GPIO_GET_LINEEVENT_IOCTL) {
1241 return lineevent_create(gdev, ip);
1246 #ifdef CONFIG_COMPAT
1247 static long gpio_ioctl_compat(struct file *filp, unsigned int cmd,
1250 return gpio_ioctl(filp, cmd, (unsigned long)compat_ptr(arg));
1255 * gpio_chrdev_open() - open the chardev for ioctl operations
1256 * @inode: inode for this chardev
1257 * @filp: file struct for storing private data
1258 * Returns 0 on success
1260 static int gpio_chrdev_open(struct inode *inode, struct file *filp)
1262 struct gpio_device *gdev = container_of(inode->i_cdev,
1263 struct gpio_device, chrdev);
1265 /* Fail on open if the backing gpiochip is gone */
1268 get_device(&gdev->dev);
1269 filp->private_data = gdev;
1271 return nonseekable_open(inode, filp);
1275 * gpio_chrdev_release() - close chardev after ioctl operations
1276 * @inode: inode for this chardev
1277 * @filp: file struct for storing private data
1278 * Returns 0 on success
1280 static int gpio_chrdev_release(struct inode *inode, struct file *filp)
1282 struct gpio_device *gdev = container_of(inode->i_cdev,
1283 struct gpio_device, chrdev);
1285 put_device(&gdev->dev);
1290 static const struct file_operations gpio_fileops = {
1291 .release = gpio_chrdev_release,
1292 .open = gpio_chrdev_open,
1293 .owner = THIS_MODULE,
1294 .llseek = no_llseek,
1295 .unlocked_ioctl = gpio_ioctl,
1296 #ifdef CONFIG_COMPAT
1297 .compat_ioctl = gpio_ioctl_compat,
1301 static void gpiodevice_release(struct device *dev)
1303 struct gpio_device *gdev = dev_get_drvdata(dev);
1305 list_del(&gdev->list);
1306 ida_simple_remove(&gpio_ida, gdev->id);
1307 kfree_const(gdev->label);
1312 static int gpiochip_setup_dev(struct gpio_device *gdev)
1316 cdev_init(&gdev->chrdev, &gpio_fileops);
1317 gdev->chrdev.owner = THIS_MODULE;
1318 gdev->dev.devt = MKDEV(MAJOR(gpio_devt), gdev->id);
1320 ret = cdev_device_add(&gdev->chrdev, &gdev->dev);
1324 chip_dbg(gdev->chip, "added GPIO chardev (%d:%d)\n",
1325 MAJOR(gpio_devt), gdev->id);
1327 ret = gpiochip_sysfs_register(gdev);
1329 goto err_remove_device;
1331 /* From this point, the .release() function cleans up gpio_device */
1332 gdev->dev.release = gpiodevice_release;
1333 pr_debug("%s: registered GPIOs %d to %d on device: %s (%s)\n",
1334 __func__, gdev->base, gdev->base + gdev->ngpio - 1,
1335 dev_name(&gdev->dev), gdev->chip->label ? : "generic");
1340 cdev_device_del(&gdev->chrdev, &gdev->dev);
1344 static void gpiochip_machine_hog(struct gpio_chip *chip, struct gpiod_hog *hog)
1346 struct gpio_desc *desc;
1349 desc = gpiochip_get_desc(chip, hog->chip_hwnum);
1351 pr_err("%s: unable to get GPIO desc: %ld\n",
1352 __func__, PTR_ERR(desc));
1356 if (test_bit(FLAG_IS_HOGGED, &desc->flags))
1359 rv = gpiod_hog(desc, hog->line_name, hog->lflags, hog->dflags);
1361 pr_err("%s: unable to hog GPIO line (%s:%u): %d\n",
1362 __func__, chip->label, hog->chip_hwnum, rv);
1365 static void machine_gpiochip_add(struct gpio_chip *chip)
1367 struct gpiod_hog *hog;
1369 mutex_lock(&gpio_machine_hogs_mutex);
1371 list_for_each_entry(hog, &gpio_machine_hogs, list) {
1372 if (!strcmp(chip->label, hog->chip_label))
1373 gpiochip_machine_hog(chip, hog);
1376 mutex_unlock(&gpio_machine_hogs_mutex);
1379 static void gpiochip_setup_devs(void)
1381 struct gpio_device *gdev;
1384 list_for_each_entry(gdev, &gpio_devices, list) {
1385 ret = gpiochip_setup_dev(gdev);
1387 pr_err("%s: Failed to initialize gpio device (%d)\n",
1388 dev_name(&gdev->dev), ret);
1392 int gpiochip_add_data_with_key(struct gpio_chip *chip, void *data,
1393 struct lock_class_key *lock_key,
1394 struct lock_class_key *request_key)
1396 unsigned long flags;
1399 int base = chip->base;
1400 struct gpio_device *gdev;
1403 * First: allocate and populate the internal stat container, and
1404 * set up the struct device.
1406 gdev = kzalloc(sizeof(*gdev), GFP_KERNEL);
1409 gdev->dev.bus = &gpio_bus_type;
1411 chip->gpiodev = gdev;
1413 gdev->dev.parent = chip->parent;
1414 gdev->dev.of_node = chip->parent->of_node;
1417 #ifdef CONFIG_OF_GPIO
1418 /* If the gpiochip has an assigned OF node this takes precedence */
1420 gdev->dev.of_node = chip->of_node;
1422 chip->of_node = gdev->dev.of_node;
1425 gdev->id = ida_simple_get(&gpio_ida, 0, 0, GFP_KERNEL);
1430 dev_set_name(&gdev->dev, "gpiochip%d", gdev->id);
1431 device_initialize(&gdev->dev);
1432 dev_set_drvdata(&gdev->dev, gdev);
1433 if (chip->parent && chip->parent->driver)
1434 gdev->owner = chip->parent->driver->owner;
1435 else if (chip->owner)
1436 /* TODO: remove chip->owner */
1437 gdev->owner = chip->owner;
1439 gdev->owner = THIS_MODULE;
1441 gdev->descs = kcalloc(chip->ngpio, sizeof(gdev->descs[0]), GFP_KERNEL);
1447 if (chip->ngpio == 0) {
1448 chip_err(chip, "tried to insert a GPIO chip with zero lines\n");
1450 goto err_free_descs;
1453 if (chip->ngpio > FASTPATH_NGPIO)
1454 chip_warn(chip, "line cnt %u is greater than fast path cnt %u\n",
1455 chip->ngpio, FASTPATH_NGPIO);
1457 gdev->label = kstrdup_const(chip->label ?: "unknown", GFP_KERNEL);
1460 goto err_free_descs;
1463 gdev->ngpio = chip->ngpio;
1466 spin_lock_irqsave(&gpio_lock, flags);
1469 * TODO: this allocates a Linux GPIO number base in the global
1470 * GPIO numberspace for this chip. In the long run we want to
1471 * get *rid* of this numberspace and use only descriptors, but
1472 * it may be a pipe dream. It will not happen before we get rid
1473 * of the sysfs interface anyways.
1476 base = gpiochip_find_base(chip->ngpio);
1479 spin_unlock_irqrestore(&gpio_lock, flags);
1480 goto err_free_label;
1483 * TODO: it should not be necessary to reflect the assigned
1484 * base outside of the GPIO subsystem. Go over drivers and
1485 * see if anyone makes use of this, else drop this and assign
1492 ret = gpiodev_add_to_list(gdev);
1494 spin_unlock_irqrestore(&gpio_lock, flags);
1495 goto err_free_label;
1498 spin_unlock_irqrestore(&gpio_lock, flags);
1500 for (i = 0; i < chip->ngpio; i++)
1501 gdev->descs[i].gdev = gdev;
1503 #ifdef CONFIG_PINCTRL
1504 INIT_LIST_HEAD(&gdev->pin_ranges);
1507 ret = gpiochip_set_desc_names(chip);
1509 goto err_remove_from_list;
1511 ret = gpiochip_alloc_valid_mask(chip);
1513 goto err_remove_from_list;
1515 ret = of_gpiochip_add(chip);
1517 goto err_free_gpiochip_mask;
1519 ret = gpiochip_init_valid_mask(chip);
1521 goto err_remove_of_chip;
1523 for (i = 0; i < chip->ngpio; i++) {
1524 struct gpio_desc *desc = &gdev->descs[i];
1526 if (chip->get_direction && gpiochip_line_is_valid(chip, i)) {
1527 if (!chip->get_direction(chip, i))
1528 set_bit(FLAG_IS_OUT, &desc->flags);
1530 clear_bit(FLAG_IS_OUT, &desc->flags);
1532 if (!chip->direction_input)
1533 set_bit(FLAG_IS_OUT, &desc->flags);
1535 clear_bit(FLAG_IS_OUT, &desc->flags);
1539 ret = gpiochip_add_pin_ranges(chip);
1541 goto err_remove_of_chip;
1543 acpi_gpiochip_add(chip);
1545 machine_gpiochip_add(chip);
1547 ret = gpiochip_irqchip_init_valid_mask(chip);
1549 goto err_remove_acpi_chip;
1551 ret = gpiochip_irqchip_init_hw(chip);
1553 goto err_remove_acpi_chip;
1555 ret = gpiochip_add_irqchip(chip, lock_key, request_key);
1557 goto err_remove_irqchip_mask;
1560 * By first adding the chardev, and then adding the device,
1561 * we get a device node entry in sysfs under
1562 * /sys/bus/gpio/devices/gpiochipN/dev that can be used for
1563 * coldplug of device nodes and other udev business.
1564 * We can do this only if gpiolib has been initialized.
1565 * Otherwise, defer until later.
1567 if (gpiolib_initialized) {
1568 ret = gpiochip_setup_dev(gdev);
1570 goto err_remove_irqchip;
1575 gpiochip_irqchip_remove(chip);
1576 err_remove_irqchip_mask:
1577 gpiochip_irqchip_free_valid_mask(chip);
1578 err_remove_acpi_chip:
1579 acpi_gpiochip_remove(chip);
1581 gpiochip_free_hogs(chip);
1582 of_gpiochip_remove(chip);
1583 err_free_gpiochip_mask:
1584 gpiochip_remove_pin_ranges(chip);
1585 gpiochip_free_valid_mask(chip);
1586 err_remove_from_list:
1587 spin_lock_irqsave(&gpio_lock, flags);
1588 list_del(&gdev->list);
1589 spin_unlock_irqrestore(&gpio_lock, flags);
1591 kfree_const(gdev->label);
1595 ida_simple_remove(&gpio_ida, gdev->id);
1597 /* failures here can mean systems won't boot... */
1598 pr_err("%s: GPIOs %d..%d (%s) failed to register, %d\n", __func__,
1599 gdev->base, gdev->base + gdev->ngpio - 1,
1600 chip->label ? : "generic", ret);
1604 EXPORT_SYMBOL_GPL(gpiochip_add_data_with_key);
1607 * gpiochip_get_data() - get per-subdriver data for the chip
1611 * The per-subdriver data for the chip.
1613 void *gpiochip_get_data(struct gpio_chip *chip)
1615 return chip->gpiodev->data;
1617 EXPORT_SYMBOL_GPL(gpiochip_get_data);
1620 * gpiochip_remove() - unregister a gpio_chip
1621 * @chip: the chip to unregister
1623 * A gpio_chip with any GPIOs still requested may not be removed.
1625 void gpiochip_remove(struct gpio_chip *chip)
1627 struct gpio_device *gdev = chip->gpiodev;
1628 struct gpio_desc *desc;
1629 unsigned long flags;
1631 bool requested = false;
1633 /* FIXME: should the legacy sysfs handling be moved to gpio_device? */
1634 gpiochip_sysfs_unregister(gdev);
1635 gpiochip_free_hogs(chip);
1636 /* Numb the device, cancelling all outstanding operations */
1638 gpiochip_irqchip_remove(chip);
1639 acpi_gpiochip_remove(chip);
1640 of_gpiochip_remove(chip);
1641 gpiochip_remove_pin_ranges(chip);
1642 gpiochip_free_valid_mask(chip);
1644 * We accept no more calls into the driver from this point, so
1645 * NULL the driver data pointer
1649 spin_lock_irqsave(&gpio_lock, flags);
1650 for (i = 0; i < gdev->ngpio; i++) {
1651 desc = &gdev->descs[i];
1652 if (test_bit(FLAG_REQUESTED, &desc->flags))
1655 spin_unlock_irqrestore(&gpio_lock, flags);
1658 dev_crit(&gdev->dev,
1659 "REMOVING GPIOCHIP WITH GPIOS STILL REQUESTED\n");
1662 * The gpiochip side puts its use of the device to rest here:
1663 * if there are no userspace clients, the chardev and device will
1664 * be removed, else it will be dangling until the last user is
1667 cdev_device_del(&gdev->chrdev, &gdev->dev);
1668 put_device(&gdev->dev);
1670 EXPORT_SYMBOL_GPL(gpiochip_remove);
1672 static void devm_gpio_chip_release(struct device *dev, void *res)
1674 struct gpio_chip *chip = *(struct gpio_chip **)res;
1676 gpiochip_remove(chip);
1680 * devm_gpiochip_add_data() - Resource managed gpiochip_add_data()
1681 * @dev: pointer to the device that gpio_chip belongs to.
1682 * @chip: the chip to register, with chip->base initialized
1683 * @data: driver-private data associated with this chip
1685 * Context: potentially before irqs will work
1687 * The gpio chip automatically be released when the device is unbound.
1690 * A negative errno if the chip can't be registered, such as because the
1691 * chip->base is invalid or already associated with a different chip.
1692 * Otherwise it returns zero as a success code.
1694 int devm_gpiochip_add_data(struct device *dev, struct gpio_chip *chip,
1697 struct gpio_chip **ptr;
1700 ptr = devres_alloc(devm_gpio_chip_release, sizeof(*ptr),
1705 ret = gpiochip_add_data(chip, data);
1712 devres_add(dev, ptr);
1716 EXPORT_SYMBOL_GPL(devm_gpiochip_add_data);
1719 * gpiochip_find() - iterator for locating a specific gpio_chip
1720 * @data: data to pass to match function
1721 * @match: Callback function to check gpio_chip
1723 * Similar to bus_find_device. It returns a reference to a gpio_chip as
1724 * determined by a user supplied @match callback. The callback should return
1725 * 0 if the device doesn't match and non-zero if it does. If the callback is
1726 * non-zero, this function will return to the caller and not iterate over any
1729 struct gpio_chip *gpiochip_find(void *data,
1730 int (*match)(struct gpio_chip *chip,
1733 struct gpio_device *gdev;
1734 struct gpio_chip *chip = NULL;
1735 unsigned long flags;
1737 spin_lock_irqsave(&gpio_lock, flags);
1738 list_for_each_entry(gdev, &gpio_devices, list)
1739 if (gdev->chip && match(gdev->chip, data)) {
1744 spin_unlock_irqrestore(&gpio_lock, flags);
1748 EXPORT_SYMBOL_GPL(gpiochip_find);
1750 static int gpiochip_match_name(struct gpio_chip *chip, void *data)
1752 const char *name = data;
1754 return !strcmp(chip->label, name);
1757 static struct gpio_chip *find_chip_by_name(const char *name)
1759 return gpiochip_find((void *)name, gpiochip_match_name);
1762 #ifdef CONFIG_GPIOLIB_IRQCHIP
1765 * The following is irqchip helper code for gpiochips.
1768 static int gpiochip_irqchip_init_hw(struct gpio_chip *gc)
1770 struct gpio_irq_chip *girq = &gc->irq;
1775 return girq->init_hw(gc);
1778 static int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gc)
1780 struct gpio_irq_chip *girq = &gc->irq;
1782 if (!girq->init_valid_mask)
1785 girq->valid_mask = gpiochip_allocate_mask(gc);
1786 if (!girq->valid_mask)
1789 girq->init_valid_mask(gc, girq->valid_mask, gc->ngpio);
1794 static void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gpiochip)
1796 bitmap_free(gpiochip->irq.valid_mask);
1797 gpiochip->irq.valid_mask = NULL;
1800 bool gpiochip_irqchip_irq_valid(const struct gpio_chip *gpiochip,
1801 unsigned int offset)
1803 if (!gpiochip_line_is_valid(gpiochip, offset))
1805 /* No mask means all valid */
1806 if (likely(!gpiochip->irq.valid_mask))
1808 return test_bit(offset, gpiochip->irq.valid_mask);
1810 EXPORT_SYMBOL_GPL(gpiochip_irqchip_irq_valid);
1813 * gpiochip_set_cascaded_irqchip() - connects a cascaded irqchip to a gpiochip
1814 * @gc: the gpiochip to set the irqchip chain to
1815 * @parent_irq: the irq number corresponding to the parent IRQ for this
1817 * @parent_handler: the parent interrupt handler for the accumulated IRQ
1818 * coming out of the gpiochip. If the interrupt is nested rather than
1819 * cascaded, pass NULL in this handler argument
1821 static void gpiochip_set_cascaded_irqchip(struct gpio_chip *gc,
1822 unsigned int parent_irq,
1823 irq_flow_handler_t parent_handler)
1825 struct gpio_irq_chip *girq = &gc->irq;
1826 struct device *dev = &gc->gpiodev->dev;
1828 if (!girq->domain) {
1829 chip_err(gc, "called %s before setting up irqchip\n",
1834 if (parent_handler) {
1835 if (gc->can_sleep) {
1837 "you cannot have chained interrupts on a chip that may sleep\n");
1840 girq->parents = devm_kcalloc(dev, 1,
1841 sizeof(*girq->parents),
1843 if (!girq->parents) {
1844 chip_err(gc, "out of memory allocating parent IRQ\n");
1847 girq->parents[0] = parent_irq;
1848 girq->num_parents = 1;
1850 * The parent irqchip is already using the chip_data for this
1851 * irqchip, so our callbacks simply use the handler_data.
1853 irq_set_chained_handler_and_data(parent_irq, parent_handler,
1859 * gpiochip_set_chained_irqchip() - connects a chained irqchip to a gpiochip
1860 * @gpiochip: the gpiochip to set the irqchip chain to
1861 * @irqchip: the irqchip to chain to the gpiochip
1862 * @parent_irq: the irq number corresponding to the parent IRQ for this
1864 * @parent_handler: the parent interrupt handler for the accumulated IRQ
1865 * coming out of the gpiochip.
1867 void gpiochip_set_chained_irqchip(struct gpio_chip *gpiochip,
1868 struct irq_chip *irqchip,
1869 unsigned int parent_irq,
1870 irq_flow_handler_t parent_handler)
1872 if (gpiochip->irq.threaded) {
1873 chip_err(gpiochip, "tried to chain a threaded gpiochip\n");
1877 gpiochip_set_cascaded_irqchip(gpiochip, parent_irq, parent_handler);
1879 EXPORT_SYMBOL_GPL(gpiochip_set_chained_irqchip);
1882 * gpiochip_set_nested_irqchip() - connects a nested irqchip to a gpiochip
1883 * @gpiochip: the gpiochip to set the irqchip nested handler to
1884 * @irqchip: the irqchip to nest to the gpiochip
1885 * @parent_irq: the irq number corresponding to the parent IRQ for this
1888 void gpiochip_set_nested_irqchip(struct gpio_chip *gpiochip,
1889 struct irq_chip *irqchip,
1890 unsigned int parent_irq)
1892 gpiochip_set_cascaded_irqchip(gpiochip, parent_irq, NULL);
1894 EXPORT_SYMBOL_GPL(gpiochip_set_nested_irqchip);
1896 #ifdef CONFIG_IRQ_DOMAIN_HIERARCHY
1899 * gpiochip_set_hierarchical_irqchip() - connects a hierarchical irqchip
1901 * @gc: the gpiochip to set the irqchip hierarchical handler to
1902 * @irqchip: the irqchip to handle this level of the hierarchy, the interrupt
1903 * will then percolate up to the parent
1905 static void gpiochip_set_hierarchical_irqchip(struct gpio_chip *gc,
1906 struct irq_chip *irqchip)
1908 /* DT will deal with mapping each IRQ as we go along */
1909 if (is_of_node(gc->irq.fwnode))
1913 * This is for legacy and boardfile "irqchip" fwnodes: allocate
1914 * irqs upfront instead of dynamically since we don't have the
1915 * dynamic type of allocation that hardware description languages
1916 * provide. Once all GPIO drivers using board files are gone from
1917 * the kernel we can delete this code, but for a transitional period
1918 * it is necessary to keep this around.
1920 if (is_fwnode_irqchip(gc->irq.fwnode)) {
1924 for (i = 0; i < gc->ngpio; i++) {
1925 struct irq_fwspec fwspec;
1926 unsigned int parent_hwirq;
1927 unsigned int parent_type;
1928 struct gpio_irq_chip *girq = &gc->irq;
1931 * We call the child to parent translation function
1932 * only to check if the child IRQ is valid or not.
1933 * Just pick the rising edge type here as that is what
1934 * we likely need to support.
1936 ret = girq->child_to_parent_hwirq(gc, i,
1937 IRQ_TYPE_EDGE_RISING,
1941 chip_err(gc, "skip set-up on hwirq %d\n",
1946 fwspec.fwnode = gc->irq.fwnode;
1947 /* This is the hwirq for the GPIO line side of things */
1948 fwspec.param[0] = girq->child_offset_to_irq(gc, i);
1949 /* Just pick something */
1950 fwspec.param[1] = IRQ_TYPE_EDGE_RISING;
1951 fwspec.param_count = 2;
1952 ret = __irq_domain_alloc_irqs(gc->irq.domain,
1953 /* just pick something */
1962 "can not allocate irq for GPIO line %d parent hwirq %d in hierarchy domain: %d\n",
1969 chip_err(gc, "%s unknown fwnode type proceed anyway\n", __func__);
1974 static int gpiochip_hierarchy_irq_domain_translate(struct irq_domain *d,
1975 struct irq_fwspec *fwspec,
1976 unsigned long *hwirq,
1979 /* We support standard DT translation */
1980 if (is_of_node(fwspec->fwnode) && fwspec->param_count == 2) {
1981 return irq_domain_translate_twocell(d, fwspec, hwirq, type);
1984 /* This is for board files and others not using DT */
1985 if (is_fwnode_irqchip(fwspec->fwnode)) {
1988 ret = irq_domain_translate_twocell(d, fwspec, hwirq, type);
1991 WARN_ON(*type == IRQ_TYPE_NONE);
1997 static int gpiochip_hierarchy_irq_domain_alloc(struct irq_domain *d,
1999 unsigned int nr_irqs,
2002 struct gpio_chip *gc = d->host_data;
2003 irq_hw_number_t hwirq;
2004 unsigned int type = IRQ_TYPE_NONE;
2005 struct irq_fwspec *fwspec = data;
2006 struct irq_fwspec parent_fwspec;
2007 unsigned int parent_hwirq;
2008 unsigned int parent_type;
2009 struct gpio_irq_chip *girq = &gc->irq;
2013 * The nr_irqs parameter is always one except for PCI multi-MSI
2014 * so this should not happen.
2016 WARN_ON(nr_irqs != 1);
2018 ret = gc->irq.child_irq_domain_ops.translate(d, fwspec, &hwirq, &type);
2022 chip_info(gc, "allocate IRQ %d, hwirq %lu\n", irq, hwirq);
2024 ret = girq->child_to_parent_hwirq(gc, hwirq, type,
2025 &parent_hwirq, &parent_type);
2027 chip_err(gc, "can't look up hwirq %lu\n", hwirq);
2030 chip_info(gc, "found parent hwirq %u\n", parent_hwirq);
2033 * We set handle_bad_irq because the .set_type() should
2034 * always be invoked and set the right type of handler.
2036 irq_domain_set_info(d,
2046 * Create a IRQ fwspec to send up to the parent irqdomain:
2047 * specify the hwirq we address on the parent and tie it
2048 * all together up the chain.
2050 parent_fwspec.fwnode = d->parent->fwnode;
2051 /* This parent only handles asserted level IRQs */
2052 girq->populate_parent_fwspec(gc, &parent_fwspec, parent_hwirq,
2054 chip_info(gc, "alloc_irqs_parent for %d parent hwirq %d\n",
2056 ret = irq_domain_alloc_irqs_parent(d, irq, 1, &parent_fwspec);
2059 "failed to allocate parent hwirq %d for hwirq %lu\n",
2060 parent_hwirq, hwirq);
2065 static unsigned int gpiochip_child_offset_to_irq_noop(struct gpio_chip *chip,
2066 unsigned int offset)
2071 static void gpiochip_hierarchy_setup_domain_ops(struct irq_domain_ops *ops)
2073 ops->activate = gpiochip_irq_domain_activate;
2074 ops->deactivate = gpiochip_irq_domain_deactivate;
2075 ops->alloc = gpiochip_hierarchy_irq_domain_alloc;
2076 ops->free = irq_domain_free_irqs_common;
2079 * We only allow overriding the translate() function for
2080 * hierarchical chips, and this should only be done if the user
2081 * really need something other than 1:1 translation.
2083 if (!ops->translate)
2084 ops->translate = gpiochip_hierarchy_irq_domain_translate;
2087 static int gpiochip_hierarchy_add_domain(struct gpio_chip *gc)
2089 if (!gc->irq.child_to_parent_hwirq ||
2091 chip_err(gc, "missing irqdomain vital data\n");
2095 if (!gc->irq.child_offset_to_irq)
2096 gc->irq.child_offset_to_irq = gpiochip_child_offset_to_irq_noop;
2098 if (!gc->irq.populate_parent_fwspec)
2099 gc->irq.populate_parent_fwspec =
2100 gpiochip_populate_parent_fwspec_twocell;
2102 gpiochip_hierarchy_setup_domain_ops(&gc->irq.child_irq_domain_ops);
2104 gc->irq.domain = irq_domain_create_hierarchy(
2105 gc->irq.parent_domain,
2109 &gc->irq.child_irq_domain_ops,
2112 if (!gc->irq.domain)
2115 gpiochip_set_hierarchical_irqchip(gc, gc->irq.chip);
2120 static bool gpiochip_hierarchy_is_hierarchical(struct gpio_chip *gc)
2122 return !!gc->irq.parent_domain;
2125 void gpiochip_populate_parent_fwspec_twocell(struct gpio_chip *chip,
2126 struct irq_fwspec *fwspec,
2127 unsigned int parent_hwirq,
2128 unsigned int parent_type)
2130 fwspec->param_count = 2;
2131 fwspec->param[0] = parent_hwirq;
2132 fwspec->param[1] = parent_type;
2134 EXPORT_SYMBOL_GPL(gpiochip_populate_parent_fwspec_twocell);
2136 void gpiochip_populate_parent_fwspec_fourcell(struct gpio_chip *chip,
2137 struct irq_fwspec *fwspec,
2138 unsigned int parent_hwirq,
2139 unsigned int parent_type)
2141 fwspec->param_count = 4;
2142 fwspec->param[0] = 0;
2143 fwspec->param[1] = parent_hwirq;
2144 fwspec->param[2] = 0;
2145 fwspec->param[3] = parent_type;
2147 EXPORT_SYMBOL_GPL(gpiochip_populate_parent_fwspec_fourcell);
2151 static int gpiochip_hierarchy_add_domain(struct gpio_chip *gc)
2156 static bool gpiochip_hierarchy_is_hierarchical(struct gpio_chip *gc)
2161 #endif /* CONFIG_IRQ_DOMAIN_HIERARCHY */
2164 * gpiochip_irq_map() - maps an IRQ into a GPIO irqchip
2165 * @d: the irqdomain used by this irqchip
2166 * @irq: the global irq number used by this GPIO irqchip irq
2167 * @hwirq: the local IRQ/GPIO line offset on this gpiochip
2169 * This function will set up the mapping for a certain IRQ line on a
2170 * gpiochip by assigning the gpiochip as chip data, and using the irqchip
2171 * stored inside the gpiochip.
2173 int gpiochip_irq_map(struct irq_domain *d, unsigned int irq,
2174 irq_hw_number_t hwirq)
2176 struct gpio_chip *chip = d->host_data;
2179 if (!gpiochip_irqchip_irq_valid(chip, hwirq))
2182 irq_set_chip_data(irq, chip);
2184 * This lock class tells lockdep that GPIO irqs are in a different
2185 * category than their parents, so it won't report false recursion.
2187 irq_set_lockdep_class(irq, chip->irq.lock_key, chip->irq.request_key);
2188 irq_set_chip_and_handler(irq, chip->irq.chip, chip->irq.handler);
2189 /* Chips that use nested thread handlers have them marked */
2190 if (chip->irq.threaded)
2191 irq_set_nested_thread(irq, 1);
2192 irq_set_noprobe(irq);
2194 if (chip->irq.num_parents == 1)
2195 ret = irq_set_parent(irq, chip->irq.parents[0]);
2196 else if (chip->irq.map)
2197 ret = irq_set_parent(irq, chip->irq.map[hwirq]);
2203 * No set-up of the hardware will happen if IRQ_TYPE_NONE
2204 * is passed as default type.
2206 if (chip->irq.default_type != IRQ_TYPE_NONE)
2207 irq_set_irq_type(irq, chip->irq.default_type);
2211 EXPORT_SYMBOL_GPL(gpiochip_irq_map);
2213 void gpiochip_irq_unmap(struct irq_domain *d, unsigned int irq)
2215 struct gpio_chip *chip = d->host_data;
2217 if (chip->irq.threaded)
2218 irq_set_nested_thread(irq, 0);
2219 irq_set_chip_and_handler(irq, NULL, NULL);
2220 irq_set_chip_data(irq, NULL);
2222 EXPORT_SYMBOL_GPL(gpiochip_irq_unmap);
2224 static const struct irq_domain_ops gpiochip_domain_ops = {
2225 .map = gpiochip_irq_map,
2226 .unmap = gpiochip_irq_unmap,
2227 /* Virtually all GPIO irqchips are twocell:ed */
2228 .xlate = irq_domain_xlate_twocell,
2232 * TODO: move these activate/deactivate in under the hierarchicial
2233 * irqchip implementation as static once SPMI and SSBI (all external
2234 * users) are phased over.
2237 * gpiochip_irq_domain_activate() - Lock a GPIO to be used as an IRQ
2238 * @domain: The IRQ domain used by this IRQ chip
2239 * @data: Outermost irq_data associated with the IRQ
2240 * @reserve: If set, only reserve an interrupt vector instead of assigning one
2242 * This function is a wrapper that calls gpiochip_lock_as_irq() and is to be
2243 * used as the activate function for the &struct irq_domain_ops. The host_data
2244 * for the IRQ domain must be the &struct gpio_chip.
2246 int gpiochip_irq_domain_activate(struct irq_domain *domain,
2247 struct irq_data *data, bool reserve)
2249 struct gpio_chip *chip = domain->host_data;
2251 return gpiochip_lock_as_irq(chip, data->hwirq);
2253 EXPORT_SYMBOL_GPL(gpiochip_irq_domain_activate);
2256 * gpiochip_irq_domain_deactivate() - Unlock a GPIO used as an IRQ
2257 * @domain: The IRQ domain used by this IRQ chip
2258 * @data: Outermost irq_data associated with the IRQ
2260 * This function is a wrapper that will call gpiochip_unlock_as_irq() and is to
2261 * be used as the deactivate function for the &struct irq_domain_ops. The
2262 * host_data for the IRQ domain must be the &struct gpio_chip.
2264 void gpiochip_irq_domain_deactivate(struct irq_domain *domain,
2265 struct irq_data *data)
2267 struct gpio_chip *chip = domain->host_data;
2269 return gpiochip_unlock_as_irq(chip, data->hwirq);
2271 EXPORT_SYMBOL_GPL(gpiochip_irq_domain_deactivate);
2273 static int gpiochip_to_irq(struct gpio_chip *chip, unsigned offset)
2275 struct irq_domain *domain = chip->irq.domain;
2277 if (!gpiochip_irqchip_irq_valid(chip, offset))
2280 #ifdef CONFIG_IRQ_DOMAIN_HIERARCHY
2281 if (irq_domain_is_hierarchy(domain)) {
2282 struct irq_fwspec spec;
2284 spec.fwnode = domain->fwnode;
2285 spec.param_count = 2;
2286 spec.param[0] = chip->irq.child_offset_to_irq(chip, offset);
2287 spec.param[1] = IRQ_TYPE_NONE;
2289 return irq_create_fwspec_mapping(&spec);
2293 return irq_create_mapping(domain, offset);
2296 static int gpiochip_irq_reqres(struct irq_data *d)
2298 struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
2300 return gpiochip_reqres_irq(chip, d->hwirq);
2303 static void gpiochip_irq_relres(struct irq_data *d)
2305 struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
2307 gpiochip_relres_irq(chip, d->hwirq);
2310 static void gpiochip_irq_enable(struct irq_data *d)
2312 struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
2314 gpiochip_enable_irq(chip, d->hwirq);
2315 if (chip->irq.irq_enable)
2316 chip->irq.irq_enable(d);
2318 chip->irq.chip->irq_unmask(d);
2321 static void gpiochip_irq_disable(struct irq_data *d)
2323 struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
2325 if (chip->irq.irq_disable)
2326 chip->irq.irq_disable(d);
2328 chip->irq.chip->irq_mask(d);
2329 gpiochip_disable_irq(chip, d->hwirq);
2332 static void gpiochip_set_irq_hooks(struct gpio_chip *gpiochip)
2334 struct irq_chip *irqchip = gpiochip->irq.chip;
2336 if (!irqchip->irq_request_resources &&
2337 !irqchip->irq_release_resources) {
2338 irqchip->irq_request_resources = gpiochip_irq_reqres;
2339 irqchip->irq_release_resources = gpiochip_irq_relres;
2341 if (WARN_ON(gpiochip->irq.irq_enable))
2343 /* Check if the irqchip already has this hook... */
2344 if (irqchip->irq_enable == gpiochip_irq_enable) {
2346 * ...and if so, give a gentle warning that this is bad
2350 "detected irqchip that is shared with multiple gpiochips: please fix the driver.\n");
2353 gpiochip->irq.irq_enable = irqchip->irq_enable;
2354 gpiochip->irq.irq_disable = irqchip->irq_disable;
2355 irqchip->irq_enable = gpiochip_irq_enable;
2356 irqchip->irq_disable = gpiochip_irq_disable;
2360 * gpiochip_add_irqchip() - adds an IRQ chip to a GPIO chip
2361 * @gpiochip: the GPIO chip to add the IRQ chip to
2362 * @lock_key: lockdep class for IRQ lock
2363 * @request_key: lockdep class for IRQ request
2365 static int gpiochip_add_irqchip(struct gpio_chip *gpiochip,
2366 struct lock_class_key *lock_key,
2367 struct lock_class_key *request_key)
2369 struct irq_chip *irqchip = gpiochip->irq.chip;
2370 const struct irq_domain_ops *ops = NULL;
2371 struct device_node *np;
2378 if (gpiochip->irq.parent_handler && gpiochip->can_sleep) {
2379 chip_err(gpiochip, "you cannot have chained interrupts on a chip that may sleep\n");
2383 np = gpiochip->gpiodev->dev.of_node;
2384 type = gpiochip->irq.default_type;
2387 * Specifying a default trigger is a terrible idea if DT or ACPI is
2388 * used to configure the interrupts, as you may end up with
2389 * conflicting triggers. Tell the user, and reset to NONE.
2391 if (WARN(np && type != IRQ_TYPE_NONE,
2392 "%s: Ignoring %u default trigger\n", np->full_name, type))
2393 type = IRQ_TYPE_NONE;
2395 if (has_acpi_companion(gpiochip->parent) && type != IRQ_TYPE_NONE) {
2396 acpi_handle_warn(ACPI_HANDLE(gpiochip->parent),
2397 "Ignoring %u default trigger\n", type);
2398 type = IRQ_TYPE_NONE;
2401 gpiochip->to_irq = gpiochip_to_irq;
2402 gpiochip->irq.default_type = type;
2403 gpiochip->irq.lock_key = lock_key;
2404 gpiochip->irq.request_key = request_key;
2406 /* If a parent irqdomain is provided, let's build a hierarchy */
2407 if (gpiochip_hierarchy_is_hierarchical(gpiochip)) {
2408 int ret = gpiochip_hierarchy_add_domain(gpiochip);
2412 /* Some drivers provide custom irqdomain ops */
2413 if (gpiochip->irq.domain_ops)
2414 ops = gpiochip->irq.domain_ops;
2417 ops = &gpiochip_domain_ops;
2418 gpiochip->irq.domain = irq_domain_add_simple(np,
2420 gpiochip->irq.first,
2422 if (!gpiochip->irq.domain)
2426 if (gpiochip->irq.parent_handler) {
2427 void *data = gpiochip->irq.parent_handler_data ?: gpiochip;
2429 for (i = 0; i < gpiochip->irq.num_parents; i++) {
2431 * The parent IRQ chip is already using the chip_data
2432 * for this IRQ chip, so our callbacks simply use the
2435 irq_set_chained_handler_and_data(gpiochip->irq.parents[i],
2436 gpiochip->irq.parent_handler,
2441 gpiochip_set_irq_hooks(gpiochip);
2443 acpi_gpiochip_request_interrupts(gpiochip);
2449 * gpiochip_irqchip_remove() - removes an irqchip added to a gpiochip
2450 * @gpiochip: the gpiochip to remove the irqchip from
2452 * This is called only from gpiochip_remove()
2454 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip)
2456 struct irq_chip *irqchip = gpiochip->irq.chip;
2457 unsigned int offset;
2459 acpi_gpiochip_free_interrupts(gpiochip);
2461 if (irqchip && gpiochip->irq.parent_handler) {
2462 struct gpio_irq_chip *irq = &gpiochip->irq;
2465 for (i = 0; i < irq->num_parents; i++)
2466 irq_set_chained_handler_and_data(irq->parents[i],
2470 /* Remove all IRQ mappings and delete the domain */
2471 if (gpiochip->irq.domain) {
2474 for (offset = 0; offset < gpiochip->ngpio; offset++) {
2475 if (!gpiochip_irqchip_irq_valid(gpiochip, offset))
2478 irq = irq_find_mapping(gpiochip->irq.domain, offset);
2479 irq_dispose_mapping(irq);
2482 irq_domain_remove(gpiochip->irq.domain);
2486 if (irqchip->irq_request_resources == gpiochip_irq_reqres) {
2487 irqchip->irq_request_resources = NULL;
2488 irqchip->irq_release_resources = NULL;
2490 if (irqchip->irq_enable == gpiochip_irq_enable) {
2491 irqchip->irq_enable = gpiochip->irq.irq_enable;
2492 irqchip->irq_disable = gpiochip->irq.irq_disable;
2495 gpiochip->irq.irq_enable = NULL;
2496 gpiochip->irq.irq_disable = NULL;
2497 gpiochip->irq.chip = NULL;
2499 gpiochip_irqchip_free_valid_mask(gpiochip);
2503 * gpiochip_irqchip_add_key() - adds an irqchip to a gpiochip
2504 * @gpiochip: the gpiochip to add the irqchip to
2505 * @irqchip: the irqchip to add to the gpiochip
2506 * @first_irq: if not dynamically assigned, the base (first) IRQ to
2507 * allocate gpiochip irqs from
2508 * @handler: the irq handler to use (often a predefined irq core function)
2509 * @type: the default type for IRQs on this irqchip, pass IRQ_TYPE_NONE
2510 * to have the core avoid setting up any default type in the hardware.
2511 * @threaded: whether this irqchip uses a nested thread handler
2512 * @lock_key: lockdep class for IRQ lock
2513 * @request_key: lockdep class for IRQ request
2515 * This function closely associates a certain irqchip with a certain
2516 * gpiochip, providing an irq domain to translate the local IRQs to
2517 * global irqs in the gpiolib core, and making sure that the gpiochip
2518 * is passed as chip data to all related functions. Driver callbacks
2519 * need to use gpiochip_get_data() to get their local state containers back
2520 * from the gpiochip passed as chip data. An irqdomain will be stored
2521 * in the gpiochip that shall be used by the driver to handle IRQ number
2522 * translation. The gpiochip will need to be initialized and registered
2523 * before calling this function.
2525 * This function will handle two cell:ed simple IRQs and assumes all
2526 * the pins on the gpiochip can generate a unique IRQ. Everything else
2527 * need to be open coded.
2529 int gpiochip_irqchip_add_key(struct gpio_chip *gpiochip,
2530 struct irq_chip *irqchip,
2531 unsigned int first_irq,
2532 irq_flow_handler_t handler,
2535 struct lock_class_key *lock_key,
2536 struct lock_class_key *request_key)
2538 struct device_node *of_node;
2540 if (!gpiochip || !irqchip)
2543 if (!gpiochip->parent) {
2544 pr_err("missing gpiochip .dev parent pointer\n");
2547 gpiochip->irq.threaded = threaded;
2548 of_node = gpiochip->parent->of_node;
2549 #ifdef CONFIG_OF_GPIO
2551 * If the gpiochip has an assigned OF node this takes precedence
2552 * FIXME: get rid of this and use gpiochip->parent->of_node
2555 if (gpiochip->of_node)
2556 of_node = gpiochip->of_node;
2559 * Specifying a default trigger is a terrible idea if DT or ACPI is
2560 * used to configure the interrupts, as you may end-up with
2561 * conflicting triggers. Tell the user, and reset to NONE.
2563 if (WARN(of_node && type != IRQ_TYPE_NONE,
2564 "%pOF: Ignoring %d default trigger\n", of_node, type))
2565 type = IRQ_TYPE_NONE;
2566 if (has_acpi_companion(gpiochip->parent) && type != IRQ_TYPE_NONE) {
2567 acpi_handle_warn(ACPI_HANDLE(gpiochip->parent),
2568 "Ignoring %d default trigger\n", type);
2569 type = IRQ_TYPE_NONE;
2572 gpiochip->irq.chip = irqchip;
2573 gpiochip->irq.handler = handler;
2574 gpiochip->irq.default_type = type;
2575 gpiochip->to_irq = gpiochip_to_irq;
2576 gpiochip->irq.lock_key = lock_key;
2577 gpiochip->irq.request_key = request_key;
2578 gpiochip->irq.domain = irq_domain_add_simple(of_node,
2579 gpiochip->ngpio, first_irq,
2580 &gpiochip_domain_ops, gpiochip);
2581 if (!gpiochip->irq.domain) {
2582 gpiochip->irq.chip = NULL;
2586 gpiochip_set_irq_hooks(gpiochip);
2588 acpi_gpiochip_request_interrupts(gpiochip);
2592 EXPORT_SYMBOL_GPL(gpiochip_irqchip_add_key);
2594 #else /* CONFIG_GPIOLIB_IRQCHIP */
2596 static inline int gpiochip_add_irqchip(struct gpio_chip *gpiochip,
2597 struct lock_class_key *lock_key,
2598 struct lock_class_key *request_key)
2602 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip) {}
2604 static inline int gpiochip_irqchip_init_hw(struct gpio_chip *gpiochip)
2609 static inline int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gpiochip)
2613 static inline void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gpiochip)
2616 #endif /* CONFIG_GPIOLIB_IRQCHIP */
2619 * gpiochip_generic_request() - request the gpio function for a pin
2620 * @chip: the gpiochip owning the GPIO
2621 * @offset: the offset of the GPIO to request for GPIO function
2623 int gpiochip_generic_request(struct gpio_chip *chip, unsigned offset)
2625 return pinctrl_gpio_request(chip->gpiodev->base + offset);
2627 EXPORT_SYMBOL_GPL(gpiochip_generic_request);
2630 * gpiochip_generic_free() - free the gpio function from a pin
2631 * @chip: the gpiochip to request the gpio function for
2632 * @offset: the offset of the GPIO to free from GPIO function
2634 void gpiochip_generic_free(struct gpio_chip *chip, unsigned offset)
2636 pinctrl_gpio_free(chip->gpiodev->base + offset);
2638 EXPORT_SYMBOL_GPL(gpiochip_generic_free);
2641 * gpiochip_generic_config() - apply configuration for a pin
2642 * @chip: the gpiochip owning the GPIO
2643 * @offset: the offset of the GPIO to apply the configuration
2644 * @config: the configuration to be applied
2646 int gpiochip_generic_config(struct gpio_chip *chip, unsigned offset,
2647 unsigned long config)
2649 return pinctrl_gpio_set_config(chip->gpiodev->base + offset, config);
2651 EXPORT_SYMBOL_GPL(gpiochip_generic_config);
2653 #ifdef CONFIG_PINCTRL
2656 * gpiochip_add_pingroup_range() - add a range for GPIO <-> pin mapping
2657 * @chip: the gpiochip to add the range for
2658 * @pctldev: the pin controller to map to
2659 * @gpio_offset: the start offset in the current gpio_chip number space
2660 * @pin_group: name of the pin group inside the pin controller
2662 * Calling this function directly from a DeviceTree-supported
2663 * pinctrl driver is DEPRECATED. Please see Section 2.1 of
2664 * Documentation/devicetree/bindings/gpio/gpio.txt on how to
2665 * bind pinctrl and gpio drivers via the "gpio-ranges" property.
2667 int gpiochip_add_pingroup_range(struct gpio_chip *chip,
2668 struct pinctrl_dev *pctldev,
2669 unsigned int gpio_offset, const char *pin_group)
2671 struct gpio_pin_range *pin_range;
2672 struct gpio_device *gdev = chip->gpiodev;
2675 pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
2677 chip_err(chip, "failed to allocate pin ranges\n");
2681 /* Use local offset as range ID */
2682 pin_range->range.id = gpio_offset;
2683 pin_range->range.gc = chip;
2684 pin_range->range.name = chip->label;
2685 pin_range->range.base = gdev->base + gpio_offset;
2686 pin_range->pctldev = pctldev;
2688 ret = pinctrl_get_group_pins(pctldev, pin_group,
2689 &pin_range->range.pins,
2690 &pin_range->range.npins);
2696 pinctrl_add_gpio_range(pctldev, &pin_range->range);
2698 chip_dbg(chip, "created GPIO range %d->%d ==> %s PINGRP %s\n",
2699 gpio_offset, gpio_offset + pin_range->range.npins - 1,
2700 pinctrl_dev_get_devname(pctldev), pin_group);
2702 list_add_tail(&pin_range->node, &gdev->pin_ranges);
2706 EXPORT_SYMBOL_GPL(gpiochip_add_pingroup_range);
2709 * gpiochip_add_pin_range() - add a range for GPIO <-> pin mapping
2710 * @chip: the gpiochip to add the range for
2711 * @pinctl_name: the dev_name() of the pin controller to map to
2712 * @gpio_offset: the start offset in the current gpio_chip number space
2713 * @pin_offset: the start offset in the pin controller number space
2714 * @npins: the number of pins from the offset of each pin space (GPIO and
2715 * pin controller) to accumulate in this range
2718 * 0 on success, or a negative error-code on failure.
2720 * Calling this function directly from a DeviceTree-supported
2721 * pinctrl driver is DEPRECATED. Please see Section 2.1 of
2722 * Documentation/devicetree/bindings/gpio/gpio.txt on how to
2723 * bind pinctrl and gpio drivers via the "gpio-ranges" property.
2725 int gpiochip_add_pin_range(struct gpio_chip *chip, const char *pinctl_name,
2726 unsigned int gpio_offset, unsigned int pin_offset,
2729 struct gpio_pin_range *pin_range;
2730 struct gpio_device *gdev = chip->gpiodev;
2733 pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
2735 chip_err(chip, "failed to allocate pin ranges\n");
2739 /* Use local offset as range ID */
2740 pin_range->range.id = gpio_offset;
2741 pin_range->range.gc = chip;
2742 pin_range->range.name = chip->label;
2743 pin_range->range.base = gdev->base + gpio_offset;
2744 pin_range->range.pin_base = pin_offset;
2745 pin_range->range.npins = npins;
2746 pin_range->pctldev = pinctrl_find_and_add_gpio_range(pinctl_name,
2748 if (IS_ERR(pin_range->pctldev)) {
2749 ret = PTR_ERR(pin_range->pctldev);
2750 chip_err(chip, "could not create pin range\n");
2754 chip_dbg(chip, "created GPIO range %d->%d ==> %s PIN %d->%d\n",
2755 gpio_offset, gpio_offset + npins - 1,
2757 pin_offset, pin_offset + npins - 1);
2759 list_add_tail(&pin_range->node, &gdev->pin_ranges);
2763 EXPORT_SYMBOL_GPL(gpiochip_add_pin_range);
2766 * gpiochip_remove_pin_ranges() - remove all the GPIO <-> pin mappings
2767 * @chip: the chip to remove all the mappings for
2769 void gpiochip_remove_pin_ranges(struct gpio_chip *chip)
2771 struct gpio_pin_range *pin_range, *tmp;
2772 struct gpio_device *gdev = chip->gpiodev;
2774 list_for_each_entry_safe(pin_range, tmp, &gdev->pin_ranges, node) {
2775 list_del(&pin_range->node);
2776 pinctrl_remove_gpio_range(pin_range->pctldev,
2781 EXPORT_SYMBOL_GPL(gpiochip_remove_pin_ranges);
2783 #endif /* CONFIG_PINCTRL */
2785 /* These "optional" allocation calls help prevent drivers from stomping
2786 * on each other, and help provide better diagnostics in debugfs.
2787 * They're called even less than the "set direction" calls.
2789 static int gpiod_request_commit(struct gpio_desc *desc, const char *label)
2791 struct gpio_chip *chip = desc->gdev->chip;
2793 unsigned long flags;
2797 label = kstrdup_const(label, GFP_KERNEL);
2802 spin_lock_irqsave(&gpio_lock, flags);
2804 /* NOTE: gpio_request() can be called in early boot,
2805 * before IRQs are enabled, for non-sleeping (SOC) GPIOs.
2808 if (test_and_set_bit(FLAG_REQUESTED, &desc->flags) == 0) {
2809 desc_set_label(desc, label ? : "?");
2817 if (chip->request) {
2818 /* chip->request may sleep */
2819 spin_unlock_irqrestore(&gpio_lock, flags);
2820 offset = gpio_chip_hwgpio(desc);
2821 if (gpiochip_line_is_valid(chip, offset))
2822 ret = chip->request(chip, offset);
2825 spin_lock_irqsave(&gpio_lock, flags);
2828 desc_set_label(desc, NULL);
2830 clear_bit(FLAG_REQUESTED, &desc->flags);
2834 if (chip->get_direction) {
2835 /* chip->get_direction may sleep */
2836 spin_unlock_irqrestore(&gpio_lock, flags);
2837 gpiod_get_direction(desc);
2838 spin_lock_irqsave(&gpio_lock, flags);
2841 spin_unlock_irqrestore(&gpio_lock, flags);
2846 * This descriptor validation needs to be inserted verbatim into each
2847 * function taking a descriptor, so we need to use a preprocessor
2848 * macro to avoid endless duplication. If the desc is NULL it is an
2849 * optional GPIO and calls should just bail out.
2851 static int validate_desc(const struct gpio_desc *desc, const char *func)
2856 pr_warn("%s: invalid GPIO (errorpointer)\n", func);
2857 return PTR_ERR(desc);
2860 pr_warn("%s: invalid GPIO (no device)\n", func);
2863 if (!desc->gdev->chip) {
2864 dev_warn(&desc->gdev->dev,
2865 "%s: backing chip is gone\n", func);
2871 #define VALIDATE_DESC(desc) do { \
2872 int __valid = validate_desc(desc, __func__); \
2877 #define VALIDATE_DESC_VOID(desc) do { \
2878 int __valid = validate_desc(desc, __func__); \
2883 int gpiod_request(struct gpio_desc *desc, const char *label)
2885 int ret = -EPROBE_DEFER;
2886 struct gpio_device *gdev;
2888 VALIDATE_DESC(desc);
2891 if (try_module_get(gdev->owner)) {
2892 ret = gpiod_request_commit(desc, label);
2894 module_put(gdev->owner);
2896 get_device(&gdev->dev);
2900 gpiod_dbg(desc, "%s: status %d\n", __func__, ret);
2905 static bool gpiod_free_commit(struct gpio_desc *desc)
2908 unsigned long flags;
2909 struct gpio_chip *chip;
2913 gpiod_unexport(desc);
2915 spin_lock_irqsave(&gpio_lock, flags);
2917 chip = desc->gdev->chip;
2918 if (chip && test_bit(FLAG_REQUESTED, &desc->flags)) {
2920 spin_unlock_irqrestore(&gpio_lock, flags);
2921 might_sleep_if(chip->can_sleep);
2922 chip->free(chip, gpio_chip_hwgpio(desc));
2923 spin_lock_irqsave(&gpio_lock, flags);
2925 kfree_const(desc->label);
2926 desc_set_label(desc, NULL);
2927 clear_bit(FLAG_ACTIVE_LOW, &desc->flags);
2928 clear_bit(FLAG_REQUESTED, &desc->flags);
2929 clear_bit(FLAG_OPEN_DRAIN, &desc->flags);
2930 clear_bit(FLAG_OPEN_SOURCE, &desc->flags);
2931 clear_bit(FLAG_PULL_UP, &desc->flags);
2932 clear_bit(FLAG_PULL_DOWN, &desc->flags);
2933 clear_bit(FLAG_BIAS_DISABLE, &desc->flags);
2934 clear_bit(FLAG_IS_HOGGED, &desc->flags);
2938 spin_unlock_irqrestore(&gpio_lock, flags);
2942 void gpiod_free(struct gpio_desc *desc)
2944 if (desc && desc->gdev && gpiod_free_commit(desc)) {
2945 module_put(desc->gdev->owner);
2946 put_device(&desc->gdev->dev);
2948 WARN_ON(extra_checks);
2953 * gpiochip_is_requested - return string iff signal was requested
2954 * @chip: controller managing the signal
2955 * @offset: of signal within controller's 0..(ngpio - 1) range
2957 * Returns NULL if the GPIO is not currently requested, else a string.
2958 * The string returned is the label passed to gpio_request(); if none has been
2959 * passed it is a meaningless, non-NULL constant.
2961 * This function is for use by GPIO controller drivers. The label can
2962 * help with diagnostics, and knowing that the signal is used as a GPIO
2963 * can help avoid accidentally multiplexing it to another controller.
2965 const char *gpiochip_is_requested(struct gpio_chip *chip, unsigned offset)
2967 struct gpio_desc *desc;
2969 if (offset >= chip->ngpio)
2972 desc = &chip->gpiodev->descs[offset];
2974 if (test_bit(FLAG_REQUESTED, &desc->flags) == 0)
2978 EXPORT_SYMBOL_GPL(gpiochip_is_requested);
2981 * gpiochip_request_own_desc - Allow GPIO chip to request its own descriptor
2983 * @hwnum: hardware number of the GPIO for which to request the descriptor
2984 * @label: label for the GPIO
2985 * @lflags: lookup flags for this GPIO or 0 if default, this can be used to
2986 * specify things like line inversion semantics with the machine flags
2987 * such as GPIO_OUT_LOW
2988 * @dflags: descriptor request flags for this GPIO or 0 if default, this
2989 * can be used to specify consumer semantics such as open drain
2991 * Function allows GPIO chip drivers to request and use their own GPIO
2992 * descriptors via gpiolib API. Difference to gpiod_request() is that this
2993 * function will not increase reference count of the GPIO chip module. This
2994 * allows the GPIO chip module to be unloaded as needed (we assume that the
2995 * GPIO chip driver handles freeing the GPIOs it has requested).
2998 * A pointer to the GPIO descriptor, or an ERR_PTR()-encoded negative error
3001 struct gpio_desc *gpiochip_request_own_desc(struct gpio_chip *chip, u16 hwnum,
3003 enum gpio_lookup_flags lflags,
3004 enum gpiod_flags dflags)
3006 struct gpio_desc *desc = gpiochip_get_desc(chip, hwnum);
3010 chip_err(chip, "failed to get GPIO descriptor\n");
3014 ret = gpiod_request_commit(desc, label);
3016 return ERR_PTR(ret);
3018 ret = gpiod_configure_flags(desc, label, lflags, dflags);
3020 chip_err(chip, "setup of own GPIO %s failed\n", label);
3021 gpiod_free_commit(desc);
3022 return ERR_PTR(ret);
3027 EXPORT_SYMBOL_GPL(gpiochip_request_own_desc);
3030 * gpiochip_free_own_desc - Free GPIO requested by the chip driver
3031 * @desc: GPIO descriptor to free
3033 * Function frees the given GPIO requested previously with
3034 * gpiochip_request_own_desc().
3036 void gpiochip_free_own_desc(struct gpio_desc *desc)
3039 gpiod_free_commit(desc);
3041 EXPORT_SYMBOL_GPL(gpiochip_free_own_desc);
3044 * Drivers MUST set GPIO direction before making get/set calls. In
3045 * some cases this is done in early boot, before IRQs are enabled.
3047 * As a rule these aren't called more than once (except for drivers
3048 * using the open-drain emulation idiom) so these are natural places
3049 * to accumulate extra debugging checks. Note that we can't (yet)
3050 * rely on gpio_request() having been called beforehand.
3053 static int gpio_set_config(struct gpio_chip *gc, unsigned offset,
3054 enum pin_config_param mode)
3056 unsigned long config;
3060 case PIN_CONFIG_BIAS_DISABLE:
3061 case PIN_CONFIG_BIAS_PULL_DOWN:
3062 case PIN_CONFIG_BIAS_PULL_UP:
3070 config = PIN_CONF_PACKED(mode, arg);
3071 return gc->set_config ? gc->set_config(gc, offset, config) : -ENOTSUPP;
3074 static int gpio_set_bias(struct gpio_chip *chip, struct gpio_desc *desc)
3079 if (test_bit(FLAG_BIAS_DISABLE, &desc->flags))
3080 bias = PIN_CONFIG_BIAS_DISABLE;
3081 else if (test_bit(FLAG_PULL_UP, &desc->flags))
3082 bias = PIN_CONFIG_BIAS_PULL_UP;
3083 else if (test_bit(FLAG_PULL_DOWN, &desc->flags))
3084 bias = PIN_CONFIG_BIAS_PULL_DOWN;
3087 ret = gpio_set_config(chip, gpio_chip_hwgpio(desc), bias);
3088 if (ret != -ENOTSUPP)
3095 * gpiod_direction_input - set the GPIO direction to input
3096 * @desc: GPIO to set to input
3098 * Set the direction of the passed GPIO to input, such as gpiod_get_value() can
3099 * be called safely on it.
3101 * Return 0 in case of success, else an error code.
3103 int gpiod_direction_input(struct gpio_desc *desc)
3105 struct gpio_chip *chip;
3108 VALIDATE_DESC(desc);
3109 chip = desc->gdev->chip;
3112 * It is legal to have no .get() and .direction_input() specified if
3113 * the chip is output-only, but you can't specify .direction_input()
3114 * and not support the .get() operation, that doesn't make sense.
3116 if (!chip->get && chip->direction_input) {
3118 "%s: missing get() but have direction_input()\n",
3124 * If we have a .direction_input() callback, things are simple,
3125 * just call it. Else we are some input-only chip so try to check the
3126 * direction (if .get_direction() is supported) else we silently
3127 * assume we are in input mode after this.
3129 if (chip->direction_input) {
3130 ret = chip->direction_input(chip, gpio_chip_hwgpio(desc));
3131 } else if (chip->get_direction &&
3132 (chip->get_direction(chip, gpio_chip_hwgpio(desc)) != 1)) {
3134 "%s: missing direction_input() operation and line is output\n",
3139 clear_bit(FLAG_IS_OUT, &desc->flags);
3140 ret = gpio_set_bias(chip, desc);
3143 trace_gpio_direction(desc_to_gpio(desc), 1, ret);
3147 EXPORT_SYMBOL_GPL(gpiod_direction_input);
3149 static int gpiod_direction_output_raw_commit(struct gpio_desc *desc, int value)
3151 struct gpio_chip *gc = desc->gdev->chip;
3156 * It's OK not to specify .direction_output() if the gpiochip is
3157 * output-only, but if there is then not even a .set() operation it
3158 * is pretty tricky to drive the output line.
3160 if (!gc->set && !gc->direction_output) {
3162 "%s: missing set() and direction_output() operations\n",
3167 if (gc->direction_output) {
3168 ret = gc->direction_output(gc, gpio_chip_hwgpio(desc), val);
3170 /* Check that we are in output mode if we can */
3171 if (gc->get_direction &&
3172 gc->get_direction(gc, gpio_chip_hwgpio(desc))) {
3174 "%s: missing direction_output() operation\n",
3179 * If we can't actively set the direction, we are some
3180 * output-only chip, so just drive the output as desired.
3182 gc->set(gc, gpio_chip_hwgpio(desc), val);
3186 set_bit(FLAG_IS_OUT, &desc->flags);
3187 trace_gpio_value(desc_to_gpio(desc), 0, val);
3188 trace_gpio_direction(desc_to_gpio(desc), 0, ret);
3193 * gpiod_direction_output_raw - set the GPIO direction to output
3194 * @desc: GPIO to set to output
3195 * @value: initial output value of the GPIO
3197 * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
3198 * be called safely on it. The initial value of the output must be specified
3199 * as raw value on the physical line without regard for the ACTIVE_LOW status.
3201 * Return 0 in case of success, else an error code.
3203 int gpiod_direction_output_raw(struct gpio_desc *desc, int value)
3205 VALIDATE_DESC(desc);
3206 return gpiod_direction_output_raw_commit(desc, value);
3208 EXPORT_SYMBOL_GPL(gpiod_direction_output_raw);
3211 * gpiod_direction_output - set the GPIO direction to output
3212 * @desc: GPIO to set to output
3213 * @value: initial output value of the GPIO
3215 * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
3216 * be called safely on it. The initial value of the output must be specified
3217 * as the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
3220 * Return 0 in case of success, else an error code.
3222 int gpiod_direction_output(struct gpio_desc *desc, int value)
3224 struct gpio_chip *gc;
3227 VALIDATE_DESC(desc);
3228 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3233 /* GPIOs used for enabled IRQs shall not be set as output */
3234 if (test_bit(FLAG_USED_AS_IRQ, &desc->flags) &&
3235 test_bit(FLAG_IRQ_IS_ENABLED, &desc->flags)) {
3237 "%s: tried to set a GPIO tied to an IRQ as output\n",
3242 gc = desc->gdev->chip;
3243 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags)) {
3244 /* First see if we can enable open drain in hardware */
3245 ret = gpio_set_config(gc, gpio_chip_hwgpio(desc),
3246 PIN_CONFIG_DRIVE_OPEN_DRAIN);
3248 goto set_output_value;
3249 /* Emulate open drain by not actively driving the line high */
3251 ret = gpiod_direction_input(desc);
3252 goto set_output_flag;
3255 else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags)) {
3256 ret = gpio_set_config(gc, gpio_chip_hwgpio(desc),
3257 PIN_CONFIG_DRIVE_OPEN_SOURCE);
3259 goto set_output_value;
3260 /* Emulate open source by not actively driving the line low */
3262 ret = gpiod_direction_input(desc);
3263 goto set_output_flag;
3266 gpio_set_config(gc, gpio_chip_hwgpio(desc),
3267 PIN_CONFIG_DRIVE_PUSH_PULL);
3271 ret = gpio_set_bias(gc, desc);
3274 return gpiod_direction_output_raw_commit(desc, value);
3278 * When emulating open-source or open-drain functionalities by not
3279 * actively driving the line (setting mode to input) we still need to
3280 * set the IS_OUT flag or otherwise we won't be able to set the line
3284 set_bit(FLAG_IS_OUT, &desc->flags);
3287 EXPORT_SYMBOL_GPL(gpiod_direction_output);
3290 * gpiod_set_debounce - sets @debounce time for a GPIO
3291 * @desc: descriptor of the GPIO for which to set debounce time
3292 * @debounce: debounce time in microseconds
3295 * 0 on success, %-ENOTSUPP if the controller doesn't support setting the
3298 int gpiod_set_debounce(struct gpio_desc *desc, unsigned debounce)
3300 struct gpio_chip *chip;
3301 unsigned long config;
3303 VALIDATE_DESC(desc);
3304 chip = desc->gdev->chip;
3305 if (!chip->set || !chip->set_config) {
3307 "%s: missing set() or set_config() operations\n",
3312 config = pinconf_to_config_packed(PIN_CONFIG_INPUT_DEBOUNCE, debounce);
3313 return chip->set_config(chip, gpio_chip_hwgpio(desc), config);
3315 EXPORT_SYMBOL_GPL(gpiod_set_debounce);
3318 * gpiod_set_transitory - Lose or retain GPIO state on suspend or reset
3319 * @desc: descriptor of the GPIO for which to configure persistence
3320 * @transitory: True to lose state on suspend or reset, false for persistence
3323 * 0 on success, otherwise a negative error code.
3325 int gpiod_set_transitory(struct gpio_desc *desc, bool transitory)
3327 struct gpio_chip *chip;
3328 unsigned long packed;
3332 VALIDATE_DESC(desc);
3334 * Handle FLAG_TRANSITORY first, enabling queries to gpiolib for
3335 * persistence state.
3338 set_bit(FLAG_TRANSITORY, &desc->flags);
3340 clear_bit(FLAG_TRANSITORY, &desc->flags);
3342 /* If the driver supports it, set the persistence state now */
3343 chip = desc->gdev->chip;
3344 if (!chip->set_config)
3347 packed = pinconf_to_config_packed(PIN_CONFIG_PERSIST_STATE,
3349 gpio = gpio_chip_hwgpio(desc);
3350 rc = chip->set_config(chip, gpio, packed);
3351 if (rc == -ENOTSUPP) {
3352 dev_dbg(&desc->gdev->dev, "Persistence not supported for GPIO %d\n",
3359 EXPORT_SYMBOL_GPL(gpiod_set_transitory);
3362 * gpiod_is_active_low - test whether a GPIO is active-low or not
3363 * @desc: the gpio descriptor to test
3365 * Returns 1 if the GPIO is active-low, 0 otherwise.
3367 int gpiod_is_active_low(const struct gpio_desc *desc)
3369 VALIDATE_DESC(desc);
3370 return test_bit(FLAG_ACTIVE_LOW, &desc->flags);
3372 EXPORT_SYMBOL_GPL(gpiod_is_active_low);
3375 * gpiod_toggle_active_low - toggle whether a GPIO is active-low or not
3376 * @desc: the gpio descriptor to change
3378 void gpiod_toggle_active_low(struct gpio_desc *desc)
3380 VALIDATE_DESC_VOID(desc);
3381 change_bit(FLAG_ACTIVE_LOW, &desc->flags);
3383 EXPORT_SYMBOL_GPL(gpiod_toggle_active_low);
3385 /* I/O calls are only valid after configuration completed; the relevant
3386 * "is this a valid GPIO" error checks should already have been done.
3388 * "Get" operations are often inlinable as reading a pin value register,
3389 * and masking the relevant bit in that register.
3391 * When "set" operations are inlinable, they involve writing that mask to
3392 * one register to set a low value, or a different register to set it high.
3393 * Otherwise locking is needed, so there may be little value to inlining.
3395 *------------------------------------------------------------------------
3397 * IMPORTANT!!! The hot paths -- get/set value -- assume that callers
3398 * have requested the GPIO. That can include implicit requesting by
3399 * a direction setting call. Marking a gpio as requested locks its chip
3400 * in memory, guaranteeing that these table lookups need no more locking
3401 * and that gpiochip_remove() will fail.
3403 * REVISIT when debugging, consider adding some instrumentation to ensure
3404 * that the GPIO was actually requested.
3407 static int gpiod_get_raw_value_commit(const struct gpio_desc *desc)
3409 struct gpio_chip *chip;
3413 chip = desc->gdev->chip;
3414 offset = gpio_chip_hwgpio(desc);
3415 value = chip->get ? chip->get(chip, offset) : -EIO;
3416 value = value < 0 ? value : !!value;
3417 trace_gpio_value(desc_to_gpio(desc), 1, value);
3421 static int gpio_chip_get_multiple(struct gpio_chip *chip,
3422 unsigned long *mask, unsigned long *bits)
3424 if (chip->get_multiple) {
3425 return chip->get_multiple(chip, mask, bits);
3426 } else if (chip->get) {
3429 for_each_set_bit(i, mask, chip->ngpio) {
3430 value = chip->get(chip, i);
3433 __assign_bit(i, bits, value);
3440 int gpiod_get_array_value_complex(bool raw, bool can_sleep,
3441 unsigned int array_size,
3442 struct gpio_desc **desc_array,
3443 struct gpio_array *array_info,
3444 unsigned long *value_bitmap)
3449 * Validate array_info against desc_array and its size.
3450 * It should immediately follow desc_array if both
3451 * have been obtained from the same gpiod_get_array() call.
3453 if (array_info && array_info->desc == desc_array &&
3454 array_size <= array_info->size &&
3455 (void *)array_info == desc_array + array_info->size) {
3457 WARN_ON(array_info->chip->can_sleep);
3459 ret = gpio_chip_get_multiple(array_info->chip,
3460 array_info->get_mask,
3465 if (!raw && !bitmap_empty(array_info->invert_mask, array_size))
3466 bitmap_xor(value_bitmap, value_bitmap,
3467 array_info->invert_mask, array_size);
3469 if (bitmap_full(array_info->get_mask, array_size))
3472 i = find_first_zero_bit(array_info->get_mask, array_size);
3477 while (i < array_size) {
3478 struct gpio_chip *chip = desc_array[i]->gdev->chip;
3479 unsigned long fastpath[2 * BITS_TO_LONGS(FASTPATH_NGPIO)];
3480 unsigned long *mask, *bits;
3483 if (likely(chip->ngpio <= FASTPATH_NGPIO)) {
3486 mask = kmalloc_array(2 * BITS_TO_LONGS(chip->ngpio),
3488 can_sleep ? GFP_KERNEL : GFP_ATOMIC);
3493 bits = mask + BITS_TO_LONGS(chip->ngpio);
3494 bitmap_zero(mask, chip->ngpio);
3497 WARN_ON(chip->can_sleep);
3499 /* collect all inputs belonging to the same chip */
3502 const struct gpio_desc *desc = desc_array[i];
3503 int hwgpio = gpio_chip_hwgpio(desc);
3505 __set_bit(hwgpio, mask);
3509 i = find_next_zero_bit(array_info->get_mask,
3511 } while ((i < array_size) &&
3512 (desc_array[i]->gdev->chip == chip));
3514 ret = gpio_chip_get_multiple(chip, mask, bits);
3516 if (mask != fastpath)
3521 for (j = first; j < i; ) {
3522 const struct gpio_desc *desc = desc_array[j];
3523 int hwgpio = gpio_chip_hwgpio(desc);
3524 int value = test_bit(hwgpio, bits);
3526 if (!raw && test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3528 __assign_bit(j, value_bitmap, value);
3529 trace_gpio_value(desc_to_gpio(desc), 1, value);
3533 j = find_next_zero_bit(array_info->get_mask, i,
3537 if (mask != fastpath)
3544 * gpiod_get_raw_value() - return a gpio's raw value
3545 * @desc: gpio whose value will be returned
3547 * Return the GPIO's raw value, i.e. the value of the physical line disregarding
3548 * its ACTIVE_LOW status, or negative errno on failure.
3550 * This function can be called from contexts where we cannot sleep, and will
3551 * complain if the GPIO chip functions potentially sleep.
3553 int gpiod_get_raw_value(const struct gpio_desc *desc)
3555 VALIDATE_DESC(desc);
3556 /* Should be using gpiod_get_raw_value_cansleep() */
3557 WARN_ON(desc->gdev->chip->can_sleep);
3558 return gpiod_get_raw_value_commit(desc);
3560 EXPORT_SYMBOL_GPL(gpiod_get_raw_value);
3563 * gpiod_get_value() - return a gpio's value
3564 * @desc: gpio whose value will be returned
3566 * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
3567 * account, or negative errno on failure.
3569 * This function can be called from contexts where we cannot sleep, and will
3570 * complain if the GPIO chip functions potentially sleep.
3572 int gpiod_get_value(const struct gpio_desc *desc)
3576 VALIDATE_DESC(desc);
3577 /* Should be using gpiod_get_value_cansleep() */
3578 WARN_ON(desc->gdev->chip->can_sleep);
3580 value = gpiod_get_raw_value_commit(desc);
3584 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3589 EXPORT_SYMBOL_GPL(gpiod_get_value);
3592 * gpiod_get_raw_array_value() - read raw values from an array of GPIOs
3593 * @array_size: number of elements in the descriptor array / value bitmap
3594 * @desc_array: array of GPIO descriptors whose values will be read
3595 * @array_info: information on applicability of fast bitmap processing path
3596 * @value_bitmap: bitmap to store the read values
3598 * Read the raw values of the GPIOs, i.e. the values of the physical lines
3599 * without regard for their ACTIVE_LOW status. Return 0 in case of success,
3600 * else an error code.
3602 * This function can be called from contexts where we cannot sleep,
3603 * and it will complain if the GPIO chip functions potentially sleep.
3605 int gpiod_get_raw_array_value(unsigned int array_size,
3606 struct gpio_desc **desc_array,
3607 struct gpio_array *array_info,
3608 unsigned long *value_bitmap)
3612 return gpiod_get_array_value_complex(true, false, array_size,
3613 desc_array, array_info,
3616 EXPORT_SYMBOL_GPL(gpiod_get_raw_array_value);
3619 * gpiod_get_array_value() - read values from an array of GPIOs
3620 * @array_size: number of elements in the descriptor array / value bitmap
3621 * @desc_array: array of GPIO descriptors whose values will be read
3622 * @array_info: information on applicability of fast bitmap processing path
3623 * @value_bitmap: bitmap to store the read values
3625 * Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3626 * into account. Return 0 in case of success, else an error code.
3628 * This function can be called from contexts where we cannot sleep,
3629 * and it will complain if the GPIO chip functions potentially sleep.
3631 int gpiod_get_array_value(unsigned int array_size,
3632 struct gpio_desc **desc_array,
3633 struct gpio_array *array_info,
3634 unsigned long *value_bitmap)
3638 return gpiod_get_array_value_complex(false, false, array_size,
3639 desc_array, array_info,
3642 EXPORT_SYMBOL_GPL(gpiod_get_array_value);
3645 * gpio_set_open_drain_value_commit() - Set the open drain gpio's value.
3646 * @desc: gpio descriptor whose state need to be set.
3647 * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
3649 static void gpio_set_open_drain_value_commit(struct gpio_desc *desc, bool value)
3652 struct gpio_chip *chip = desc->gdev->chip;
3653 int offset = gpio_chip_hwgpio(desc);
3656 ret = chip->direction_input(chip, offset);
3658 ret = chip->direction_output(chip, offset, 0);
3660 set_bit(FLAG_IS_OUT, &desc->flags);
3662 trace_gpio_direction(desc_to_gpio(desc), value, ret);
3665 "%s: Error in set_value for open drain err %d\n",
3670 * _gpio_set_open_source_value() - Set the open source gpio's value.
3671 * @desc: gpio descriptor whose state need to be set.
3672 * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
3674 static void gpio_set_open_source_value_commit(struct gpio_desc *desc, bool value)
3677 struct gpio_chip *chip = desc->gdev->chip;
3678 int offset = gpio_chip_hwgpio(desc);
3681 ret = chip->direction_output(chip, offset, 1);
3683 set_bit(FLAG_IS_OUT, &desc->flags);
3685 ret = chip->direction_input(chip, offset);
3687 trace_gpio_direction(desc_to_gpio(desc), !value, ret);
3690 "%s: Error in set_value for open source err %d\n",
3694 static void gpiod_set_raw_value_commit(struct gpio_desc *desc, bool value)
3696 struct gpio_chip *chip;
3698 chip = desc->gdev->chip;
3699 trace_gpio_value(desc_to_gpio(desc), 0, value);
3700 chip->set(chip, gpio_chip_hwgpio(desc), value);
3704 * set multiple outputs on the same chip;
3705 * use the chip's set_multiple function if available;
3706 * otherwise set the outputs sequentially;
3707 * @mask: bit mask array; one bit per output; BITS_PER_LONG bits per word
3708 * defines which outputs are to be changed
3709 * @bits: bit value array; one bit per output; BITS_PER_LONG bits per word
3710 * defines the values the outputs specified by mask are to be set to
3712 static void gpio_chip_set_multiple(struct gpio_chip *chip,
3713 unsigned long *mask, unsigned long *bits)
3715 if (chip->set_multiple) {
3716 chip->set_multiple(chip, mask, bits);
3720 /* set outputs if the corresponding mask bit is set */
3721 for_each_set_bit(i, mask, chip->ngpio)
3722 chip->set(chip, i, test_bit(i, bits));
3726 int gpiod_set_array_value_complex(bool raw, bool can_sleep,
3727 unsigned int array_size,
3728 struct gpio_desc **desc_array,
3729 struct gpio_array *array_info,
3730 unsigned long *value_bitmap)
3735 * Validate array_info against desc_array and its size.
3736 * It should immediately follow desc_array if both
3737 * have been obtained from the same gpiod_get_array() call.
3739 if (array_info && array_info->desc == desc_array &&
3740 array_size <= array_info->size &&
3741 (void *)array_info == desc_array + array_info->size) {
3743 WARN_ON(array_info->chip->can_sleep);
3745 if (!raw && !bitmap_empty(array_info->invert_mask, array_size))
3746 bitmap_xor(value_bitmap, value_bitmap,
3747 array_info->invert_mask, array_size);
3749 gpio_chip_set_multiple(array_info->chip, array_info->set_mask,
3752 if (bitmap_full(array_info->set_mask, array_size))
3755 i = find_first_zero_bit(array_info->set_mask, array_size);
3760 while (i < array_size) {
3761 struct gpio_chip *chip = desc_array[i]->gdev->chip;
3762 unsigned long fastpath[2 * BITS_TO_LONGS(FASTPATH_NGPIO)];
3763 unsigned long *mask, *bits;
3766 if (likely(chip->ngpio <= FASTPATH_NGPIO)) {
3769 mask = kmalloc_array(2 * BITS_TO_LONGS(chip->ngpio),
3771 can_sleep ? GFP_KERNEL : GFP_ATOMIC);
3776 bits = mask + BITS_TO_LONGS(chip->ngpio);
3777 bitmap_zero(mask, chip->ngpio);
3780 WARN_ON(chip->can_sleep);
3783 struct gpio_desc *desc = desc_array[i];
3784 int hwgpio = gpio_chip_hwgpio(desc);
3785 int value = test_bit(i, value_bitmap);
3788 * Pins applicable for fast input but not for
3789 * fast output processing may have been already
3790 * inverted inside the fast path, skip them.
3792 if (!raw && !(array_info &&
3793 test_bit(i, array_info->invert_mask)) &&
3794 test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3796 trace_gpio_value(desc_to_gpio(desc), 0, value);
3798 * collect all normal outputs belonging to the same chip
3799 * open drain and open source outputs are set individually
3801 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags) && !raw) {
3802 gpio_set_open_drain_value_commit(desc, value);
3803 } else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags) && !raw) {
3804 gpio_set_open_source_value_commit(desc, value);
3806 __set_bit(hwgpio, mask);
3808 __set_bit(hwgpio, bits);
3810 __clear_bit(hwgpio, bits);
3816 i = find_next_zero_bit(array_info->set_mask,
3818 } while ((i < array_size) &&
3819 (desc_array[i]->gdev->chip == chip));
3820 /* push collected bits to outputs */
3822 gpio_chip_set_multiple(chip, mask, bits);
3824 if (mask != fastpath)
3831 * gpiod_set_raw_value() - assign a gpio's raw value
3832 * @desc: gpio whose value will be assigned
3833 * @value: value to assign
3835 * Set the raw value of the GPIO, i.e. the value of its physical line without
3836 * regard for its ACTIVE_LOW status.
3838 * This function can be called from contexts where we cannot sleep, and will
3839 * complain if the GPIO chip functions potentially sleep.
3841 void gpiod_set_raw_value(struct gpio_desc *desc, int value)
3843 VALIDATE_DESC_VOID(desc);
3844 /* Should be using gpiod_set_raw_value_cansleep() */
3845 WARN_ON(desc->gdev->chip->can_sleep);
3846 gpiod_set_raw_value_commit(desc, value);
3848 EXPORT_SYMBOL_GPL(gpiod_set_raw_value);
3851 * gpiod_set_value_nocheck() - set a GPIO line value without checking
3852 * @desc: the descriptor to set the value on
3853 * @value: value to set
3855 * This sets the value of a GPIO line backing a descriptor, applying
3856 * different semantic quirks like active low and open drain/source
3859 static void gpiod_set_value_nocheck(struct gpio_desc *desc, int value)
3861 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3863 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
3864 gpio_set_open_drain_value_commit(desc, value);
3865 else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
3866 gpio_set_open_source_value_commit(desc, value);
3868 gpiod_set_raw_value_commit(desc, value);
3872 * gpiod_set_value() - assign a gpio's value
3873 * @desc: gpio whose value will be assigned
3874 * @value: value to assign
3876 * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW,
3877 * OPEN_DRAIN and OPEN_SOURCE flags into account.
3879 * This function can be called from contexts where we cannot sleep, and will
3880 * complain if the GPIO chip functions potentially sleep.
3882 void gpiod_set_value(struct gpio_desc *desc, int value)
3884 VALIDATE_DESC_VOID(desc);
3885 /* Should be using gpiod_set_value_cansleep() */
3886 WARN_ON(desc->gdev->chip->can_sleep);
3887 gpiod_set_value_nocheck(desc, value);
3889 EXPORT_SYMBOL_GPL(gpiod_set_value);
3892 * gpiod_set_raw_array_value() - assign values to an array of GPIOs
3893 * @array_size: number of elements in the descriptor array / value bitmap
3894 * @desc_array: array of GPIO descriptors whose values will be assigned
3895 * @array_info: information on applicability of fast bitmap processing path
3896 * @value_bitmap: bitmap of values to assign
3898 * Set the raw values of the GPIOs, i.e. the values of the physical lines
3899 * without regard for their ACTIVE_LOW status.
3901 * This function can be called from contexts where we cannot sleep, and will
3902 * complain if the GPIO chip functions potentially sleep.
3904 int gpiod_set_raw_array_value(unsigned int array_size,
3905 struct gpio_desc **desc_array,
3906 struct gpio_array *array_info,
3907 unsigned long *value_bitmap)
3911 return gpiod_set_array_value_complex(true, false, array_size,
3912 desc_array, array_info, value_bitmap);
3914 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value);
3917 * gpiod_set_array_value() - assign values to an array of GPIOs
3918 * @array_size: number of elements in the descriptor array / value bitmap
3919 * @desc_array: array of GPIO descriptors whose values will be assigned
3920 * @array_info: information on applicability of fast bitmap processing path
3921 * @value_bitmap: bitmap of values to assign
3923 * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3926 * This function can be called from contexts where we cannot sleep, and will
3927 * complain if the GPIO chip functions potentially sleep.
3929 int gpiod_set_array_value(unsigned int array_size,
3930 struct gpio_desc **desc_array,
3931 struct gpio_array *array_info,
3932 unsigned long *value_bitmap)
3936 return gpiod_set_array_value_complex(false, false, array_size,
3937 desc_array, array_info,
3940 EXPORT_SYMBOL_GPL(gpiod_set_array_value);
3943 * gpiod_cansleep() - report whether gpio value access may sleep
3944 * @desc: gpio to check
3947 int gpiod_cansleep(const struct gpio_desc *desc)
3949 VALIDATE_DESC(desc);
3950 return desc->gdev->chip->can_sleep;
3952 EXPORT_SYMBOL_GPL(gpiod_cansleep);
3955 * gpiod_set_consumer_name() - set the consumer name for the descriptor
3956 * @desc: gpio to set the consumer name on
3957 * @name: the new consumer name
3959 int gpiod_set_consumer_name(struct gpio_desc *desc, const char *name)
3961 VALIDATE_DESC(desc);
3963 name = kstrdup_const(name, GFP_KERNEL);
3968 kfree_const(desc->label);
3969 desc_set_label(desc, name);
3973 EXPORT_SYMBOL_GPL(gpiod_set_consumer_name);
3976 * gpiod_to_irq() - return the IRQ corresponding to a GPIO
3977 * @desc: gpio whose IRQ will be returned (already requested)
3979 * Return the IRQ corresponding to the passed GPIO, or an error code in case of
3982 int gpiod_to_irq(const struct gpio_desc *desc)
3984 struct gpio_chip *chip;
3988 * Cannot VALIDATE_DESC() here as gpiod_to_irq() consumer semantics
3989 * requires this function to not return zero on an invalid descriptor
3990 * but rather a negative error number.
3992 if (!desc || IS_ERR(desc) || !desc->gdev || !desc->gdev->chip)
3995 chip = desc->gdev->chip;
3996 offset = gpio_chip_hwgpio(desc);
3998 int retirq = chip->to_irq(chip, offset);
4000 /* Zero means NO_IRQ */
4008 EXPORT_SYMBOL_GPL(gpiod_to_irq);
4011 * gpiochip_lock_as_irq() - lock a GPIO to be used as IRQ
4012 * @chip: the chip the GPIO to lock belongs to
4013 * @offset: the offset of the GPIO to lock as IRQ
4015 * This is used directly by GPIO drivers that want to lock down
4016 * a certain GPIO line to be used for IRQs.
4018 int gpiochip_lock_as_irq(struct gpio_chip *chip, unsigned int offset)
4020 struct gpio_desc *desc;
4022 desc = gpiochip_get_desc(chip, offset);
4024 return PTR_ERR(desc);
4027 * If it's fast: flush the direction setting if something changed
4030 if (!chip->can_sleep && chip->get_direction) {
4031 int dir = gpiod_get_direction(desc);
4034 chip_err(chip, "%s: cannot get GPIO direction\n",
4040 if (test_bit(FLAG_IS_OUT, &desc->flags)) {
4042 "%s: tried to flag a GPIO set as output for IRQ\n",
4047 set_bit(FLAG_USED_AS_IRQ, &desc->flags);
4048 set_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
4051 * If the consumer has not set up a label (such as when the
4052 * IRQ is referenced from .to_irq()) we set up a label here
4053 * so it is clear this is used as an interrupt.
4056 desc_set_label(desc, "interrupt");
4060 EXPORT_SYMBOL_GPL(gpiochip_lock_as_irq);
4063 * gpiochip_unlock_as_irq() - unlock a GPIO used as IRQ
4064 * @chip: the chip the GPIO to lock belongs to
4065 * @offset: the offset of the GPIO to lock as IRQ
4067 * This is used directly by GPIO drivers that want to indicate
4068 * that a certain GPIO is no longer used exclusively for IRQ.
4070 void gpiochip_unlock_as_irq(struct gpio_chip *chip, unsigned int offset)
4072 struct gpio_desc *desc;
4074 desc = gpiochip_get_desc(chip, offset);
4078 clear_bit(FLAG_USED_AS_IRQ, &desc->flags);
4079 clear_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
4081 /* If we only had this marking, erase it */
4082 if (desc->label && !strcmp(desc->label, "interrupt"))
4083 desc_set_label(desc, NULL);
4085 EXPORT_SYMBOL_GPL(gpiochip_unlock_as_irq);
4087 void gpiochip_disable_irq(struct gpio_chip *chip, unsigned int offset)
4089 struct gpio_desc *desc = gpiochip_get_desc(chip, offset);
4091 if (!IS_ERR(desc) &&
4092 !WARN_ON(!test_bit(FLAG_USED_AS_IRQ, &desc->flags)))
4093 clear_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
4095 EXPORT_SYMBOL_GPL(gpiochip_disable_irq);
4097 void gpiochip_enable_irq(struct gpio_chip *chip, unsigned int offset)
4099 struct gpio_desc *desc = gpiochip_get_desc(chip, offset);
4101 if (!IS_ERR(desc) &&
4102 !WARN_ON(!test_bit(FLAG_USED_AS_IRQ, &desc->flags))) {
4103 WARN_ON(test_bit(FLAG_IS_OUT, &desc->flags));
4104 set_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
4107 EXPORT_SYMBOL_GPL(gpiochip_enable_irq);
4109 bool gpiochip_line_is_irq(struct gpio_chip *chip, unsigned int offset)
4111 if (offset >= chip->ngpio)
4114 return test_bit(FLAG_USED_AS_IRQ, &chip->gpiodev->descs[offset].flags);
4116 EXPORT_SYMBOL_GPL(gpiochip_line_is_irq);
4118 int gpiochip_reqres_irq(struct gpio_chip *chip, unsigned int offset)
4122 if (!try_module_get(chip->gpiodev->owner))
4125 ret = gpiochip_lock_as_irq(chip, offset);
4127 chip_err(chip, "unable to lock HW IRQ %u for IRQ\n", offset);
4128 module_put(chip->gpiodev->owner);
4133 EXPORT_SYMBOL_GPL(gpiochip_reqres_irq);
4135 void gpiochip_relres_irq(struct gpio_chip *chip, unsigned int offset)
4137 gpiochip_unlock_as_irq(chip, offset);
4138 module_put(chip->gpiodev->owner);
4140 EXPORT_SYMBOL_GPL(gpiochip_relres_irq);
4142 bool gpiochip_line_is_open_drain(struct gpio_chip *chip, unsigned int offset)
4144 if (offset >= chip->ngpio)
4147 return test_bit(FLAG_OPEN_DRAIN, &chip->gpiodev->descs[offset].flags);
4149 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_drain);
4151 bool gpiochip_line_is_open_source(struct gpio_chip *chip, unsigned int offset)
4153 if (offset >= chip->ngpio)
4156 return test_bit(FLAG_OPEN_SOURCE, &chip->gpiodev->descs[offset].flags);
4158 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_source);
4160 bool gpiochip_line_is_persistent(struct gpio_chip *chip, unsigned int offset)
4162 if (offset >= chip->ngpio)
4165 return !test_bit(FLAG_TRANSITORY, &chip->gpiodev->descs[offset].flags);
4167 EXPORT_SYMBOL_GPL(gpiochip_line_is_persistent);
4170 * gpiod_get_raw_value_cansleep() - return a gpio's raw value
4171 * @desc: gpio whose value will be returned
4173 * Return the GPIO's raw value, i.e. the value of the physical line disregarding
4174 * its ACTIVE_LOW status, or negative errno on failure.
4176 * This function is to be called from contexts that can sleep.
4178 int gpiod_get_raw_value_cansleep(const struct gpio_desc *desc)
4180 might_sleep_if(extra_checks);
4181 VALIDATE_DESC(desc);
4182 return gpiod_get_raw_value_commit(desc);
4184 EXPORT_SYMBOL_GPL(gpiod_get_raw_value_cansleep);
4187 * gpiod_get_value_cansleep() - return a gpio's value
4188 * @desc: gpio whose value will be returned
4190 * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
4191 * account, or negative errno on failure.
4193 * This function is to be called from contexts that can sleep.
4195 int gpiod_get_value_cansleep(const struct gpio_desc *desc)
4199 might_sleep_if(extra_checks);
4200 VALIDATE_DESC(desc);
4201 value = gpiod_get_raw_value_commit(desc);
4205 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
4210 EXPORT_SYMBOL_GPL(gpiod_get_value_cansleep);
4213 * gpiod_get_raw_array_value_cansleep() - read raw values from an array of GPIOs
4214 * @array_size: number of elements in the descriptor array / value bitmap
4215 * @desc_array: array of GPIO descriptors whose values will be read
4216 * @array_info: information on applicability of fast bitmap processing path
4217 * @value_bitmap: bitmap to store the read values
4219 * Read the raw values of the GPIOs, i.e. the values of the physical lines
4220 * without regard for their ACTIVE_LOW status. Return 0 in case of success,
4221 * else an error code.
4223 * This function is to be called from contexts that can sleep.
4225 int gpiod_get_raw_array_value_cansleep(unsigned int array_size,
4226 struct gpio_desc **desc_array,
4227 struct gpio_array *array_info,
4228 unsigned long *value_bitmap)
4230 might_sleep_if(extra_checks);
4233 return gpiod_get_array_value_complex(true, true, array_size,
4234 desc_array, array_info,
4237 EXPORT_SYMBOL_GPL(gpiod_get_raw_array_value_cansleep);
4240 * gpiod_get_array_value_cansleep() - read values from an array of GPIOs
4241 * @array_size: number of elements in the descriptor array / value bitmap
4242 * @desc_array: array of GPIO descriptors whose values will be read
4243 * @array_info: information on applicability of fast bitmap processing path
4244 * @value_bitmap: bitmap to store the read values
4246 * Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
4247 * into account. Return 0 in case of success, else an error code.
4249 * This function is to be called from contexts that can sleep.
4251 int gpiod_get_array_value_cansleep(unsigned int array_size,
4252 struct gpio_desc **desc_array,
4253 struct gpio_array *array_info,
4254 unsigned long *value_bitmap)
4256 might_sleep_if(extra_checks);
4259 return gpiod_get_array_value_complex(false, true, array_size,
4260 desc_array, array_info,
4263 EXPORT_SYMBOL_GPL(gpiod_get_array_value_cansleep);
4266 * gpiod_set_raw_value_cansleep() - assign a gpio's raw value
4267 * @desc: gpio whose value will be assigned
4268 * @value: value to assign
4270 * Set the raw value of the GPIO, i.e. the value of its physical line without
4271 * regard for its ACTIVE_LOW status.
4273 * This function is to be called from contexts that can sleep.
4275 void gpiod_set_raw_value_cansleep(struct gpio_desc *desc, int value)
4277 might_sleep_if(extra_checks);
4278 VALIDATE_DESC_VOID(desc);
4279 gpiod_set_raw_value_commit(desc, value);
4281 EXPORT_SYMBOL_GPL(gpiod_set_raw_value_cansleep);
4284 * gpiod_set_value_cansleep() - assign a gpio's value
4285 * @desc: gpio whose value will be assigned
4286 * @value: value to assign
4288 * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
4291 * This function is to be called from contexts that can sleep.
4293 void gpiod_set_value_cansleep(struct gpio_desc *desc, int value)
4295 might_sleep_if(extra_checks);
4296 VALIDATE_DESC_VOID(desc);
4297 gpiod_set_value_nocheck(desc, value);
4299 EXPORT_SYMBOL_GPL(gpiod_set_value_cansleep);
4302 * gpiod_set_raw_array_value_cansleep() - assign values to an array of GPIOs
4303 * @array_size: number of elements in the descriptor array / value bitmap
4304 * @desc_array: array of GPIO descriptors whose values will be assigned
4305 * @array_info: information on applicability of fast bitmap processing path
4306 * @value_bitmap: bitmap of values to assign
4308 * Set the raw values of the GPIOs, i.e. the values of the physical lines
4309 * without regard for their ACTIVE_LOW status.
4311 * This function is to be called from contexts that can sleep.
4313 int gpiod_set_raw_array_value_cansleep(unsigned int array_size,
4314 struct gpio_desc **desc_array,
4315 struct gpio_array *array_info,
4316 unsigned long *value_bitmap)
4318 might_sleep_if(extra_checks);
4321 return gpiod_set_array_value_complex(true, true, array_size, desc_array,
4322 array_info, value_bitmap);
4324 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value_cansleep);
4327 * gpiod_add_lookup_tables() - register GPIO device consumers
4328 * @tables: list of tables of consumers to register
4329 * @n: number of tables in the list
4331 void gpiod_add_lookup_tables(struct gpiod_lookup_table **tables, size_t n)
4335 mutex_lock(&gpio_lookup_lock);
4337 for (i = 0; i < n; i++)
4338 list_add_tail(&tables[i]->list, &gpio_lookup_list);
4340 mutex_unlock(&gpio_lookup_lock);
4344 * gpiod_set_array_value_cansleep() - assign values to an array of GPIOs
4345 * @array_size: number of elements in the descriptor array / value bitmap
4346 * @desc_array: array of GPIO descriptors whose values will be assigned
4347 * @array_info: information on applicability of fast bitmap processing path
4348 * @value_bitmap: bitmap of values to assign
4350 * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
4353 * This function is to be called from contexts that can sleep.
4355 int gpiod_set_array_value_cansleep(unsigned int array_size,
4356 struct gpio_desc **desc_array,
4357 struct gpio_array *array_info,
4358 unsigned long *value_bitmap)
4360 might_sleep_if(extra_checks);
4363 return gpiod_set_array_value_complex(false, true, array_size,
4364 desc_array, array_info,
4367 EXPORT_SYMBOL_GPL(gpiod_set_array_value_cansleep);
4370 * gpiod_add_lookup_table() - register GPIO device consumers
4371 * @table: table of consumers to register
4373 void gpiod_add_lookup_table(struct gpiod_lookup_table *table)
4375 mutex_lock(&gpio_lookup_lock);
4377 list_add_tail(&table->list, &gpio_lookup_list);
4379 mutex_unlock(&gpio_lookup_lock);
4381 EXPORT_SYMBOL_GPL(gpiod_add_lookup_table);
4384 * gpiod_remove_lookup_table() - unregister GPIO device consumers
4385 * @table: table of consumers to unregister
4387 void gpiod_remove_lookup_table(struct gpiod_lookup_table *table)
4389 mutex_lock(&gpio_lookup_lock);
4391 list_del(&table->list);
4393 mutex_unlock(&gpio_lookup_lock);
4395 EXPORT_SYMBOL_GPL(gpiod_remove_lookup_table);
4398 * gpiod_add_hogs() - register a set of GPIO hogs from machine code
4399 * @hogs: table of gpio hog entries with a zeroed sentinel at the end
4401 void gpiod_add_hogs(struct gpiod_hog *hogs)
4403 struct gpio_chip *chip;
4404 struct gpiod_hog *hog;
4406 mutex_lock(&gpio_machine_hogs_mutex);
4408 for (hog = &hogs[0]; hog->chip_label; hog++) {
4409 list_add_tail(&hog->list, &gpio_machine_hogs);
4412 * The chip may have been registered earlier, so check if it
4413 * exists and, if so, try to hog the line now.
4415 chip = find_chip_by_name(hog->chip_label);
4417 gpiochip_machine_hog(chip, hog);
4420 mutex_unlock(&gpio_machine_hogs_mutex);
4422 EXPORT_SYMBOL_GPL(gpiod_add_hogs);
4424 static struct gpiod_lookup_table *gpiod_find_lookup_table(struct device *dev)
4426 const char *dev_id = dev ? dev_name(dev) : NULL;
4427 struct gpiod_lookup_table *table;
4429 mutex_lock(&gpio_lookup_lock);
4431 list_for_each_entry(table, &gpio_lookup_list, list) {
4432 if (table->dev_id && dev_id) {
4434 * Valid strings on both ends, must be identical to have
4437 if (!strcmp(table->dev_id, dev_id))
4441 * One of the pointers is NULL, so both must be to have
4444 if (dev_id == table->dev_id)
4451 mutex_unlock(&gpio_lookup_lock);
4455 static struct gpio_desc *gpiod_find(struct device *dev, const char *con_id,
4456 unsigned int idx, unsigned long *flags)
4458 struct gpio_desc *desc = ERR_PTR(-ENOENT);
4459 struct gpiod_lookup_table *table;
4460 struct gpiod_lookup *p;
4462 table = gpiod_find_lookup_table(dev);
4466 for (p = &table->table[0]; p->chip_label; p++) {
4467 struct gpio_chip *chip;
4469 /* idx must always match exactly */
4473 /* If the lookup entry has a con_id, require exact match */
4474 if (p->con_id && (!con_id || strcmp(p->con_id, con_id)))
4477 chip = find_chip_by_name(p->chip_label);
4481 * As the lookup table indicates a chip with
4482 * p->chip_label should exist, assume it may
4483 * still appear later and let the interested
4484 * consumer be probed again or let the Deferred
4485 * Probe infrastructure handle the error.
4487 dev_warn(dev, "cannot find GPIO chip %s, deferring\n",
4489 return ERR_PTR(-EPROBE_DEFER);
4492 if (chip->ngpio <= p->chip_hwnum) {
4494 "requested GPIO %u (%u) is out of range [0..%u] for chip %s\n",
4495 idx, p->chip_hwnum, chip->ngpio - 1,
4497 return ERR_PTR(-EINVAL);
4500 desc = gpiochip_get_desc(chip, p->chip_hwnum);
4509 static int platform_gpio_count(struct device *dev, const char *con_id)
4511 struct gpiod_lookup_table *table;
4512 struct gpiod_lookup *p;
4513 unsigned int count = 0;
4515 table = gpiod_find_lookup_table(dev);
4519 for (p = &table->table[0]; p->chip_label; p++) {
4520 if ((con_id && p->con_id && !strcmp(con_id, p->con_id)) ||
4521 (!con_id && !p->con_id))
4531 * fwnode_gpiod_get_index - obtain a GPIO from firmware node
4532 * @fwnode: handle of the firmware node
4533 * @con_id: function within the GPIO consumer
4534 * @index: index of the GPIO to obtain for the consumer
4535 * @flags: GPIO initialization flags
4536 * @label: label to attach to the requested GPIO
4538 * This function can be used for drivers that get their configuration
4539 * from opaque firmware.
4541 * The function properly finds the corresponding GPIO using whatever is the
4542 * underlying firmware interface and then makes sure that the GPIO
4543 * descriptor is requested before it is returned to the caller.
4546 * On successful request the GPIO pin is configured in accordance with
4549 * In case of error an ERR_PTR() is returned.
4551 struct gpio_desc *fwnode_gpiod_get_index(struct fwnode_handle *fwnode,
4552 const char *con_id, int index,
4553 enum gpiod_flags flags,
4556 struct gpio_desc *desc;
4557 char prop_name[32]; /* 32 is max size of property name */
4560 for (i = 0; i < ARRAY_SIZE(gpio_suffixes); i++) {
4562 snprintf(prop_name, sizeof(prop_name), "%s-%s",
4563 con_id, gpio_suffixes[i]);
4565 snprintf(prop_name, sizeof(prop_name), "%s",
4568 desc = fwnode_get_named_gpiod(fwnode, prop_name, index, flags,
4570 if (!IS_ERR(desc) || (PTR_ERR(desc) != -ENOENT))
4576 EXPORT_SYMBOL_GPL(fwnode_gpiod_get_index);
4579 * gpiod_count - return the number of GPIOs associated with a device / function
4580 * or -ENOENT if no GPIO has been assigned to the requested function
4581 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4582 * @con_id: function within the GPIO consumer
4584 int gpiod_count(struct device *dev, const char *con_id)
4586 int count = -ENOENT;
4588 if (IS_ENABLED(CONFIG_OF) && dev && dev->of_node)
4589 count = of_gpio_get_count(dev, con_id);
4590 else if (IS_ENABLED(CONFIG_ACPI) && dev && ACPI_HANDLE(dev))
4591 count = acpi_gpio_count(dev, con_id);
4594 count = platform_gpio_count(dev, con_id);
4598 EXPORT_SYMBOL_GPL(gpiod_count);
4601 * gpiod_get - obtain a GPIO for a given GPIO function
4602 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4603 * @con_id: function within the GPIO consumer
4604 * @flags: optional GPIO initialization flags
4606 * Return the GPIO descriptor corresponding to the function con_id of device
4607 * dev, -ENOENT if no GPIO has been assigned to the requested function, or
4608 * another IS_ERR() code if an error occurred while trying to acquire the GPIO.
4610 struct gpio_desc *__must_check gpiod_get(struct device *dev, const char *con_id,
4611 enum gpiod_flags flags)
4613 return gpiod_get_index(dev, con_id, 0, flags);
4615 EXPORT_SYMBOL_GPL(gpiod_get);
4618 * gpiod_get_optional - obtain an optional GPIO for a given GPIO function
4619 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4620 * @con_id: function within the GPIO consumer
4621 * @flags: optional GPIO initialization flags
4623 * This is equivalent to gpiod_get(), except that when no GPIO was assigned to
4624 * the requested function it will return NULL. This is convenient for drivers
4625 * that need to handle optional GPIOs.
4627 struct gpio_desc *__must_check gpiod_get_optional(struct device *dev,
4629 enum gpiod_flags flags)
4631 return gpiod_get_index_optional(dev, con_id, 0, flags);
4633 EXPORT_SYMBOL_GPL(gpiod_get_optional);
4637 * gpiod_configure_flags - helper function to configure a given GPIO
4638 * @desc: gpio whose value will be assigned
4639 * @con_id: function within the GPIO consumer
4640 * @lflags: bitmask of gpio_lookup_flags GPIO_* values - returned from
4641 * of_find_gpio() or of_get_gpio_hog()
4642 * @dflags: gpiod_flags - optional GPIO initialization flags
4644 * Return 0 on success, -ENOENT if no GPIO has been assigned to the
4645 * requested function and/or index, or another IS_ERR() code if an error
4646 * occurred while trying to acquire the GPIO.
4648 int gpiod_configure_flags(struct gpio_desc *desc, const char *con_id,
4649 unsigned long lflags, enum gpiod_flags dflags)
4653 if (lflags & GPIO_ACTIVE_LOW)
4654 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
4656 if (lflags & GPIO_OPEN_DRAIN)
4657 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
4658 else if (dflags & GPIOD_FLAGS_BIT_OPEN_DRAIN) {
4660 * This enforces open drain mode from the consumer side.
4661 * This is necessary for some busses like I2C, but the lookup
4662 * should *REALLY* have specified them as open drain in the
4663 * first place, so print a little warning here.
4665 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
4667 "enforced open drain please flag it properly in DT/ACPI DSDT/board file\n");
4670 if (lflags & GPIO_OPEN_SOURCE)
4671 set_bit(FLAG_OPEN_SOURCE, &desc->flags);
4673 if ((lflags & GPIO_PULL_UP) && (lflags & GPIO_PULL_DOWN)) {
4675 "both pull-up and pull-down enabled, invalid configuration\n");
4679 if (lflags & GPIO_PULL_UP)
4680 set_bit(FLAG_PULL_UP, &desc->flags);
4681 else if (lflags & GPIO_PULL_DOWN)
4682 set_bit(FLAG_PULL_DOWN, &desc->flags);
4684 ret = gpiod_set_transitory(desc, (lflags & GPIO_TRANSITORY));
4688 /* No particular flag request, return here... */
4689 if (!(dflags & GPIOD_FLAGS_BIT_DIR_SET)) {
4690 pr_debug("no flags found for %s\n", con_id);
4695 if (dflags & GPIOD_FLAGS_BIT_DIR_OUT)
4696 ret = gpiod_direction_output(desc,
4697 !!(dflags & GPIOD_FLAGS_BIT_DIR_VAL));
4699 ret = gpiod_direction_input(desc);
4705 * gpiod_get_index - obtain a GPIO from a multi-index GPIO function
4706 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4707 * @con_id: function within the GPIO consumer
4708 * @idx: index of the GPIO to obtain in the consumer
4709 * @flags: optional GPIO initialization flags
4711 * This variant of gpiod_get() allows to access GPIOs other than the first
4712 * defined one for functions that define several GPIOs.
4714 * Return a valid GPIO descriptor, -ENOENT if no GPIO has been assigned to the
4715 * requested function and/or index, or another IS_ERR() code if an error
4716 * occurred while trying to acquire the GPIO.
4718 struct gpio_desc *__must_check gpiod_get_index(struct device *dev,
4721 enum gpiod_flags flags)
4723 unsigned long lookupflags = GPIO_LOOKUP_FLAGS_DEFAULT;
4724 struct gpio_desc *desc = NULL;
4726 /* Maybe we have a device name, maybe not */
4727 const char *devname = dev ? dev_name(dev) : "?";
4729 dev_dbg(dev, "GPIO lookup for consumer %s\n", con_id);
4732 /* Using device tree? */
4733 if (IS_ENABLED(CONFIG_OF) && dev->of_node) {
4734 dev_dbg(dev, "using device tree for GPIO lookup\n");
4735 desc = of_find_gpio(dev, con_id, idx, &lookupflags);
4736 } else if (ACPI_COMPANION(dev)) {
4737 dev_dbg(dev, "using ACPI for GPIO lookup\n");
4738 desc = acpi_find_gpio(dev, con_id, idx, &flags, &lookupflags);
4743 * Either we are not using DT or ACPI, or their lookup did not return
4744 * a result. In that case, use platform lookup as a fallback.
4746 if (!desc || desc == ERR_PTR(-ENOENT)) {
4747 dev_dbg(dev, "using lookup tables for GPIO lookup\n");
4748 desc = gpiod_find(dev, con_id, idx, &lookupflags);
4752 dev_dbg(dev, "No GPIO consumer %s found\n", con_id);
4757 * If a connection label was passed use that, else attempt to use
4758 * the device name as label
4760 ret = gpiod_request(desc, con_id ? con_id : devname);
4762 if (ret == -EBUSY && flags & GPIOD_FLAGS_BIT_NONEXCLUSIVE) {
4764 * This happens when there are several consumers for
4765 * the same GPIO line: we just return here without
4766 * further initialization. It is a bit if a hack.
4767 * This is necessary to support fixed regulators.
4769 * FIXME: Make this more sane and safe.
4771 dev_info(dev, "nonexclusive access to GPIO for %s\n",
4772 con_id ? con_id : devname);
4775 return ERR_PTR(ret);
4779 ret = gpiod_configure_flags(desc, con_id, lookupflags, flags);
4781 dev_dbg(dev, "setup of GPIO %s failed\n", con_id);
4783 return ERR_PTR(ret);
4788 EXPORT_SYMBOL_GPL(gpiod_get_index);
4791 * fwnode_get_named_gpiod - obtain a GPIO from firmware node
4792 * @fwnode: handle of the firmware node
4793 * @propname: name of the firmware property representing the GPIO
4794 * @index: index of the GPIO to obtain for the consumer
4795 * @dflags: GPIO initialization flags
4796 * @label: label to attach to the requested GPIO
4798 * This function can be used for drivers that get their configuration
4799 * from opaque firmware.
4801 * The function properly finds the corresponding GPIO using whatever is the
4802 * underlying firmware interface and then makes sure that the GPIO
4803 * descriptor is requested before it is returned to the caller.
4806 * On successful request the GPIO pin is configured in accordance with
4809 * In case of error an ERR_PTR() is returned.
4811 struct gpio_desc *fwnode_get_named_gpiod(struct fwnode_handle *fwnode,
4812 const char *propname, int index,
4813 enum gpiod_flags dflags,
4816 unsigned long lflags = GPIO_LOOKUP_FLAGS_DEFAULT;
4817 struct gpio_desc *desc = ERR_PTR(-ENODEV);
4821 return ERR_PTR(-EINVAL);
4823 if (is_of_node(fwnode)) {
4824 desc = gpiod_get_from_of_node(to_of_node(fwnode),
4829 } else if (is_acpi_node(fwnode)) {
4830 struct acpi_gpio_info info;
4832 desc = acpi_node_get_gpiod(fwnode, propname, index, &info);
4836 acpi_gpio_update_gpiod_flags(&dflags, &info);
4837 acpi_gpio_update_gpiod_lookup_flags(&lflags, &info);
4840 /* Currently only ACPI takes this path */
4841 ret = gpiod_request(desc, label);
4843 return ERR_PTR(ret);
4845 ret = gpiod_configure_flags(desc, propname, lflags, dflags);
4848 return ERR_PTR(ret);
4853 EXPORT_SYMBOL_GPL(fwnode_get_named_gpiod);
4856 * gpiod_get_index_optional - obtain an optional GPIO from a multi-index GPIO
4858 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4859 * @con_id: function within the GPIO consumer
4860 * @index: index of the GPIO to obtain in the consumer
4861 * @flags: optional GPIO initialization flags
4863 * This is equivalent to gpiod_get_index(), except that when no GPIO with the
4864 * specified index was assigned to the requested function it will return NULL.
4865 * This is convenient for drivers that need to handle optional GPIOs.
4867 struct gpio_desc *__must_check gpiod_get_index_optional(struct device *dev,
4870 enum gpiod_flags flags)
4872 struct gpio_desc *desc;
4874 desc = gpiod_get_index(dev, con_id, index, flags);
4876 if (PTR_ERR(desc) == -ENOENT)
4882 EXPORT_SYMBOL_GPL(gpiod_get_index_optional);
4885 * gpiod_hog - Hog the specified GPIO desc given the provided flags
4886 * @desc: gpio whose value will be assigned
4887 * @name: gpio line name
4888 * @lflags: bitmask of gpio_lookup_flags GPIO_* values - returned from
4889 * of_find_gpio() or of_get_gpio_hog()
4890 * @dflags: gpiod_flags - optional GPIO initialization flags
4892 int gpiod_hog(struct gpio_desc *desc, const char *name,
4893 unsigned long lflags, enum gpiod_flags dflags)
4895 struct gpio_chip *chip;
4896 struct gpio_desc *local_desc;
4900 chip = gpiod_to_chip(desc);
4901 hwnum = gpio_chip_hwgpio(desc);
4903 local_desc = gpiochip_request_own_desc(chip, hwnum, name,
4905 if (IS_ERR(local_desc)) {
4906 ret = PTR_ERR(local_desc);
4907 pr_err("requesting hog GPIO %s (chip %s, offset %d) failed, %d\n",
4908 name, chip->label, hwnum, ret);
4912 /* Mark GPIO as hogged so it can be identified and removed later */
4913 set_bit(FLAG_IS_HOGGED, &desc->flags);
4915 pr_info("GPIO line %d (%s) hogged as %s%s\n",
4916 desc_to_gpio(desc), name,
4917 (dflags & GPIOD_FLAGS_BIT_DIR_OUT) ? "output" : "input",
4918 (dflags & GPIOD_FLAGS_BIT_DIR_OUT) ?
4919 (dflags & GPIOD_FLAGS_BIT_DIR_VAL) ? "/high" : "/low" : "");
4925 * gpiochip_free_hogs - Scan gpio-controller chip and release GPIO hog
4926 * @chip: gpio chip to act on
4928 static void gpiochip_free_hogs(struct gpio_chip *chip)
4932 for (id = 0; id < chip->ngpio; id++) {
4933 if (test_bit(FLAG_IS_HOGGED, &chip->gpiodev->descs[id].flags))
4934 gpiochip_free_own_desc(&chip->gpiodev->descs[id]);
4939 * gpiod_get_array - obtain multiple GPIOs from a multi-index GPIO function
4940 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4941 * @con_id: function within the GPIO consumer
4942 * @flags: optional GPIO initialization flags
4944 * This function acquires all the GPIOs defined under a given function.
4946 * Return a struct gpio_descs containing an array of descriptors, -ENOENT if
4947 * no GPIO has been assigned to the requested function, or another IS_ERR()
4948 * code if an error occurred while trying to acquire the GPIOs.
4950 struct gpio_descs *__must_check gpiod_get_array(struct device *dev,
4952 enum gpiod_flags flags)
4954 struct gpio_desc *desc;
4955 struct gpio_descs *descs;
4956 struct gpio_array *array_info = NULL;
4957 struct gpio_chip *chip;
4958 int count, bitmap_size;
4960 count = gpiod_count(dev, con_id);
4962 return ERR_PTR(count);
4964 descs = kzalloc(struct_size(descs, desc, count), GFP_KERNEL);
4966 return ERR_PTR(-ENOMEM);
4968 for (descs->ndescs = 0; descs->ndescs < count; ) {
4969 desc = gpiod_get_index(dev, con_id, descs->ndescs, flags);
4971 gpiod_put_array(descs);
4972 return ERR_CAST(desc);
4975 descs->desc[descs->ndescs] = desc;
4977 chip = gpiod_to_chip(desc);
4979 * If pin hardware number of array member 0 is also 0, select
4980 * its chip as a candidate for fast bitmap processing path.
4982 if (descs->ndescs == 0 && gpio_chip_hwgpio(desc) == 0) {
4983 struct gpio_descs *array;
4985 bitmap_size = BITS_TO_LONGS(chip->ngpio > count ?
4986 chip->ngpio : count);
4988 array = kzalloc(struct_size(descs, desc, count) +
4989 struct_size(array_info, invert_mask,
4990 3 * bitmap_size), GFP_KERNEL);
4992 gpiod_put_array(descs);
4993 return ERR_PTR(-ENOMEM);
4996 memcpy(array, descs,
4997 struct_size(descs, desc, descs->ndescs + 1));
5001 array_info = (void *)(descs->desc + count);
5002 array_info->get_mask = array_info->invert_mask +
5004 array_info->set_mask = array_info->get_mask +
5007 array_info->desc = descs->desc;
5008 array_info->size = count;
5009 array_info->chip = chip;
5010 bitmap_set(array_info->get_mask, descs->ndescs,
5011 count - descs->ndescs);
5012 bitmap_set(array_info->set_mask, descs->ndescs,
5013 count - descs->ndescs);
5014 descs->info = array_info;
5016 /* Unmark array members which don't belong to the 'fast' chip */
5017 if (array_info && array_info->chip != chip) {
5018 __clear_bit(descs->ndescs, array_info->get_mask);
5019 __clear_bit(descs->ndescs, array_info->set_mask);
5022 * Detect array members which belong to the 'fast' chip
5023 * but their pins are not in hardware order.
5025 else if (array_info &&
5026 gpio_chip_hwgpio(desc) != descs->ndescs) {
5028 * Don't use fast path if all array members processed so
5029 * far belong to the same chip as this one but its pin
5030 * hardware number is different from its array index.
5032 if (bitmap_full(array_info->get_mask, descs->ndescs)) {
5035 __clear_bit(descs->ndescs,
5036 array_info->get_mask);
5037 __clear_bit(descs->ndescs,
5038 array_info->set_mask);
5040 } else if (array_info) {
5041 /* Exclude open drain or open source from fast output */
5042 if (gpiochip_line_is_open_drain(chip, descs->ndescs) ||
5043 gpiochip_line_is_open_source(chip, descs->ndescs))
5044 __clear_bit(descs->ndescs,
5045 array_info->set_mask);
5046 /* Identify 'fast' pins which require invertion */
5047 if (gpiod_is_active_low(desc))
5048 __set_bit(descs->ndescs,
5049 array_info->invert_mask);
5056 "GPIO array info: chip=%s, size=%d, get_mask=%lx, set_mask=%lx, invert_mask=%lx\n",
5057 array_info->chip->label, array_info->size,
5058 *array_info->get_mask, *array_info->set_mask,
5059 *array_info->invert_mask);
5062 EXPORT_SYMBOL_GPL(gpiod_get_array);
5065 * gpiod_get_array_optional - obtain multiple GPIOs from a multi-index GPIO
5067 * @dev: GPIO consumer, can be NULL for system-global GPIOs
5068 * @con_id: function within the GPIO consumer
5069 * @flags: optional GPIO initialization flags
5071 * This is equivalent to gpiod_get_array(), except that when no GPIO was
5072 * assigned to the requested function it will return NULL.
5074 struct gpio_descs *__must_check gpiod_get_array_optional(struct device *dev,
5076 enum gpiod_flags flags)
5078 struct gpio_descs *descs;
5080 descs = gpiod_get_array(dev, con_id, flags);
5081 if (IS_ERR(descs) && (PTR_ERR(descs) == -ENOENT))
5086 EXPORT_SYMBOL_GPL(gpiod_get_array_optional);
5089 * gpiod_put - dispose of a GPIO descriptor
5090 * @desc: GPIO descriptor to dispose of
5092 * No descriptor can be used after gpiod_put() has been called on it.
5094 void gpiod_put(struct gpio_desc *desc)
5099 EXPORT_SYMBOL_GPL(gpiod_put);
5102 * gpiod_put_array - dispose of multiple GPIO descriptors
5103 * @descs: struct gpio_descs containing an array of descriptors
5105 void gpiod_put_array(struct gpio_descs *descs)
5109 for (i = 0; i < descs->ndescs; i++)
5110 gpiod_put(descs->desc[i]);
5114 EXPORT_SYMBOL_GPL(gpiod_put_array);
5116 static int __init gpiolib_dev_init(void)
5120 /* Register GPIO sysfs bus */
5121 ret = bus_register(&gpio_bus_type);
5123 pr_err("gpiolib: could not register GPIO bus type\n");
5127 ret = alloc_chrdev_region(&gpio_devt, 0, GPIO_DEV_MAX, "gpiochip");
5129 pr_err("gpiolib: failed to allocate char dev region\n");
5130 bus_unregister(&gpio_bus_type);
5132 gpiolib_initialized = true;
5133 gpiochip_setup_devs();
5137 core_initcall(gpiolib_dev_init);
5139 #ifdef CONFIG_DEBUG_FS
5141 static void gpiolib_dbg_show(struct seq_file *s, struct gpio_device *gdev)
5144 struct gpio_chip *chip = gdev->chip;
5145 unsigned gpio = gdev->base;
5146 struct gpio_desc *gdesc = &gdev->descs[0];
5151 for (i = 0; i < gdev->ngpio; i++, gpio++, gdesc++) {
5152 if (!test_bit(FLAG_REQUESTED, &gdesc->flags)) {
5154 seq_printf(s, " gpio-%-3d (%-20.20s)\n",
5160 gpiod_get_direction(gdesc);
5161 is_out = test_bit(FLAG_IS_OUT, &gdesc->flags);
5162 is_irq = test_bit(FLAG_USED_AS_IRQ, &gdesc->flags);
5163 active_low = test_bit(FLAG_ACTIVE_LOW, &gdesc->flags);
5164 seq_printf(s, " gpio-%-3d (%-20.20s|%-20.20s) %s %s %s%s",
5165 gpio, gdesc->name ? gdesc->name : "", gdesc->label,
5166 is_out ? "out" : "in ",
5167 chip->get ? (chip->get(chip, i) ? "hi" : "lo") : "? ",
5168 is_irq ? "IRQ " : "",
5169 active_low ? "ACTIVE LOW" : "");
5170 seq_printf(s, "\n");
5174 static void *gpiolib_seq_start(struct seq_file *s, loff_t *pos)
5176 unsigned long flags;
5177 struct gpio_device *gdev = NULL;
5178 loff_t index = *pos;
5182 spin_lock_irqsave(&gpio_lock, flags);
5183 list_for_each_entry(gdev, &gpio_devices, list)
5185 spin_unlock_irqrestore(&gpio_lock, flags);
5188 spin_unlock_irqrestore(&gpio_lock, flags);
5193 static void *gpiolib_seq_next(struct seq_file *s, void *v, loff_t *pos)
5195 unsigned long flags;
5196 struct gpio_device *gdev = v;
5199 spin_lock_irqsave(&gpio_lock, flags);
5200 if (list_is_last(&gdev->list, &gpio_devices))
5203 ret = list_entry(gdev->list.next, struct gpio_device, list);
5204 spin_unlock_irqrestore(&gpio_lock, flags);
5212 static void gpiolib_seq_stop(struct seq_file *s, void *v)
5216 static int gpiolib_seq_show(struct seq_file *s, void *v)
5218 struct gpio_device *gdev = v;
5219 struct gpio_chip *chip = gdev->chip;
5220 struct device *parent;
5223 seq_printf(s, "%s%s: (dangling chip)", (char *)s->private,
5224 dev_name(&gdev->dev));
5228 seq_printf(s, "%s%s: GPIOs %d-%d", (char *)s->private,
5229 dev_name(&gdev->dev),
5230 gdev->base, gdev->base + gdev->ngpio - 1);
5231 parent = chip->parent;
5233 seq_printf(s, ", parent: %s/%s",
5234 parent->bus ? parent->bus->name : "no-bus",
5237 seq_printf(s, ", %s", chip->label);
5238 if (chip->can_sleep)
5239 seq_printf(s, ", can sleep");
5240 seq_printf(s, ":\n");
5243 chip->dbg_show(s, chip);
5245 gpiolib_dbg_show(s, gdev);
5250 static const struct seq_operations gpiolib_seq_ops = {
5251 .start = gpiolib_seq_start,
5252 .next = gpiolib_seq_next,
5253 .stop = gpiolib_seq_stop,
5254 .show = gpiolib_seq_show,
5257 static int gpiolib_open(struct inode *inode, struct file *file)
5259 return seq_open(file, &gpiolib_seq_ops);
5262 static const struct file_operations gpiolib_operations = {
5263 .owner = THIS_MODULE,
5264 .open = gpiolib_open,
5266 .llseek = seq_lseek,
5267 .release = seq_release,
5270 static int __init gpiolib_debugfs_init(void)
5272 /* /sys/kernel/debug/gpio */
5273 debugfs_create_file("gpio", S_IFREG | S_IRUGO, NULL, NULL,
5274 &gpiolib_operations);
5277 subsys_initcall(gpiolib_debugfs_init);
5279 #endif /* DEBUG_FS */