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 *gc);
85 static int gpiochip_add_irqchip(struct gpio_chip *gc,
86 struct lock_class_key *lock_key,
87 struct lock_class_key *request_key);
88 static void gpiochip_irqchip_remove(struct gpio_chip *gc);
89 static int gpiochip_irqchip_init_hw(struct gpio_chip *gc);
90 static int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gc);
91 static void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gc);
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 *gc,
145 struct gpio_device *gdev = gc->gpiodev;
147 if (hwnum >= gdev->ngpio)
148 return ERR_PTR(-EINVAL);
150 return &gdev->descs[hwnum];
152 EXPORT_SYMBOL_GPL(gpiochip_get_desc);
155 * desc_to_gpio - convert a GPIO descriptor to the integer namespace
156 * @desc: GPIO descriptor
158 * This should disappear in the future but is needed since we still
159 * use GPIO numbers for error messages and sysfs nodes.
162 * The global GPIO number for the GPIO specified by its descriptor.
164 int desc_to_gpio(const struct gpio_desc *desc)
166 return desc->gdev->base + (desc - &desc->gdev->descs[0]);
168 EXPORT_SYMBOL_GPL(desc_to_gpio);
172 * gpiod_to_chip - Return the GPIO chip to which a GPIO descriptor belongs
173 * @desc: descriptor to return the chip of
175 struct gpio_chip *gpiod_to_chip(const struct gpio_desc *desc)
177 if (!desc || !desc->gdev)
179 return desc->gdev->chip;
181 EXPORT_SYMBOL_GPL(gpiod_to_chip);
183 /* dynamic allocation of GPIOs, e.g. on a hotplugged device */
184 static int gpiochip_find_base(int ngpio)
186 struct gpio_device *gdev;
187 int base = ARCH_NR_GPIOS - ngpio;
189 list_for_each_entry_reverse(gdev, &gpio_devices, list) {
190 /* found a free space? */
191 if (gdev->base + gdev->ngpio <= base)
194 /* nope, check the space right before the chip */
195 base = gdev->base - ngpio;
198 if (gpio_is_valid(base)) {
199 pr_debug("%s: found new base at %d\n", __func__, base);
202 pr_err("%s: cannot find free range\n", __func__);
208 * gpiod_get_direction - return the current direction of a GPIO
209 * @desc: GPIO to get the direction of
211 * Returns 0 for output, 1 for input, or an error code in case of error.
213 * This function may sleep if gpiod_cansleep() is true.
215 int gpiod_get_direction(struct gpio_desc *desc)
217 struct gpio_chip *gc;
221 gc = gpiod_to_chip(desc);
222 offset = gpio_chip_hwgpio(desc);
225 * Open drain emulation using input mode may incorrectly report
226 * input here, fix that up.
228 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags) &&
229 test_bit(FLAG_IS_OUT, &desc->flags))
232 if (!gc->get_direction)
235 ret = gc->get_direction(gc, offset);
239 /* GPIOF_DIR_IN or other positive, otherwise GPIOF_DIR_OUT */
243 assign_bit(FLAG_IS_OUT, &desc->flags, !ret);
247 EXPORT_SYMBOL_GPL(gpiod_get_direction);
250 * Add a new chip to the global chips list, keeping the list of chips sorted
251 * by range(means [base, base + ngpio - 1]) order.
253 * Return -EBUSY if the new chip overlaps with some other chip's integer
256 static int gpiodev_add_to_list(struct gpio_device *gdev)
258 struct gpio_device *prev, *next;
260 if (list_empty(&gpio_devices)) {
261 /* initial entry in list */
262 list_add_tail(&gdev->list, &gpio_devices);
266 next = list_entry(gpio_devices.next, struct gpio_device, list);
267 if (gdev->base + gdev->ngpio <= next->base) {
268 /* add before first entry */
269 list_add(&gdev->list, &gpio_devices);
273 prev = list_entry(gpio_devices.prev, struct gpio_device, list);
274 if (prev->base + prev->ngpio <= gdev->base) {
275 /* add behind last entry */
276 list_add_tail(&gdev->list, &gpio_devices);
280 list_for_each_entry_safe(prev, next, &gpio_devices, list) {
281 /* at the end of the list */
282 if (&next->list == &gpio_devices)
285 /* add between prev and next */
286 if (prev->base + prev->ngpio <= gdev->base
287 && gdev->base + gdev->ngpio <= next->base) {
288 list_add(&gdev->list, &prev->list);
293 dev_err(&gdev->dev, "GPIO integer space overlap, cannot add chip\n");
298 * Convert a GPIO name to its descriptor
299 * Note that there is no guarantee that GPIO names are globally unique!
300 * Hence this function will return, if it exists, a reference to the first GPIO
301 * line found that matches the given name.
303 static struct gpio_desc *gpio_name_to_desc(const char * const name)
305 struct gpio_device *gdev;
311 spin_lock_irqsave(&gpio_lock, flags);
313 list_for_each_entry(gdev, &gpio_devices, list) {
316 for (i = 0; i != gdev->ngpio; ++i) {
317 struct gpio_desc *desc = &gdev->descs[i];
322 if (!strcmp(desc->name, name)) {
323 spin_unlock_irqrestore(&gpio_lock, flags);
329 spin_unlock_irqrestore(&gpio_lock, flags);
335 * Take the names from gc->names and assign them to their GPIO descriptors.
336 * Warn if a name is already used for a GPIO line on a different GPIO chip.
339 * 1. Non-unique names are still accepted,
340 * 2. Name collisions within the same GPIO chip are not reported.
342 static int gpiochip_set_desc_names(struct gpio_chip *gc)
344 struct gpio_device *gdev = gc->gpiodev;
350 /* First check all names if they are unique */
351 for (i = 0; i != gc->ngpio; ++i) {
352 struct gpio_desc *gpio;
354 gpio = gpio_name_to_desc(gc->names[i]);
357 "Detected name collision for GPIO name '%s'\n",
361 /* Then add all names to the GPIO descriptors */
362 for (i = 0; i != gc->ngpio; ++i)
363 gdev->descs[i].name = gc->names[i];
368 static unsigned long *gpiochip_allocate_mask(struct gpio_chip *gc)
372 p = bitmap_alloc(gc->ngpio, GFP_KERNEL);
376 /* Assume by default all GPIOs are valid */
377 bitmap_fill(p, gc->ngpio);
382 static int gpiochip_alloc_valid_mask(struct gpio_chip *gc)
384 if (!(of_gpio_need_valid_mask(gc) || gc->init_valid_mask))
387 gc->valid_mask = gpiochip_allocate_mask(gc);
394 static int gpiochip_init_valid_mask(struct gpio_chip *gc)
396 if (gc->init_valid_mask)
397 return gc->init_valid_mask(gc,
404 static void gpiochip_free_valid_mask(struct gpio_chip *gc)
406 bitmap_free(gc->valid_mask);
407 gc->valid_mask = NULL;
410 static int gpiochip_add_pin_ranges(struct gpio_chip *gc)
412 if (gc->add_pin_ranges)
413 return gc->add_pin_ranges(gc);
418 bool gpiochip_line_is_valid(const struct gpio_chip *gc,
421 /* No mask means all valid */
422 if (likely(!gc->valid_mask))
424 return test_bit(offset, gc->valid_mask);
426 EXPORT_SYMBOL_GPL(gpiochip_line_is_valid);
429 * GPIO line handle management
433 * struct linehandle_state - contains the state of a userspace handle
434 * @gdev: the GPIO device the handle pertains to
435 * @label: consumer label used to tag descriptors
436 * @descs: the GPIO descriptors held by this handle
437 * @numdescs: the number of descriptors held in the descs array
439 struct linehandle_state {
440 struct gpio_device *gdev;
442 struct gpio_desc *descs[GPIOHANDLES_MAX];
446 #define GPIOHANDLE_REQUEST_VALID_FLAGS \
447 (GPIOHANDLE_REQUEST_INPUT | \
448 GPIOHANDLE_REQUEST_OUTPUT | \
449 GPIOHANDLE_REQUEST_ACTIVE_LOW | \
450 GPIOHANDLE_REQUEST_BIAS_PULL_UP | \
451 GPIOHANDLE_REQUEST_BIAS_PULL_DOWN | \
452 GPIOHANDLE_REQUEST_BIAS_DISABLE | \
453 GPIOHANDLE_REQUEST_OPEN_DRAIN | \
454 GPIOHANDLE_REQUEST_OPEN_SOURCE)
456 static int linehandle_validate_flags(u32 flags)
458 /* Return an error if an unknown flag is set */
459 if (flags & ~GPIOHANDLE_REQUEST_VALID_FLAGS)
463 * Do not allow both INPUT & OUTPUT flags to be set as they are
466 if ((flags & GPIOHANDLE_REQUEST_INPUT) &&
467 (flags & GPIOHANDLE_REQUEST_OUTPUT))
471 * Do not allow OPEN_SOURCE & OPEN_DRAIN flags in a single request. If
472 * the hardware actually supports enabling both at the same time the
473 * electrical result would be disastrous.
475 if ((flags & GPIOHANDLE_REQUEST_OPEN_DRAIN) &&
476 (flags & GPIOHANDLE_REQUEST_OPEN_SOURCE))
479 /* OPEN_DRAIN and OPEN_SOURCE flags only make sense for output mode. */
480 if (!(flags & GPIOHANDLE_REQUEST_OUTPUT) &&
481 ((flags & GPIOHANDLE_REQUEST_OPEN_DRAIN) ||
482 (flags & GPIOHANDLE_REQUEST_OPEN_SOURCE)))
485 /* Bias flags only allowed for input or output mode. */
486 if (!((flags & GPIOHANDLE_REQUEST_INPUT) ||
487 (flags & GPIOHANDLE_REQUEST_OUTPUT)) &&
488 ((flags & GPIOHANDLE_REQUEST_BIAS_DISABLE) ||
489 (flags & GPIOHANDLE_REQUEST_BIAS_PULL_UP) ||
490 (flags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN)))
493 /* Only one bias flag can be set. */
494 if (((flags & GPIOHANDLE_REQUEST_BIAS_DISABLE) &&
495 (flags & (GPIOHANDLE_REQUEST_BIAS_PULL_DOWN |
496 GPIOHANDLE_REQUEST_BIAS_PULL_UP))) ||
497 ((flags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN) &&
498 (flags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)))
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 assign_bit(FLAG_ACTIVE_LOW, flagsp,
526 lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW);
528 assign_bit(FLAG_OPEN_DRAIN, flagsp,
529 lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN);
531 assign_bit(FLAG_OPEN_SOURCE, flagsp,
532 lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE);
534 assign_bit(FLAG_PULL_UP, flagsp,
535 lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP);
537 assign_bit(FLAG_PULL_DOWN, flagsp,
538 lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN);
540 assign_bit(FLAG_BIAS_DISABLE, flagsp,
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);
559 atomic_notifier_call_chain(&desc->gdev->notifier,
560 GPIOLINE_CHANGED_CONFIG, desc);
565 static long linehandle_ioctl(struct file *filep, unsigned int cmd,
568 struct linehandle_state *lh = filep->private_data;
569 void __user *ip = (void __user *)arg;
570 struct gpiohandle_data ghd;
571 DECLARE_BITMAP(vals, GPIOHANDLES_MAX);
574 if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
575 /* NOTE: It's ok to read values of output lines. */
576 int ret = gpiod_get_array_value_complex(false,
585 memset(&ghd, 0, sizeof(ghd));
586 for (i = 0; i < lh->numdescs; i++)
587 ghd.values[i] = test_bit(i, vals);
589 if (copy_to_user(ip, &ghd, sizeof(ghd)))
593 } else if (cmd == GPIOHANDLE_SET_LINE_VALUES_IOCTL) {
595 * All line descriptors were created at once with the same
596 * flags so just check if the first one is really output.
598 if (!test_bit(FLAG_IS_OUT, &lh->descs[0]->flags))
601 if (copy_from_user(&ghd, ip, sizeof(ghd)))
604 /* Clamp all values to [0,1] */
605 for (i = 0; i < lh->numdescs; i++)
606 __assign_bit(i, vals, ghd.values[i]);
608 /* Reuse the array setting function */
609 return gpiod_set_array_value_complex(false,
615 } else if (cmd == GPIOHANDLE_SET_CONFIG_IOCTL) {
616 return linehandle_set_config(lh, ip);
622 static long linehandle_ioctl_compat(struct file *filep, unsigned int cmd,
625 return linehandle_ioctl(filep, cmd, (unsigned long)compat_ptr(arg));
629 static int linehandle_release(struct inode *inode, struct file *filep)
631 struct linehandle_state *lh = filep->private_data;
632 struct gpio_device *gdev = lh->gdev;
635 for (i = 0; i < lh->numdescs; i++)
636 gpiod_free(lh->descs[i]);
639 put_device(&gdev->dev);
643 static const struct file_operations linehandle_fileops = {
644 .release = linehandle_release,
645 .owner = THIS_MODULE,
646 .llseek = noop_llseek,
647 .unlocked_ioctl = linehandle_ioctl,
649 .compat_ioctl = linehandle_ioctl_compat,
653 static int linehandle_create(struct gpio_device *gdev, void __user *ip)
655 struct gpiohandle_request handlereq;
656 struct linehandle_state *lh;
658 int fd, i, count = 0, ret;
661 if (copy_from_user(&handlereq, ip, sizeof(handlereq)))
663 if ((handlereq.lines == 0) || (handlereq.lines > GPIOHANDLES_MAX))
666 lflags = handlereq.flags;
668 ret = linehandle_validate_flags(lflags);
672 lh = kzalloc(sizeof(*lh), GFP_KERNEL);
676 get_device(&gdev->dev);
678 /* Make sure this is terminated */
679 handlereq.consumer_label[sizeof(handlereq.consumer_label)-1] = '\0';
680 if (strlen(handlereq.consumer_label)) {
681 lh->label = kstrdup(handlereq.consumer_label,
689 /* Request each GPIO */
690 for (i = 0; i < handlereq.lines; i++) {
691 u32 offset = handlereq.lineoffsets[i];
692 struct gpio_desc *desc = gpiochip_get_desc(gdev->chip, offset);
699 ret = gpiod_request(desc, lh->label);
705 if (lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW)
706 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
707 if (lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN)
708 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
709 if (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE)
710 set_bit(FLAG_OPEN_SOURCE, &desc->flags);
711 if (lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE)
712 set_bit(FLAG_BIAS_DISABLE, &desc->flags);
713 if (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN)
714 set_bit(FLAG_PULL_DOWN, &desc->flags);
715 if (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)
716 set_bit(FLAG_PULL_UP, &desc->flags);
718 ret = gpiod_set_transitory(desc, false);
723 * Lines have to be requested explicitly for input
724 * or output, else the line will be treated "as is".
726 if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
727 int val = !!handlereq.default_values[i];
729 ret = gpiod_direction_output(desc, val);
732 } else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
733 ret = gpiod_direction_input(desc);
737 dev_dbg(&gdev->dev, "registered chardev handle for line %d\n",
740 /* Let i point at the last handle */
742 lh->numdescs = handlereq.lines;
744 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
750 file = anon_inode_getfile("gpio-linehandle",
753 O_RDONLY | O_CLOEXEC);
756 goto out_put_unused_fd;
760 if (copy_to_user(ip, &handlereq, sizeof(handlereq))) {
762 * fput() will trigger the release() callback, so do not go onto
763 * the regular error cleanup path here.
770 fd_install(fd, file);
772 dev_dbg(&gdev->dev, "registered chardev handle for %d lines\n",
780 for (i = 0; i < count; i++)
781 gpiod_free(lh->descs[i]);
785 put_device(&gdev->dev);
790 * GPIO line event management
794 * struct lineevent_state - contains the state of a userspace event
795 * @gdev: the GPIO device the event pertains to
796 * @label: consumer label used to tag descriptors
797 * @desc: the GPIO descriptor held by this event
798 * @eflags: the event flags this line was requested with
799 * @irq: the interrupt that trigger in response to events on this GPIO
800 * @wait: wait queue that handles blocking reads of events
801 * @events: KFIFO for the GPIO events
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);
817 #define GPIOEVENT_REQUEST_VALID_FLAGS \
818 (GPIOEVENT_REQUEST_RISING_EDGE | \
819 GPIOEVENT_REQUEST_FALLING_EDGE)
821 static __poll_t lineevent_poll(struct file *filep,
822 struct poll_table_struct *wait)
824 struct lineevent_state *le = filep->private_data;
827 poll_wait(filep, &le->wait, wait);
829 if (!kfifo_is_empty_spinlocked_noirqsave(&le->events, &le->wait.lock))
830 events = EPOLLIN | EPOLLRDNORM;
836 static ssize_t lineevent_read(struct file *filep,
841 struct lineevent_state *le = filep->private_data;
842 struct gpioevent_data ge;
843 ssize_t bytes_read = 0;
846 if (count < sizeof(ge))
850 spin_lock(&le->wait.lock);
851 if (kfifo_is_empty(&le->events)) {
853 spin_unlock(&le->wait.lock);
857 if (filep->f_flags & O_NONBLOCK) {
858 spin_unlock(&le->wait.lock);
862 ret = wait_event_interruptible_locked(le->wait,
863 !kfifo_is_empty(&le->events));
865 spin_unlock(&le->wait.lock);
870 ret = kfifo_out(&le->events, &ge, 1);
871 spin_unlock(&le->wait.lock);
874 * This should never happen - we were holding the lock
875 * from the moment we learned the fifo is no longer
882 if (copy_to_user(buf + bytes_read, &ge, sizeof(ge)))
884 bytes_read += sizeof(ge);
885 } while (count >= bytes_read + sizeof(ge));
890 static int lineevent_release(struct inode *inode, struct file *filep)
892 struct lineevent_state *le = filep->private_data;
893 struct gpio_device *gdev = le->gdev;
895 free_irq(le->irq, le);
896 gpiod_free(le->desc);
899 put_device(&gdev->dev);
903 static long lineevent_ioctl(struct file *filep, unsigned int cmd,
906 struct lineevent_state *le = filep->private_data;
907 void __user *ip = (void __user *)arg;
908 struct gpiohandle_data ghd;
911 * We can get the value for an event line but not set it,
912 * because it is input by definition.
914 if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
917 memset(&ghd, 0, sizeof(ghd));
919 val = gpiod_get_value_cansleep(le->desc);
924 if (copy_to_user(ip, &ghd, sizeof(ghd)))
933 static long lineevent_ioctl_compat(struct file *filep, unsigned int cmd,
936 return lineevent_ioctl(filep, cmd, (unsigned long)compat_ptr(arg));
940 static const struct file_operations lineevent_fileops = {
941 .release = lineevent_release,
942 .read = lineevent_read,
943 .poll = lineevent_poll,
944 .owner = THIS_MODULE,
945 .llseek = noop_llseek,
946 .unlocked_ioctl = lineevent_ioctl,
948 .compat_ioctl = lineevent_ioctl_compat,
952 static irqreturn_t lineevent_irq_thread(int irq, void *p)
954 struct lineevent_state *le = p;
955 struct gpioevent_data ge;
958 /* Do not leak kernel stack to userspace */
959 memset(&ge, 0, sizeof(ge));
962 * We may be running from a nested threaded interrupt in which case
963 * we didn't get the timestamp from lineevent_irq_handler().
966 ge.timestamp = ktime_get_ns();
968 ge.timestamp = le->timestamp;
970 if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE
971 && le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
972 int level = gpiod_get_value_cansleep(le->desc);
974 /* Emit low-to-high event */
975 ge.id = GPIOEVENT_EVENT_RISING_EDGE;
977 /* Emit high-to-low event */
978 ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
979 } else if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE) {
980 /* Emit low-to-high event */
981 ge.id = GPIOEVENT_EVENT_RISING_EDGE;
982 } else if (le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
983 /* Emit high-to-low event */
984 ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
989 ret = kfifo_in_spinlocked_noirqsave(&le->events, &ge,
992 wake_up_poll(&le->wait, EPOLLIN);
994 pr_debug_ratelimited("event FIFO is full - event dropped\n");
999 static irqreturn_t lineevent_irq_handler(int irq, void *p)
1001 struct lineevent_state *le = p;
1004 * Just store the timestamp in hardirq context so we get it as
1005 * close in time as possible to the actual event.
1007 le->timestamp = ktime_get_ns();
1009 return IRQ_WAKE_THREAD;
1012 static int lineevent_create(struct gpio_device *gdev, void __user *ip)
1014 struct gpioevent_request eventreq;
1015 struct lineevent_state *le;
1016 struct gpio_desc *desc;
1025 if (copy_from_user(&eventreq, ip, sizeof(eventreq)))
1028 offset = eventreq.lineoffset;
1029 lflags = eventreq.handleflags;
1030 eflags = eventreq.eventflags;
1032 desc = gpiochip_get_desc(gdev->chip, offset);
1034 return PTR_ERR(desc);
1036 /* Return an error if a unknown flag is set */
1037 if ((lflags & ~GPIOHANDLE_REQUEST_VALID_FLAGS) ||
1038 (eflags & ~GPIOEVENT_REQUEST_VALID_FLAGS))
1041 /* This is just wrong: we don't look for events on output lines */
1042 if ((lflags & GPIOHANDLE_REQUEST_OUTPUT) ||
1043 (lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN) ||
1044 (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE))
1047 /* Only one bias flag can be set. */
1048 if (((lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE) &&
1049 (lflags & (GPIOHANDLE_REQUEST_BIAS_PULL_DOWN |
1050 GPIOHANDLE_REQUEST_BIAS_PULL_UP))) ||
1051 ((lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN) &&
1052 (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)))
1055 le = kzalloc(sizeof(*le), GFP_KERNEL);
1059 get_device(&gdev->dev);
1061 /* Make sure this is terminated */
1062 eventreq.consumer_label[sizeof(eventreq.consumer_label)-1] = '\0';
1063 if (strlen(eventreq.consumer_label)) {
1064 le->label = kstrdup(eventreq.consumer_label,
1072 ret = gpiod_request(desc, le->label);
1074 goto out_free_label;
1076 le->eflags = eflags;
1078 if (lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW)
1079 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
1080 if (lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE)
1081 set_bit(FLAG_BIAS_DISABLE, &desc->flags);
1082 if (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN)
1083 set_bit(FLAG_PULL_DOWN, &desc->flags);
1084 if (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)
1085 set_bit(FLAG_PULL_UP, &desc->flags);
1087 ret = gpiod_direction_input(desc);
1091 le->irq = gpiod_to_irq(desc);
1097 if (eflags & GPIOEVENT_REQUEST_RISING_EDGE)
1098 irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
1099 IRQF_TRIGGER_FALLING : IRQF_TRIGGER_RISING;
1100 if (eflags & GPIOEVENT_REQUEST_FALLING_EDGE)
1101 irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
1102 IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING;
1103 irqflags |= IRQF_ONESHOT;
1105 INIT_KFIFO(le->events);
1106 init_waitqueue_head(&le->wait);
1108 /* Request a thread to read the events */
1109 ret = request_threaded_irq(le->irq,
1110 lineevent_irq_handler,
1111 lineevent_irq_thread,
1118 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
1124 file = anon_inode_getfile("gpio-event",
1127 O_RDONLY | O_CLOEXEC);
1129 ret = PTR_ERR(file);
1130 goto out_put_unused_fd;
1134 if (copy_to_user(ip, &eventreq, sizeof(eventreq))) {
1136 * fput() will trigger the release() callback, so do not go onto
1137 * the regular error cleanup path here.
1144 fd_install(fd, file);
1151 free_irq(le->irq, le);
1153 gpiod_free(le->desc);
1158 put_device(&gdev->dev);
1162 static void gpio_desc_to_lineinfo(struct gpio_desc *desc,
1163 struct gpioline_info *info)
1165 struct gpio_chip *gc = desc->gdev->chip;
1166 unsigned long flags;
1168 spin_lock_irqsave(&gpio_lock, flags);
1171 strncpy(info->name, desc->name, sizeof(info->name));
1172 info->name[sizeof(info->name) - 1] = '\0';
1174 info->name[0] = '\0';
1178 strncpy(info->consumer, desc->label, sizeof(info->consumer));
1179 info->consumer[sizeof(info->consumer) - 1] = '\0';
1181 info->consumer[0] = '\0';
1185 * Userspace only need to know that the kernel is using this GPIO so
1189 if (test_bit(FLAG_REQUESTED, &desc->flags) ||
1190 test_bit(FLAG_IS_HOGGED, &desc->flags) ||
1191 test_bit(FLAG_USED_AS_IRQ, &desc->flags) ||
1192 test_bit(FLAG_EXPORT, &desc->flags) ||
1193 test_bit(FLAG_SYSFS, &desc->flags) ||
1194 !pinctrl_gpio_can_use_line(gc->base + info->line_offset))
1195 info->flags |= GPIOLINE_FLAG_KERNEL;
1196 if (test_bit(FLAG_IS_OUT, &desc->flags))
1197 info->flags |= GPIOLINE_FLAG_IS_OUT;
1198 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
1199 info->flags |= GPIOLINE_FLAG_ACTIVE_LOW;
1200 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
1201 info->flags |= (GPIOLINE_FLAG_OPEN_DRAIN |
1202 GPIOLINE_FLAG_IS_OUT);
1203 if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
1204 info->flags |= (GPIOLINE_FLAG_OPEN_SOURCE |
1205 GPIOLINE_FLAG_IS_OUT);
1206 if (test_bit(FLAG_BIAS_DISABLE, &desc->flags))
1207 info->flags |= GPIOLINE_FLAG_BIAS_DISABLE;
1208 if (test_bit(FLAG_PULL_DOWN, &desc->flags))
1209 info->flags |= GPIOLINE_FLAG_BIAS_PULL_DOWN;
1210 if (test_bit(FLAG_PULL_UP, &desc->flags))
1211 info->flags |= GPIOLINE_FLAG_BIAS_PULL_UP;
1213 spin_unlock_irqrestore(&gpio_lock, flags);
1216 struct gpio_chardev_data {
1217 struct gpio_device *gdev;
1218 wait_queue_head_t wait;
1219 DECLARE_KFIFO(events, struct gpioline_info_changed, 32);
1220 struct notifier_block lineinfo_changed_nb;
1221 unsigned long *watched_lines;
1225 * gpio_ioctl() - ioctl handler for the GPIO chardev
1227 static long gpio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1229 struct gpio_chardev_data *priv = filp->private_data;
1230 struct gpio_device *gdev = priv->gdev;
1231 struct gpio_chip *gc = gdev->chip;
1232 void __user *ip = (void __user *)arg;
1233 struct gpio_desc *desc;
1236 /* We fail any subsequent ioctl():s when the chip is gone */
1240 /* Fill in the struct and pass to userspace */
1241 if (cmd == GPIO_GET_CHIPINFO_IOCTL) {
1242 struct gpiochip_info chipinfo;
1244 memset(&chipinfo, 0, sizeof(chipinfo));
1246 strncpy(chipinfo.name, dev_name(&gdev->dev),
1247 sizeof(chipinfo.name));
1248 chipinfo.name[sizeof(chipinfo.name)-1] = '\0';
1249 strncpy(chipinfo.label, gdev->label,
1250 sizeof(chipinfo.label));
1251 chipinfo.label[sizeof(chipinfo.label)-1] = '\0';
1252 chipinfo.lines = gdev->ngpio;
1253 if (copy_to_user(ip, &chipinfo, sizeof(chipinfo)))
1256 } else if (cmd == GPIO_GET_LINEINFO_IOCTL ||
1257 cmd == GPIO_GET_LINEINFO_WATCH_IOCTL) {
1258 struct gpioline_info lineinfo;
1260 if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
1263 desc = gpiochip_get_desc(gc, lineinfo.line_offset);
1265 return PTR_ERR(desc);
1267 gpio_desc_to_lineinfo(desc, &lineinfo);
1269 if (copy_to_user(ip, &lineinfo, sizeof(lineinfo)))
1272 if (cmd == GPIO_GET_LINEINFO_WATCH_IOCTL)
1273 set_bit(gpio_chip_hwgpio(desc), priv->watched_lines);
1276 } else if (cmd == GPIO_GET_LINEHANDLE_IOCTL) {
1277 return linehandle_create(gdev, ip);
1278 } else if (cmd == GPIO_GET_LINEEVENT_IOCTL) {
1279 return lineevent_create(gdev, ip);
1280 } else if (cmd == GPIO_GET_LINEINFO_UNWATCH_IOCTL) {
1281 if (copy_from_user(&offset, ip, sizeof(offset)))
1284 desc = gpiochip_get_desc(gc, offset);
1286 return PTR_ERR(desc);
1288 clear_bit(gpio_chip_hwgpio(desc), priv->watched_lines);
1294 #ifdef CONFIG_COMPAT
1295 static long gpio_ioctl_compat(struct file *filp, unsigned int cmd,
1298 return gpio_ioctl(filp, cmd, (unsigned long)compat_ptr(arg));
1302 static struct gpio_chardev_data *
1303 to_gpio_chardev_data(struct notifier_block *nb)
1305 return container_of(nb, struct gpio_chardev_data, lineinfo_changed_nb);
1308 static int lineinfo_changed_notify(struct notifier_block *nb,
1309 unsigned long action, void *data)
1311 struct gpio_chardev_data *priv = to_gpio_chardev_data(nb);
1312 struct gpioline_info_changed chg;
1313 struct gpio_desc *desc = data;
1316 if (!test_bit(gpio_chip_hwgpio(desc), priv->watched_lines))
1319 memset(&chg, 0, sizeof(chg));
1320 chg.info.line_offset = gpio_chip_hwgpio(desc);
1321 chg.event_type = action;
1322 chg.timestamp = ktime_get_ns();
1323 gpio_desc_to_lineinfo(desc, &chg.info);
1325 ret = kfifo_in_spinlocked(&priv->events, &chg, 1, &priv->wait.lock);
1327 wake_up_poll(&priv->wait, EPOLLIN);
1329 pr_debug_ratelimited("lineinfo event FIFO is full - event dropped\n");
1334 static __poll_t lineinfo_watch_poll(struct file *filep,
1335 struct poll_table_struct *pollt)
1337 struct gpio_chardev_data *priv = filep->private_data;
1338 __poll_t events = 0;
1340 poll_wait(filep, &priv->wait, pollt);
1342 if (!kfifo_is_empty_spinlocked_noirqsave(&priv->events,
1344 events = EPOLLIN | EPOLLRDNORM;
1349 static ssize_t lineinfo_watch_read(struct file *filep, char __user *buf,
1350 size_t count, loff_t *off)
1352 struct gpio_chardev_data *priv = filep->private_data;
1353 struct gpioline_info_changed event;
1354 ssize_t bytes_read = 0;
1357 if (count < sizeof(event))
1361 spin_lock(&priv->wait.lock);
1362 if (kfifo_is_empty(&priv->events)) {
1364 spin_unlock(&priv->wait.lock);
1368 if (filep->f_flags & O_NONBLOCK) {
1369 spin_unlock(&priv->wait.lock);
1373 ret = wait_event_interruptible_locked(priv->wait,
1374 !kfifo_is_empty(&priv->events));
1376 spin_unlock(&priv->wait.lock);
1381 ret = kfifo_out(&priv->events, &event, 1);
1382 spin_unlock(&priv->wait.lock);
1386 /* We should never get here. See lineevent_read(). */
1389 if (copy_to_user(buf + bytes_read, &event, sizeof(event)))
1391 bytes_read += sizeof(event);
1392 } while (count >= bytes_read + sizeof(event));
1398 * gpio_chrdev_open() - open the chardev for ioctl operations
1399 * @inode: inode for this chardev
1400 * @filp: file struct for storing private data
1401 * Returns 0 on success
1403 static int gpio_chrdev_open(struct inode *inode, struct file *filp)
1405 struct gpio_device *gdev = container_of(inode->i_cdev,
1406 struct gpio_device, chrdev);
1407 struct gpio_chardev_data *priv;
1410 /* Fail on open if the backing gpiochip is gone */
1414 priv = kzalloc(sizeof(*priv), GFP_KERNEL);
1418 priv->watched_lines = bitmap_zalloc(gdev->chip->ngpio, GFP_KERNEL);
1419 if (!priv->watched_lines)
1422 init_waitqueue_head(&priv->wait);
1423 INIT_KFIFO(priv->events);
1426 priv->lineinfo_changed_nb.notifier_call = lineinfo_changed_notify;
1427 ret = atomic_notifier_chain_register(&gdev->notifier,
1428 &priv->lineinfo_changed_nb);
1430 goto out_free_bitmap;
1432 get_device(&gdev->dev);
1433 filp->private_data = priv;
1435 ret = nonseekable_open(inode, filp);
1437 goto out_unregister_notifier;
1441 out_unregister_notifier:
1442 atomic_notifier_chain_unregister(&gdev->notifier,
1443 &priv->lineinfo_changed_nb);
1445 bitmap_free(priv->watched_lines);
1452 * gpio_chrdev_release() - close chardev after ioctl operations
1453 * @inode: inode for this chardev
1454 * @filp: file struct for storing private data
1455 * Returns 0 on success
1457 static int gpio_chrdev_release(struct inode *inode, struct file *filp)
1459 struct gpio_chardev_data *priv = filp->private_data;
1460 struct gpio_device *gdev = priv->gdev;
1462 bitmap_free(priv->watched_lines);
1463 atomic_notifier_chain_unregister(&gdev->notifier,
1464 &priv->lineinfo_changed_nb);
1465 put_device(&gdev->dev);
1471 static const struct file_operations gpio_fileops = {
1472 .release = gpio_chrdev_release,
1473 .open = gpio_chrdev_open,
1474 .poll = lineinfo_watch_poll,
1475 .read = lineinfo_watch_read,
1476 .owner = THIS_MODULE,
1477 .llseek = no_llseek,
1478 .unlocked_ioctl = gpio_ioctl,
1479 #ifdef CONFIG_COMPAT
1480 .compat_ioctl = gpio_ioctl_compat,
1484 static void gpiodevice_release(struct device *dev)
1486 struct gpio_device *gdev = dev_get_drvdata(dev);
1488 list_del(&gdev->list);
1489 ida_simple_remove(&gpio_ida, gdev->id);
1490 kfree_const(gdev->label);
1495 static int gpiochip_setup_dev(struct gpio_device *gdev)
1499 cdev_init(&gdev->chrdev, &gpio_fileops);
1500 gdev->chrdev.owner = THIS_MODULE;
1501 gdev->dev.devt = MKDEV(MAJOR(gpio_devt), gdev->id);
1503 ret = cdev_device_add(&gdev->chrdev, &gdev->dev);
1507 chip_dbg(gdev->chip, "added GPIO chardev (%d:%d)\n",
1508 MAJOR(gpio_devt), gdev->id);
1510 ret = gpiochip_sysfs_register(gdev);
1512 goto err_remove_device;
1514 /* From this point, the .release() function cleans up gpio_device */
1515 gdev->dev.release = gpiodevice_release;
1516 dev_dbg(&gdev->dev, "registered GPIOs %d to %d on %s\n", gdev->base,
1517 gdev->base + gdev->ngpio - 1, gdev->chip->label ? : "generic");
1522 cdev_device_del(&gdev->chrdev, &gdev->dev);
1526 static void gpiochip_machine_hog(struct gpio_chip *gc, struct gpiod_hog *hog)
1528 struct gpio_desc *desc;
1531 desc = gpiochip_get_desc(gc, hog->chip_hwnum);
1533 chip_err(gc, "%s: unable to get GPIO desc: %ld\n", __func__,
1538 if (test_bit(FLAG_IS_HOGGED, &desc->flags))
1541 rv = gpiod_hog(desc, hog->line_name, hog->lflags, hog->dflags);
1543 gpiod_err(desc, "%s: unable to hog GPIO line (%s:%u): %d\n",
1544 __func__, gc->label, hog->chip_hwnum, rv);
1547 static void machine_gpiochip_add(struct gpio_chip *gc)
1549 struct gpiod_hog *hog;
1551 mutex_lock(&gpio_machine_hogs_mutex);
1553 list_for_each_entry(hog, &gpio_machine_hogs, list) {
1554 if (!strcmp(gc->label, hog->chip_label))
1555 gpiochip_machine_hog(gc, hog);
1558 mutex_unlock(&gpio_machine_hogs_mutex);
1561 static void gpiochip_setup_devs(void)
1563 struct gpio_device *gdev;
1566 list_for_each_entry(gdev, &gpio_devices, list) {
1567 ret = gpiochip_setup_dev(gdev);
1570 "Failed to initialize gpio device (%d)\n", ret);
1574 int gpiochip_add_data_with_key(struct gpio_chip *gc, void *data,
1575 struct lock_class_key *lock_key,
1576 struct lock_class_key *request_key)
1578 unsigned long flags;
1581 int base = gc->base;
1582 struct gpio_device *gdev;
1585 * First: allocate and populate the internal stat container, and
1586 * set up the struct device.
1588 gdev = kzalloc(sizeof(*gdev), GFP_KERNEL);
1591 gdev->dev.bus = &gpio_bus_type;
1595 gdev->dev.parent = gc->parent;
1596 gdev->dev.of_node = gc->parent->of_node;
1599 #ifdef CONFIG_OF_GPIO
1600 /* If the gpiochip has an assigned OF node this takes precedence */
1602 gdev->dev.of_node = gc->of_node;
1604 gc->of_node = gdev->dev.of_node;
1607 gdev->id = ida_simple_get(&gpio_ida, 0, 0, GFP_KERNEL);
1612 dev_set_name(&gdev->dev, GPIOCHIP_NAME "%d", gdev->id);
1613 device_initialize(&gdev->dev);
1614 dev_set_drvdata(&gdev->dev, gdev);
1615 if (gc->parent && gc->parent->driver)
1616 gdev->owner = gc->parent->driver->owner;
1618 /* TODO: remove chip->owner */
1619 gdev->owner = gc->owner;
1621 gdev->owner = THIS_MODULE;
1623 gdev->descs = kcalloc(gc->ngpio, sizeof(gdev->descs[0]), GFP_KERNEL);
1629 if (gc->ngpio == 0) {
1630 chip_err(gc, "tried to insert a GPIO chip with zero lines\n");
1632 goto err_free_descs;
1635 if (gc->ngpio > FASTPATH_NGPIO)
1636 chip_warn(gc, "line cnt %u is greater than fast path cnt %u\n",
1637 gc->ngpio, FASTPATH_NGPIO);
1639 gdev->label = kstrdup_const(gc->label ?: "unknown", GFP_KERNEL);
1642 goto err_free_descs;
1645 gdev->ngpio = gc->ngpio;
1648 spin_lock_irqsave(&gpio_lock, flags);
1651 * TODO: this allocates a Linux GPIO number base in the global
1652 * GPIO numberspace for this chip. In the long run we want to
1653 * get *rid* of this numberspace and use only descriptors, but
1654 * it may be a pipe dream. It will not happen before we get rid
1655 * of the sysfs interface anyways.
1658 base = gpiochip_find_base(gc->ngpio);
1661 spin_unlock_irqrestore(&gpio_lock, flags);
1662 goto err_free_label;
1665 * TODO: it should not be necessary to reflect the assigned
1666 * base outside of the GPIO subsystem. Go over drivers and
1667 * see if anyone makes use of this, else drop this and assign
1674 ret = gpiodev_add_to_list(gdev);
1676 spin_unlock_irqrestore(&gpio_lock, flags);
1677 goto err_free_label;
1680 for (i = 0; i < gc->ngpio; i++)
1681 gdev->descs[i].gdev = gdev;
1683 spin_unlock_irqrestore(&gpio_lock, flags);
1685 ATOMIC_INIT_NOTIFIER_HEAD(&gdev->notifier);
1687 #ifdef CONFIG_PINCTRL
1688 INIT_LIST_HEAD(&gdev->pin_ranges);
1691 ret = gpiochip_set_desc_names(gc);
1693 goto err_remove_from_list;
1695 ret = gpiochip_alloc_valid_mask(gc);
1697 goto err_remove_from_list;
1699 ret = of_gpiochip_add(gc);
1701 goto err_free_gpiochip_mask;
1703 ret = gpiochip_init_valid_mask(gc);
1705 goto err_remove_of_chip;
1707 for (i = 0; i < gc->ngpio; i++) {
1708 struct gpio_desc *desc = &gdev->descs[i];
1710 if (gc->get_direction && gpiochip_line_is_valid(gc, i)) {
1711 assign_bit(FLAG_IS_OUT,
1712 &desc->flags, !gc->get_direction(gc, i));
1714 assign_bit(FLAG_IS_OUT,
1715 &desc->flags, !gc->direction_input);
1719 ret = gpiochip_add_pin_ranges(gc);
1721 goto err_remove_of_chip;
1723 acpi_gpiochip_add(gc);
1725 machine_gpiochip_add(gc);
1727 ret = gpiochip_irqchip_init_valid_mask(gc);
1729 goto err_remove_acpi_chip;
1731 ret = gpiochip_irqchip_init_hw(gc);
1733 goto err_remove_acpi_chip;
1735 ret = gpiochip_add_irqchip(gc, lock_key, request_key);
1737 goto err_remove_irqchip_mask;
1740 * By first adding the chardev, and then adding the device,
1741 * we get a device node entry in sysfs under
1742 * /sys/bus/gpio/devices/gpiochipN/dev that can be used for
1743 * coldplug of device nodes and other udev business.
1744 * We can do this only if gpiolib has been initialized.
1745 * Otherwise, defer until later.
1747 if (gpiolib_initialized) {
1748 ret = gpiochip_setup_dev(gdev);
1750 goto err_remove_irqchip;
1755 gpiochip_irqchip_remove(gc);
1756 err_remove_irqchip_mask:
1757 gpiochip_irqchip_free_valid_mask(gc);
1758 err_remove_acpi_chip:
1759 acpi_gpiochip_remove(gc);
1761 gpiochip_free_hogs(gc);
1762 of_gpiochip_remove(gc);
1763 err_free_gpiochip_mask:
1764 gpiochip_remove_pin_ranges(gc);
1765 gpiochip_free_valid_mask(gc);
1766 err_remove_from_list:
1767 spin_lock_irqsave(&gpio_lock, flags);
1768 list_del(&gdev->list);
1769 spin_unlock_irqrestore(&gpio_lock, flags);
1771 kfree_const(gdev->label);
1775 ida_simple_remove(&gpio_ida, gdev->id);
1777 /* failures here can mean systems won't boot... */
1778 pr_err("%s: GPIOs %d..%d (%s) failed to register, %d\n", __func__,
1779 gdev->base, gdev->base + gdev->ngpio - 1,
1780 gc->label ? : "generic", ret);
1784 EXPORT_SYMBOL_GPL(gpiochip_add_data_with_key);
1787 * gpiochip_get_data() - get per-subdriver data for the chip
1791 * The per-subdriver data for the chip.
1793 void *gpiochip_get_data(struct gpio_chip *gc)
1795 return gc->gpiodev->data;
1797 EXPORT_SYMBOL_GPL(gpiochip_get_data);
1800 * gpiochip_remove() - unregister a gpio_chip
1801 * @gc: the chip to unregister
1803 * A gpio_chip with any GPIOs still requested may not be removed.
1805 void gpiochip_remove(struct gpio_chip *gc)
1807 struct gpio_device *gdev = gc->gpiodev;
1808 unsigned long flags;
1811 /* FIXME: should the legacy sysfs handling be moved to gpio_device? */
1812 gpiochip_sysfs_unregister(gdev);
1813 gpiochip_free_hogs(gc);
1814 /* Numb the device, cancelling all outstanding operations */
1816 gpiochip_irqchip_remove(gc);
1817 acpi_gpiochip_remove(gc);
1818 of_gpiochip_remove(gc);
1819 gpiochip_remove_pin_ranges(gc);
1820 gpiochip_free_valid_mask(gc);
1822 * We accept no more calls into the driver from this point, so
1823 * NULL the driver data pointer
1827 spin_lock_irqsave(&gpio_lock, flags);
1828 for (i = 0; i < gdev->ngpio; i++) {
1829 if (gpiochip_is_requested(gc, i))
1832 spin_unlock_irqrestore(&gpio_lock, flags);
1834 if (i != gdev->ngpio)
1835 dev_crit(&gdev->dev,
1836 "REMOVING GPIOCHIP WITH GPIOS STILL REQUESTED\n");
1839 * The gpiochip side puts its use of the device to rest here:
1840 * if there are no userspace clients, the chardev and device will
1841 * be removed, else it will be dangling until the last user is
1844 cdev_device_del(&gdev->chrdev, &gdev->dev);
1845 put_device(&gdev->dev);
1847 EXPORT_SYMBOL_GPL(gpiochip_remove);
1850 * gpiochip_find() - iterator for locating a specific gpio_chip
1851 * @data: data to pass to match function
1852 * @match: Callback function to check gpio_chip
1854 * Similar to bus_find_device. It returns a reference to a gpio_chip as
1855 * determined by a user supplied @match callback. The callback should return
1856 * 0 if the device doesn't match and non-zero if it does. If the callback is
1857 * non-zero, this function will return to the caller and not iterate over any
1860 struct gpio_chip *gpiochip_find(void *data,
1861 int (*match)(struct gpio_chip *gc,
1864 struct gpio_device *gdev;
1865 struct gpio_chip *gc = NULL;
1866 unsigned long flags;
1868 spin_lock_irqsave(&gpio_lock, flags);
1869 list_for_each_entry(gdev, &gpio_devices, list)
1870 if (gdev->chip && match(gdev->chip, data)) {
1875 spin_unlock_irqrestore(&gpio_lock, flags);
1879 EXPORT_SYMBOL_GPL(gpiochip_find);
1881 static int gpiochip_match_name(struct gpio_chip *gc, void *data)
1883 const char *name = data;
1885 return !strcmp(gc->label, name);
1888 static struct gpio_chip *find_chip_by_name(const char *name)
1890 return gpiochip_find((void *)name, gpiochip_match_name);
1893 #ifdef CONFIG_GPIOLIB_IRQCHIP
1896 * The following is irqchip helper code for gpiochips.
1899 static int gpiochip_irqchip_init_hw(struct gpio_chip *gc)
1901 struct gpio_irq_chip *girq = &gc->irq;
1906 return girq->init_hw(gc);
1909 static int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gc)
1911 struct gpio_irq_chip *girq = &gc->irq;
1913 if (!girq->init_valid_mask)
1916 girq->valid_mask = gpiochip_allocate_mask(gc);
1917 if (!girq->valid_mask)
1920 girq->init_valid_mask(gc, girq->valid_mask, gc->ngpio);
1925 static void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gc)
1927 bitmap_free(gc->irq.valid_mask);
1928 gc->irq.valid_mask = NULL;
1931 bool gpiochip_irqchip_irq_valid(const struct gpio_chip *gc,
1932 unsigned int offset)
1934 if (!gpiochip_line_is_valid(gc, offset))
1936 /* No mask means all valid */
1937 if (likely(!gc->irq.valid_mask))
1939 return test_bit(offset, gc->irq.valid_mask);
1941 EXPORT_SYMBOL_GPL(gpiochip_irqchip_irq_valid);
1944 * gpiochip_set_cascaded_irqchip() - connects a cascaded irqchip to a gpiochip
1945 * @gc: the gpiochip to set the irqchip chain to
1946 * @parent_irq: the irq number corresponding to the parent IRQ for this
1948 * @parent_handler: the parent interrupt handler for the accumulated IRQ
1949 * coming out of the gpiochip. If the interrupt is nested rather than
1950 * cascaded, pass NULL in this handler argument
1952 static void gpiochip_set_cascaded_irqchip(struct gpio_chip *gc,
1953 unsigned int parent_irq,
1954 irq_flow_handler_t parent_handler)
1956 struct gpio_irq_chip *girq = &gc->irq;
1957 struct device *dev = &gc->gpiodev->dev;
1959 if (!girq->domain) {
1960 chip_err(gc, "called %s before setting up irqchip\n",
1965 if (parent_handler) {
1966 if (gc->can_sleep) {
1968 "you cannot have chained interrupts on a chip that may sleep\n");
1971 girq->parents = devm_kcalloc(dev, 1,
1972 sizeof(*girq->parents),
1974 if (!girq->parents) {
1975 chip_err(gc, "out of memory allocating parent IRQ\n");
1978 girq->parents[0] = parent_irq;
1979 girq->num_parents = 1;
1981 * The parent irqchip is already using the chip_data for this
1982 * irqchip, so our callbacks simply use the handler_data.
1984 irq_set_chained_handler_and_data(parent_irq, parent_handler,
1990 * gpiochip_set_nested_irqchip() - connects a nested irqchip to a gpiochip
1991 * @gc: the gpiochip to set the irqchip nested handler to
1992 * @irqchip: the irqchip to nest to the gpiochip
1993 * @parent_irq: the irq number corresponding to the parent IRQ for this
1996 void gpiochip_set_nested_irqchip(struct gpio_chip *gc,
1997 struct irq_chip *irqchip,
1998 unsigned int parent_irq)
2000 gpiochip_set_cascaded_irqchip(gc, parent_irq, NULL);
2002 EXPORT_SYMBOL_GPL(gpiochip_set_nested_irqchip);
2004 #ifdef CONFIG_IRQ_DOMAIN_HIERARCHY
2007 * gpiochip_set_hierarchical_irqchip() - connects a hierarchical irqchip
2009 * @gc: the gpiochip to set the irqchip hierarchical handler to
2010 * @irqchip: the irqchip to handle this level of the hierarchy, the interrupt
2011 * will then percolate up to the parent
2013 static void gpiochip_set_hierarchical_irqchip(struct gpio_chip *gc,
2014 struct irq_chip *irqchip)
2016 /* DT will deal with mapping each IRQ as we go along */
2017 if (is_of_node(gc->irq.fwnode))
2021 * This is for legacy and boardfile "irqchip" fwnodes: allocate
2022 * irqs upfront instead of dynamically since we don't have the
2023 * dynamic type of allocation that hardware description languages
2024 * provide. Once all GPIO drivers using board files are gone from
2025 * the kernel we can delete this code, but for a transitional period
2026 * it is necessary to keep this around.
2028 if (is_fwnode_irqchip(gc->irq.fwnode)) {
2032 for (i = 0; i < gc->ngpio; i++) {
2033 struct irq_fwspec fwspec;
2034 unsigned int parent_hwirq;
2035 unsigned int parent_type;
2036 struct gpio_irq_chip *girq = &gc->irq;
2039 * We call the child to parent translation function
2040 * only to check if the child IRQ is valid or not.
2041 * Just pick the rising edge type here as that is what
2042 * we likely need to support.
2044 ret = girq->child_to_parent_hwirq(gc, i,
2045 IRQ_TYPE_EDGE_RISING,
2049 chip_err(gc, "skip set-up on hwirq %d\n",
2054 fwspec.fwnode = gc->irq.fwnode;
2055 /* This is the hwirq for the GPIO line side of things */
2056 fwspec.param[0] = girq->child_offset_to_irq(gc, i);
2057 /* Just pick something */
2058 fwspec.param[1] = IRQ_TYPE_EDGE_RISING;
2059 fwspec.param_count = 2;
2060 ret = __irq_domain_alloc_irqs(gc->irq.domain,
2061 /* just pick something */
2070 "can not allocate irq for GPIO line %d parent hwirq %d in hierarchy domain: %d\n",
2077 chip_err(gc, "%s unknown fwnode type proceed anyway\n", __func__);
2082 static int gpiochip_hierarchy_irq_domain_translate(struct irq_domain *d,
2083 struct irq_fwspec *fwspec,
2084 unsigned long *hwirq,
2087 /* We support standard DT translation */
2088 if (is_of_node(fwspec->fwnode) && fwspec->param_count == 2) {
2089 return irq_domain_translate_twocell(d, fwspec, hwirq, type);
2092 /* This is for board files and others not using DT */
2093 if (is_fwnode_irqchip(fwspec->fwnode)) {
2096 ret = irq_domain_translate_twocell(d, fwspec, hwirq, type);
2099 WARN_ON(*type == IRQ_TYPE_NONE);
2105 static int gpiochip_hierarchy_irq_domain_alloc(struct irq_domain *d,
2107 unsigned int nr_irqs,
2110 struct gpio_chip *gc = d->host_data;
2111 irq_hw_number_t hwirq;
2112 unsigned int type = IRQ_TYPE_NONE;
2113 struct irq_fwspec *fwspec = data;
2115 unsigned int parent_hwirq;
2116 unsigned int parent_type;
2117 struct gpio_irq_chip *girq = &gc->irq;
2121 * The nr_irqs parameter is always one except for PCI multi-MSI
2122 * so this should not happen.
2124 WARN_ON(nr_irqs != 1);
2126 ret = gc->irq.child_irq_domain_ops.translate(d, fwspec, &hwirq, &type);
2130 chip_dbg(gc, "allocate IRQ %d, hwirq %lu\n", irq, hwirq);
2132 ret = girq->child_to_parent_hwirq(gc, hwirq, type,
2133 &parent_hwirq, &parent_type);
2135 chip_err(gc, "can't look up hwirq %lu\n", hwirq);
2138 chip_dbg(gc, "found parent hwirq %u\n", parent_hwirq);
2141 * We set handle_bad_irq because the .set_type() should
2142 * always be invoked and set the right type of handler.
2144 irq_domain_set_info(d,
2153 /* This parent only handles asserted level IRQs */
2154 parent_arg = girq->populate_parent_alloc_arg(gc, parent_hwirq, parent_type);
2158 chip_dbg(gc, "alloc_irqs_parent for %d parent hwirq %d\n",
2160 irq_set_lockdep_class(irq, gc->irq.lock_key, gc->irq.request_key);
2161 ret = irq_domain_alloc_irqs_parent(d, irq, 1, parent_arg);
2163 * If the parent irqdomain is msi, the interrupts have already
2164 * been allocated, so the EEXIST is good.
2166 if (irq_domain_is_msi(d->parent) && (ret == -EEXIST))
2170 "failed to allocate parent hwirq %d for hwirq %lu\n",
2171 parent_hwirq, hwirq);
2177 static unsigned int gpiochip_child_offset_to_irq_noop(struct gpio_chip *gc,
2178 unsigned int offset)
2183 static void gpiochip_hierarchy_setup_domain_ops(struct irq_domain_ops *ops)
2185 ops->activate = gpiochip_irq_domain_activate;
2186 ops->deactivate = gpiochip_irq_domain_deactivate;
2187 ops->alloc = gpiochip_hierarchy_irq_domain_alloc;
2188 ops->free = irq_domain_free_irqs_common;
2191 * We only allow overriding the translate() function for
2192 * hierarchical chips, and this should only be done if the user
2193 * really need something other than 1:1 translation.
2195 if (!ops->translate)
2196 ops->translate = gpiochip_hierarchy_irq_domain_translate;
2199 static int gpiochip_hierarchy_add_domain(struct gpio_chip *gc)
2201 if (!gc->irq.child_to_parent_hwirq ||
2203 chip_err(gc, "missing irqdomain vital data\n");
2207 if (!gc->irq.child_offset_to_irq)
2208 gc->irq.child_offset_to_irq = gpiochip_child_offset_to_irq_noop;
2210 if (!gc->irq.populate_parent_alloc_arg)
2211 gc->irq.populate_parent_alloc_arg =
2212 gpiochip_populate_parent_fwspec_twocell;
2214 gpiochip_hierarchy_setup_domain_ops(&gc->irq.child_irq_domain_ops);
2216 gc->irq.domain = irq_domain_create_hierarchy(
2217 gc->irq.parent_domain,
2221 &gc->irq.child_irq_domain_ops,
2224 if (!gc->irq.domain)
2227 gpiochip_set_hierarchical_irqchip(gc, gc->irq.chip);
2232 static bool gpiochip_hierarchy_is_hierarchical(struct gpio_chip *gc)
2234 return !!gc->irq.parent_domain;
2237 void *gpiochip_populate_parent_fwspec_twocell(struct gpio_chip *gc,
2238 unsigned int parent_hwirq,
2239 unsigned int parent_type)
2241 struct irq_fwspec *fwspec;
2243 fwspec = kmalloc(sizeof(*fwspec), GFP_KERNEL);
2247 fwspec->fwnode = gc->irq.parent_domain->fwnode;
2248 fwspec->param_count = 2;
2249 fwspec->param[0] = parent_hwirq;
2250 fwspec->param[1] = parent_type;
2254 EXPORT_SYMBOL_GPL(gpiochip_populate_parent_fwspec_twocell);
2256 void *gpiochip_populate_parent_fwspec_fourcell(struct gpio_chip *gc,
2257 unsigned int parent_hwirq,
2258 unsigned int parent_type)
2260 struct irq_fwspec *fwspec;
2262 fwspec = kmalloc(sizeof(*fwspec), GFP_KERNEL);
2266 fwspec->fwnode = gc->irq.parent_domain->fwnode;
2267 fwspec->param_count = 4;
2268 fwspec->param[0] = 0;
2269 fwspec->param[1] = parent_hwirq;
2270 fwspec->param[2] = 0;
2271 fwspec->param[3] = parent_type;
2275 EXPORT_SYMBOL_GPL(gpiochip_populate_parent_fwspec_fourcell);
2279 static int gpiochip_hierarchy_add_domain(struct gpio_chip *gc)
2284 static bool gpiochip_hierarchy_is_hierarchical(struct gpio_chip *gc)
2289 #endif /* CONFIG_IRQ_DOMAIN_HIERARCHY */
2292 * gpiochip_irq_map() - maps an IRQ into a GPIO irqchip
2293 * @d: the irqdomain used by this irqchip
2294 * @irq: the global irq number used by this GPIO irqchip irq
2295 * @hwirq: the local IRQ/GPIO line offset on this gpiochip
2297 * This function will set up the mapping for a certain IRQ line on a
2298 * gpiochip by assigning the gpiochip as chip data, and using the irqchip
2299 * stored inside the gpiochip.
2301 int gpiochip_irq_map(struct irq_domain *d, unsigned int irq,
2302 irq_hw_number_t hwirq)
2304 struct gpio_chip *gc = d->host_data;
2307 if (!gpiochip_irqchip_irq_valid(gc, hwirq))
2310 irq_set_chip_data(irq, gc);
2312 * This lock class tells lockdep that GPIO irqs are in a different
2313 * category than their parents, so it won't report false recursion.
2315 irq_set_lockdep_class(irq, gc->irq.lock_key, gc->irq.request_key);
2316 irq_set_chip_and_handler(irq, gc->irq.chip, gc->irq.handler);
2317 /* Chips that use nested thread handlers have them marked */
2318 if (gc->irq.threaded)
2319 irq_set_nested_thread(irq, 1);
2320 irq_set_noprobe(irq);
2322 if (gc->irq.num_parents == 1)
2323 ret = irq_set_parent(irq, gc->irq.parents[0]);
2324 else if (gc->irq.map)
2325 ret = irq_set_parent(irq, gc->irq.map[hwirq]);
2331 * No set-up of the hardware will happen if IRQ_TYPE_NONE
2332 * is passed as default type.
2334 if (gc->irq.default_type != IRQ_TYPE_NONE)
2335 irq_set_irq_type(irq, gc->irq.default_type);
2339 EXPORT_SYMBOL_GPL(gpiochip_irq_map);
2341 void gpiochip_irq_unmap(struct irq_domain *d, unsigned int irq)
2343 struct gpio_chip *gc = d->host_data;
2345 if (gc->irq.threaded)
2346 irq_set_nested_thread(irq, 0);
2347 irq_set_chip_and_handler(irq, NULL, NULL);
2348 irq_set_chip_data(irq, NULL);
2350 EXPORT_SYMBOL_GPL(gpiochip_irq_unmap);
2352 static const struct irq_domain_ops gpiochip_domain_ops = {
2353 .map = gpiochip_irq_map,
2354 .unmap = gpiochip_irq_unmap,
2355 /* Virtually all GPIO irqchips are twocell:ed */
2356 .xlate = irq_domain_xlate_twocell,
2360 * TODO: move these activate/deactivate in under the hierarchicial
2361 * irqchip implementation as static once SPMI and SSBI (all external
2362 * users) are phased over.
2365 * gpiochip_irq_domain_activate() - Lock a GPIO to be used as an IRQ
2366 * @domain: The IRQ domain used by this IRQ chip
2367 * @data: Outermost irq_data associated with the IRQ
2368 * @reserve: If set, only reserve an interrupt vector instead of assigning one
2370 * This function is a wrapper that calls gpiochip_lock_as_irq() and is to be
2371 * used as the activate function for the &struct irq_domain_ops. The host_data
2372 * for the IRQ domain must be the &struct gpio_chip.
2374 int gpiochip_irq_domain_activate(struct irq_domain *domain,
2375 struct irq_data *data, bool reserve)
2377 struct gpio_chip *gc = domain->host_data;
2379 return gpiochip_lock_as_irq(gc, data->hwirq);
2381 EXPORT_SYMBOL_GPL(gpiochip_irq_domain_activate);
2384 * gpiochip_irq_domain_deactivate() - Unlock a GPIO used as an IRQ
2385 * @domain: The IRQ domain used by this IRQ chip
2386 * @data: Outermost irq_data associated with the IRQ
2388 * This function is a wrapper that will call gpiochip_unlock_as_irq() and is to
2389 * be used as the deactivate function for the &struct irq_domain_ops. The
2390 * host_data for the IRQ domain must be the &struct gpio_chip.
2392 void gpiochip_irq_domain_deactivate(struct irq_domain *domain,
2393 struct irq_data *data)
2395 struct gpio_chip *gc = domain->host_data;
2397 return gpiochip_unlock_as_irq(gc, data->hwirq);
2399 EXPORT_SYMBOL_GPL(gpiochip_irq_domain_deactivate);
2401 static int gpiochip_to_irq(struct gpio_chip *gc, unsigned offset)
2403 struct irq_domain *domain = gc->irq.domain;
2405 if (!gpiochip_irqchip_irq_valid(gc, offset))
2408 #ifdef CONFIG_IRQ_DOMAIN_HIERARCHY
2409 if (irq_domain_is_hierarchy(domain)) {
2410 struct irq_fwspec spec;
2412 spec.fwnode = domain->fwnode;
2413 spec.param_count = 2;
2414 spec.param[0] = gc->irq.child_offset_to_irq(gc, offset);
2415 spec.param[1] = IRQ_TYPE_NONE;
2417 return irq_create_fwspec_mapping(&spec);
2421 return irq_create_mapping(domain, offset);
2424 static int gpiochip_irq_reqres(struct irq_data *d)
2426 struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
2428 return gpiochip_reqres_irq(gc, d->hwirq);
2431 static void gpiochip_irq_relres(struct irq_data *d)
2433 struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
2435 gpiochip_relres_irq(gc, d->hwirq);
2438 static void gpiochip_irq_enable(struct irq_data *d)
2440 struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
2442 gpiochip_enable_irq(gc, d->hwirq);
2443 if (gc->irq.irq_enable)
2444 gc->irq.irq_enable(d);
2446 gc->irq.chip->irq_unmask(d);
2449 static void gpiochip_irq_disable(struct irq_data *d)
2451 struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
2454 * Since we override .irq_disable() we need to mimic the
2455 * behaviour of __irq_disable() in irq/chip.c.
2456 * First call .irq_disable() if it exists, else mimic the
2457 * behaviour of mask_irq() which calls .irq_mask() if
2460 if (gc->irq.irq_disable)
2461 gc->irq.irq_disable(d);
2462 else if (gc->irq.chip->irq_mask)
2463 gc->irq.chip->irq_mask(d);
2464 gpiochip_disable_irq(gc, d->hwirq);
2467 static void gpiochip_set_irq_hooks(struct gpio_chip *gc)
2469 struct irq_chip *irqchip = gc->irq.chip;
2471 if (!irqchip->irq_request_resources &&
2472 !irqchip->irq_release_resources) {
2473 irqchip->irq_request_resources = gpiochip_irq_reqres;
2474 irqchip->irq_release_resources = gpiochip_irq_relres;
2476 if (WARN_ON(gc->irq.irq_enable))
2478 /* Check if the irqchip already has this hook... */
2479 if (irqchip->irq_enable == gpiochip_irq_enable) {
2481 * ...and if so, give a gentle warning that this is bad
2485 "detected irqchip that is shared with multiple gpiochips: please fix the driver.\n");
2488 gc->irq.irq_enable = irqchip->irq_enable;
2489 gc->irq.irq_disable = irqchip->irq_disable;
2490 irqchip->irq_enable = gpiochip_irq_enable;
2491 irqchip->irq_disable = gpiochip_irq_disable;
2495 * gpiochip_add_irqchip() - adds an IRQ chip to a GPIO chip
2496 * @gc: the GPIO chip to add the IRQ chip to
2497 * @lock_key: lockdep class for IRQ lock
2498 * @request_key: lockdep class for IRQ request
2500 static int gpiochip_add_irqchip(struct gpio_chip *gc,
2501 struct lock_class_key *lock_key,
2502 struct lock_class_key *request_key)
2504 struct irq_chip *irqchip = gc->irq.chip;
2505 const struct irq_domain_ops *ops = NULL;
2506 struct device_node *np;
2513 if (gc->irq.parent_handler && gc->can_sleep) {
2514 chip_err(gc, "you cannot have chained interrupts on a chip that may sleep\n");
2518 np = gc->gpiodev->dev.of_node;
2519 type = gc->irq.default_type;
2522 * Specifying a default trigger is a terrible idea if DT or ACPI is
2523 * used to configure the interrupts, as you may end up with
2524 * conflicting triggers. Tell the user, and reset to NONE.
2526 if (WARN(np && type != IRQ_TYPE_NONE,
2527 "%s: Ignoring %u default trigger\n", np->full_name, type))
2528 type = IRQ_TYPE_NONE;
2530 if (has_acpi_companion(gc->parent) && type != IRQ_TYPE_NONE) {
2531 acpi_handle_warn(ACPI_HANDLE(gc->parent),
2532 "Ignoring %u default trigger\n", type);
2533 type = IRQ_TYPE_NONE;
2536 gc->to_irq = gpiochip_to_irq;
2537 gc->irq.default_type = type;
2538 gc->irq.lock_key = lock_key;
2539 gc->irq.request_key = request_key;
2541 /* If a parent irqdomain is provided, let's build a hierarchy */
2542 if (gpiochip_hierarchy_is_hierarchical(gc)) {
2543 int ret = gpiochip_hierarchy_add_domain(gc);
2547 /* Some drivers provide custom irqdomain ops */
2548 if (gc->irq.domain_ops)
2549 ops = gc->irq.domain_ops;
2552 ops = &gpiochip_domain_ops;
2553 gc->irq.domain = irq_domain_add_simple(np,
2557 if (!gc->irq.domain)
2561 if (gc->irq.parent_handler) {
2562 void *data = gc->irq.parent_handler_data ?: gc;
2564 for (i = 0; i < gc->irq.num_parents; i++) {
2566 * The parent IRQ chip is already using the chip_data
2567 * for this IRQ chip, so our callbacks simply use the
2570 irq_set_chained_handler_and_data(gc->irq.parents[i],
2571 gc->irq.parent_handler,
2576 gpiochip_set_irq_hooks(gc);
2578 acpi_gpiochip_request_interrupts(gc);
2584 * gpiochip_irqchip_remove() - removes an irqchip added to a gpiochip
2585 * @gc: the gpiochip to remove the irqchip from
2587 * This is called only from gpiochip_remove()
2589 static void gpiochip_irqchip_remove(struct gpio_chip *gc)
2591 struct irq_chip *irqchip = gc->irq.chip;
2592 unsigned int offset;
2594 acpi_gpiochip_free_interrupts(gc);
2596 if (irqchip && gc->irq.parent_handler) {
2597 struct gpio_irq_chip *irq = &gc->irq;
2600 for (i = 0; i < irq->num_parents; i++)
2601 irq_set_chained_handler_and_data(irq->parents[i],
2605 /* Remove all IRQ mappings and delete the domain */
2606 if (gc->irq.domain) {
2609 for (offset = 0; offset < gc->ngpio; offset++) {
2610 if (!gpiochip_irqchip_irq_valid(gc, offset))
2613 irq = irq_find_mapping(gc->irq.domain, offset);
2614 irq_dispose_mapping(irq);
2617 irq_domain_remove(gc->irq.domain);
2621 if (irqchip->irq_request_resources == gpiochip_irq_reqres) {
2622 irqchip->irq_request_resources = NULL;
2623 irqchip->irq_release_resources = NULL;
2625 if (irqchip->irq_enable == gpiochip_irq_enable) {
2626 irqchip->irq_enable = gc->irq.irq_enable;
2627 irqchip->irq_disable = gc->irq.irq_disable;
2630 gc->irq.irq_enable = NULL;
2631 gc->irq.irq_disable = NULL;
2632 gc->irq.chip = NULL;
2634 gpiochip_irqchip_free_valid_mask(gc);
2638 * gpiochip_irqchip_add_key() - adds an irqchip to a gpiochip
2639 * @gc: the gpiochip to add the irqchip to
2640 * @irqchip: the irqchip to add to the gpiochip
2641 * @first_irq: if not dynamically assigned, the base (first) IRQ to
2642 * allocate gpiochip irqs from
2643 * @handler: the irq handler to use (often a predefined irq core function)
2644 * @type: the default type for IRQs on this irqchip, pass IRQ_TYPE_NONE
2645 * to have the core avoid setting up any default type in the hardware.
2646 * @threaded: whether this irqchip uses a nested thread handler
2647 * @lock_key: lockdep class for IRQ lock
2648 * @request_key: lockdep class for IRQ request
2650 * This function closely associates a certain irqchip with a certain
2651 * gpiochip, providing an irq domain to translate the local IRQs to
2652 * global irqs in the gpiolib core, and making sure that the gpiochip
2653 * is passed as chip data to all related functions. Driver callbacks
2654 * need to use gpiochip_get_data() to get their local state containers back
2655 * from the gpiochip passed as chip data. An irqdomain will be stored
2656 * in the gpiochip that shall be used by the driver to handle IRQ number
2657 * translation. The gpiochip will need to be initialized and registered
2658 * before calling this function.
2660 * This function will handle two cell:ed simple IRQs and assumes all
2661 * the pins on the gpiochip can generate a unique IRQ. Everything else
2662 * need to be open coded.
2664 int gpiochip_irqchip_add_key(struct gpio_chip *gc,
2665 struct irq_chip *irqchip,
2666 unsigned int first_irq,
2667 irq_flow_handler_t handler,
2670 struct lock_class_key *lock_key,
2671 struct lock_class_key *request_key)
2673 struct device_node *of_node;
2675 if (!gc || !irqchip)
2679 chip_err(gc, "missing gpiochip .dev parent pointer\n");
2682 gc->irq.threaded = threaded;
2683 of_node = gc->parent->of_node;
2684 #ifdef CONFIG_OF_GPIO
2686 * If the gpiochip has an assigned OF node this takes precedence
2687 * FIXME: get rid of this and use gc->parent->of_node
2691 of_node = gc->of_node;
2694 * Specifying a default trigger is a terrible idea if DT or ACPI is
2695 * used to configure the interrupts, as you may end-up with
2696 * conflicting triggers. Tell the user, and reset to NONE.
2698 if (WARN(of_node && type != IRQ_TYPE_NONE,
2699 "%pOF: Ignoring %d default trigger\n", of_node, type))
2700 type = IRQ_TYPE_NONE;
2701 if (has_acpi_companion(gc->parent) && type != IRQ_TYPE_NONE) {
2702 acpi_handle_warn(ACPI_HANDLE(gc->parent),
2703 "Ignoring %d default trigger\n", type);
2704 type = IRQ_TYPE_NONE;
2707 gc->irq.chip = irqchip;
2708 gc->irq.handler = handler;
2709 gc->irq.default_type = type;
2710 gc->to_irq = gpiochip_to_irq;
2711 gc->irq.lock_key = lock_key;
2712 gc->irq.request_key = request_key;
2713 gc->irq.domain = irq_domain_add_simple(of_node,
2714 gc->ngpio, first_irq,
2715 &gpiochip_domain_ops, gc);
2716 if (!gc->irq.domain) {
2717 gc->irq.chip = NULL;
2721 gpiochip_set_irq_hooks(gc);
2723 acpi_gpiochip_request_interrupts(gc);
2727 EXPORT_SYMBOL_GPL(gpiochip_irqchip_add_key);
2729 #else /* CONFIG_GPIOLIB_IRQCHIP */
2731 static inline int gpiochip_add_irqchip(struct gpio_chip *gc,
2732 struct lock_class_key *lock_key,
2733 struct lock_class_key *request_key)
2737 static void gpiochip_irqchip_remove(struct gpio_chip *gc) {}
2739 static inline int gpiochip_irqchip_init_hw(struct gpio_chip *gc)
2744 static inline int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gc)
2748 static inline void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gc)
2751 #endif /* CONFIG_GPIOLIB_IRQCHIP */
2754 * gpiochip_generic_request() - request the gpio function for a pin
2755 * @gc: the gpiochip owning the GPIO
2756 * @offset: the offset of the GPIO to request for GPIO function
2758 int gpiochip_generic_request(struct gpio_chip *gc, unsigned offset)
2760 #ifdef CONFIG_PINCTRL
2761 if (list_empty(&gc->gpiodev->pin_ranges))
2765 return pinctrl_gpio_request(gc->gpiodev->base + offset);
2767 EXPORT_SYMBOL_GPL(gpiochip_generic_request);
2770 * gpiochip_generic_free() - free the gpio function from a pin
2771 * @gc: the gpiochip to request the gpio function for
2772 * @offset: the offset of the GPIO to free from GPIO function
2774 void gpiochip_generic_free(struct gpio_chip *gc, unsigned offset)
2776 pinctrl_gpio_free(gc->gpiodev->base + offset);
2778 EXPORT_SYMBOL_GPL(gpiochip_generic_free);
2781 * gpiochip_generic_config() - apply configuration for a pin
2782 * @gc: the gpiochip owning the GPIO
2783 * @offset: the offset of the GPIO to apply the configuration
2784 * @config: the configuration to be applied
2786 int gpiochip_generic_config(struct gpio_chip *gc, unsigned offset,
2787 unsigned long config)
2789 return pinctrl_gpio_set_config(gc->gpiodev->base + offset, config);
2791 EXPORT_SYMBOL_GPL(gpiochip_generic_config);
2793 #ifdef CONFIG_PINCTRL
2796 * gpiochip_add_pingroup_range() - add a range for GPIO <-> pin mapping
2797 * @gc: the gpiochip to add the range for
2798 * @pctldev: the pin controller to map to
2799 * @gpio_offset: the start offset in the current gpio_chip number space
2800 * @pin_group: name of the pin group inside the pin controller
2802 * Calling this function directly from a DeviceTree-supported
2803 * pinctrl driver is DEPRECATED. Please see Section 2.1 of
2804 * Documentation/devicetree/bindings/gpio/gpio.txt on how to
2805 * bind pinctrl and gpio drivers via the "gpio-ranges" property.
2807 int gpiochip_add_pingroup_range(struct gpio_chip *gc,
2808 struct pinctrl_dev *pctldev,
2809 unsigned int gpio_offset, const char *pin_group)
2811 struct gpio_pin_range *pin_range;
2812 struct gpio_device *gdev = gc->gpiodev;
2815 pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
2817 chip_err(gc, "failed to allocate pin ranges\n");
2821 /* Use local offset as range ID */
2822 pin_range->range.id = gpio_offset;
2823 pin_range->range.gc = gc;
2824 pin_range->range.name = gc->label;
2825 pin_range->range.base = gdev->base + gpio_offset;
2826 pin_range->pctldev = pctldev;
2828 ret = pinctrl_get_group_pins(pctldev, pin_group,
2829 &pin_range->range.pins,
2830 &pin_range->range.npins);
2836 pinctrl_add_gpio_range(pctldev, &pin_range->range);
2838 chip_dbg(gc, "created GPIO range %d->%d ==> %s PINGRP %s\n",
2839 gpio_offset, gpio_offset + pin_range->range.npins - 1,
2840 pinctrl_dev_get_devname(pctldev), pin_group);
2842 list_add_tail(&pin_range->node, &gdev->pin_ranges);
2846 EXPORT_SYMBOL_GPL(gpiochip_add_pingroup_range);
2849 * gpiochip_add_pin_range() - add a range for GPIO <-> pin mapping
2850 * @gc: the gpiochip to add the range for
2851 * @pinctl_name: the dev_name() of the pin controller to map to
2852 * @gpio_offset: the start offset in the current gpio_chip number space
2853 * @pin_offset: the start offset in the pin controller number space
2854 * @npins: the number of pins from the offset of each pin space (GPIO and
2855 * pin controller) to accumulate in this range
2858 * 0 on success, or a negative error-code on failure.
2860 * Calling this function directly from a DeviceTree-supported
2861 * pinctrl driver is DEPRECATED. Please see Section 2.1 of
2862 * Documentation/devicetree/bindings/gpio/gpio.txt on how to
2863 * bind pinctrl and gpio drivers via the "gpio-ranges" property.
2865 int gpiochip_add_pin_range(struct gpio_chip *gc, const char *pinctl_name,
2866 unsigned int gpio_offset, unsigned int pin_offset,
2869 struct gpio_pin_range *pin_range;
2870 struct gpio_device *gdev = gc->gpiodev;
2873 pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
2875 chip_err(gc, "failed to allocate pin ranges\n");
2879 /* Use local offset as range ID */
2880 pin_range->range.id = gpio_offset;
2881 pin_range->range.gc = gc;
2882 pin_range->range.name = gc->label;
2883 pin_range->range.base = gdev->base + gpio_offset;
2884 pin_range->range.pin_base = pin_offset;
2885 pin_range->range.npins = npins;
2886 pin_range->pctldev = pinctrl_find_and_add_gpio_range(pinctl_name,
2888 if (IS_ERR(pin_range->pctldev)) {
2889 ret = PTR_ERR(pin_range->pctldev);
2890 chip_err(gc, "could not create pin range\n");
2894 chip_dbg(gc, "created GPIO range %d->%d ==> %s PIN %d->%d\n",
2895 gpio_offset, gpio_offset + npins - 1,
2897 pin_offset, pin_offset + npins - 1);
2899 list_add_tail(&pin_range->node, &gdev->pin_ranges);
2903 EXPORT_SYMBOL_GPL(gpiochip_add_pin_range);
2906 * gpiochip_remove_pin_ranges() - remove all the GPIO <-> pin mappings
2907 * @gc: the chip to remove all the mappings for
2909 void gpiochip_remove_pin_ranges(struct gpio_chip *gc)
2911 struct gpio_pin_range *pin_range, *tmp;
2912 struct gpio_device *gdev = gc->gpiodev;
2914 list_for_each_entry_safe(pin_range, tmp, &gdev->pin_ranges, node) {
2915 list_del(&pin_range->node);
2916 pinctrl_remove_gpio_range(pin_range->pctldev,
2921 EXPORT_SYMBOL_GPL(gpiochip_remove_pin_ranges);
2923 #endif /* CONFIG_PINCTRL */
2925 /* These "optional" allocation calls help prevent drivers from stomping
2926 * on each other, and help provide better diagnostics in debugfs.
2927 * They're called even less than the "set direction" calls.
2929 static int gpiod_request_commit(struct gpio_desc *desc, const char *label)
2931 struct gpio_chip *gc = desc->gdev->chip;
2933 unsigned long flags;
2937 label = kstrdup_const(label, GFP_KERNEL);
2942 spin_lock_irqsave(&gpio_lock, flags);
2944 /* NOTE: gpio_request() can be called in early boot,
2945 * before IRQs are enabled, for non-sleeping (SOC) GPIOs.
2948 if (test_and_set_bit(FLAG_REQUESTED, &desc->flags) == 0) {
2949 desc_set_label(desc, label ? : "?");
2958 /* gc->request may sleep */
2959 spin_unlock_irqrestore(&gpio_lock, flags);
2960 offset = gpio_chip_hwgpio(desc);
2961 if (gpiochip_line_is_valid(gc, offset))
2962 ret = gc->request(gc, offset);
2965 spin_lock_irqsave(&gpio_lock, flags);
2968 desc_set_label(desc, NULL);
2970 clear_bit(FLAG_REQUESTED, &desc->flags);
2974 if (gc->get_direction) {
2975 /* gc->get_direction may sleep */
2976 spin_unlock_irqrestore(&gpio_lock, flags);
2977 gpiod_get_direction(desc);
2978 spin_lock_irqsave(&gpio_lock, flags);
2981 spin_unlock_irqrestore(&gpio_lock, flags);
2982 atomic_notifier_call_chain(&desc->gdev->notifier,
2983 GPIOLINE_CHANGED_REQUESTED, desc);
2988 * This descriptor validation needs to be inserted verbatim into each
2989 * function taking a descriptor, so we need to use a preprocessor
2990 * macro to avoid endless duplication. If the desc is NULL it is an
2991 * optional GPIO and calls should just bail out.
2993 static int validate_desc(const struct gpio_desc *desc, const char *func)
2998 pr_warn("%s: invalid GPIO (errorpointer)\n", func);
2999 return PTR_ERR(desc);
3002 pr_warn("%s: invalid GPIO (no device)\n", func);
3005 if (!desc->gdev->chip) {
3006 dev_warn(&desc->gdev->dev,
3007 "%s: backing chip is gone\n", func);
3013 #define VALIDATE_DESC(desc) do { \
3014 int __valid = validate_desc(desc, __func__); \
3019 #define VALIDATE_DESC_VOID(desc) do { \
3020 int __valid = validate_desc(desc, __func__); \
3025 int gpiod_request(struct gpio_desc *desc, const char *label)
3027 int ret = -EPROBE_DEFER;
3028 struct gpio_device *gdev;
3030 VALIDATE_DESC(desc);
3033 if (try_module_get(gdev->owner)) {
3034 ret = gpiod_request_commit(desc, label);
3036 module_put(gdev->owner);
3038 get_device(&gdev->dev);
3042 gpiod_dbg(desc, "%s: status %d\n", __func__, ret);
3047 static bool gpiod_free_commit(struct gpio_desc *desc)
3050 unsigned long flags;
3051 struct gpio_chip *gc;
3055 gpiod_unexport(desc);
3057 spin_lock_irqsave(&gpio_lock, flags);
3059 gc = desc->gdev->chip;
3060 if (gc && test_bit(FLAG_REQUESTED, &desc->flags)) {
3062 spin_unlock_irqrestore(&gpio_lock, flags);
3063 might_sleep_if(gc->can_sleep);
3064 gc->free(gc, gpio_chip_hwgpio(desc));
3065 spin_lock_irqsave(&gpio_lock, flags);
3067 kfree_const(desc->label);
3068 desc_set_label(desc, NULL);
3069 clear_bit(FLAG_ACTIVE_LOW, &desc->flags);
3070 clear_bit(FLAG_REQUESTED, &desc->flags);
3071 clear_bit(FLAG_OPEN_DRAIN, &desc->flags);
3072 clear_bit(FLAG_OPEN_SOURCE, &desc->flags);
3073 clear_bit(FLAG_PULL_UP, &desc->flags);
3074 clear_bit(FLAG_PULL_DOWN, &desc->flags);
3075 clear_bit(FLAG_BIAS_DISABLE, &desc->flags);
3076 clear_bit(FLAG_IS_HOGGED, &desc->flags);
3077 #ifdef CONFIG_OF_DYNAMIC
3083 spin_unlock_irqrestore(&gpio_lock, flags);
3084 atomic_notifier_call_chain(&desc->gdev->notifier,
3085 GPIOLINE_CHANGED_RELEASED, desc);
3090 void gpiod_free(struct gpio_desc *desc)
3092 if (desc && desc->gdev && gpiod_free_commit(desc)) {
3093 module_put(desc->gdev->owner);
3094 put_device(&desc->gdev->dev);
3096 WARN_ON(extra_checks);
3101 * gpiochip_is_requested - return string iff signal was requested
3102 * @gc: controller managing the signal
3103 * @offset: of signal within controller's 0..(ngpio - 1) range
3105 * Returns NULL if the GPIO is not currently requested, else a string.
3106 * The string returned is the label passed to gpio_request(); if none has been
3107 * passed it is a meaningless, non-NULL constant.
3109 * This function is for use by GPIO controller drivers. The label can
3110 * help with diagnostics, and knowing that the signal is used as a GPIO
3111 * can help avoid accidentally multiplexing it to another controller.
3113 const char *gpiochip_is_requested(struct gpio_chip *gc, unsigned offset)
3115 struct gpio_desc *desc;
3117 if (offset >= gc->ngpio)
3120 desc = gpiochip_get_desc(gc, offset);
3124 if (test_bit(FLAG_REQUESTED, &desc->flags) == 0)
3128 EXPORT_SYMBOL_GPL(gpiochip_is_requested);
3131 * gpiochip_request_own_desc - Allow GPIO chip to request its own descriptor
3133 * @hwnum: hardware number of the GPIO for which to request the descriptor
3134 * @label: label for the GPIO
3135 * @lflags: lookup flags for this GPIO or 0 if default, this can be used to
3136 * specify things like line inversion semantics with the machine flags
3137 * such as GPIO_OUT_LOW
3138 * @dflags: descriptor request flags for this GPIO or 0 if default, this
3139 * can be used to specify consumer semantics such as open drain
3141 * Function allows GPIO chip drivers to request and use their own GPIO
3142 * descriptors via gpiolib API. Difference to gpiod_request() is that this
3143 * function will not increase reference count of the GPIO chip module. This
3144 * allows the GPIO chip module to be unloaded as needed (we assume that the
3145 * GPIO chip driver handles freeing the GPIOs it has requested).
3148 * A pointer to the GPIO descriptor, or an ERR_PTR()-encoded negative error
3151 struct gpio_desc *gpiochip_request_own_desc(struct gpio_chip *gc,
3154 enum gpio_lookup_flags lflags,
3155 enum gpiod_flags dflags)
3157 struct gpio_desc *desc = gpiochip_get_desc(gc, hwnum);
3161 chip_err(gc, "failed to get GPIO descriptor\n");
3165 ret = gpiod_request_commit(desc, label);
3167 return ERR_PTR(ret);
3169 ret = gpiod_configure_flags(desc, label, lflags, dflags);
3171 chip_err(gc, "setup of own GPIO %s failed\n", label);
3172 gpiod_free_commit(desc);
3173 return ERR_PTR(ret);
3178 EXPORT_SYMBOL_GPL(gpiochip_request_own_desc);
3181 * gpiochip_free_own_desc - Free GPIO requested by the chip driver
3182 * @desc: GPIO descriptor to free
3184 * Function frees the given GPIO requested previously with
3185 * gpiochip_request_own_desc().
3187 void gpiochip_free_own_desc(struct gpio_desc *desc)
3190 gpiod_free_commit(desc);
3192 EXPORT_SYMBOL_GPL(gpiochip_free_own_desc);
3195 * Drivers MUST set GPIO direction before making get/set calls. In
3196 * some cases this is done in early boot, before IRQs are enabled.
3198 * As a rule these aren't called more than once (except for drivers
3199 * using the open-drain emulation idiom) so these are natural places
3200 * to accumulate extra debugging checks. Note that we can't (yet)
3201 * rely on gpio_request() having been called beforehand.
3204 static int gpio_do_set_config(struct gpio_chip *gc, unsigned int offset,
3205 unsigned long config)
3207 if (!gc->set_config)
3210 return gc->set_config(gc, offset, config);
3213 static int gpio_set_config(struct gpio_desc *desc, enum pin_config_param mode)
3215 struct gpio_chip *gc = desc->gdev->chip;
3216 unsigned long config;
3220 case PIN_CONFIG_BIAS_PULL_DOWN:
3221 case PIN_CONFIG_BIAS_PULL_UP:
3229 config = PIN_CONF_PACKED(mode, arg);
3230 return gpio_do_set_config(gc, gpio_chip_hwgpio(desc), config);
3233 static int gpio_set_bias(struct gpio_desc *desc)
3238 if (test_bit(FLAG_BIAS_DISABLE, &desc->flags))
3239 bias = PIN_CONFIG_BIAS_DISABLE;
3240 else if (test_bit(FLAG_PULL_UP, &desc->flags))
3241 bias = PIN_CONFIG_BIAS_PULL_UP;
3242 else if (test_bit(FLAG_PULL_DOWN, &desc->flags))
3243 bias = PIN_CONFIG_BIAS_PULL_DOWN;
3246 ret = gpio_set_config(desc, bias);
3247 if (ret != -ENOTSUPP)
3254 * gpiod_direction_input - set the GPIO direction to input
3255 * @desc: GPIO to set to input
3257 * Set the direction of the passed GPIO to input, such as gpiod_get_value() can
3258 * be called safely on it.
3260 * Return 0 in case of success, else an error code.
3262 int gpiod_direction_input(struct gpio_desc *desc)
3264 struct gpio_chip *gc;
3267 VALIDATE_DESC(desc);
3268 gc = desc->gdev->chip;
3271 * It is legal to have no .get() and .direction_input() specified if
3272 * the chip is output-only, but you can't specify .direction_input()
3273 * and not support the .get() operation, that doesn't make sense.
3275 if (!gc->get && gc->direction_input) {
3277 "%s: missing get() but have direction_input()\n",
3283 * If we have a .direction_input() callback, things are simple,
3284 * just call it. Else we are some input-only chip so try to check the
3285 * direction (if .get_direction() is supported) else we silently
3286 * assume we are in input mode after this.
3288 if (gc->direction_input) {
3289 ret = gc->direction_input(gc, gpio_chip_hwgpio(desc));
3290 } else if (gc->get_direction &&
3291 (gc->get_direction(gc, gpio_chip_hwgpio(desc)) != 1)) {
3293 "%s: missing direction_input() operation and line is output\n",
3298 clear_bit(FLAG_IS_OUT, &desc->flags);
3299 ret = gpio_set_bias(desc);
3302 trace_gpio_direction(desc_to_gpio(desc), 1, ret);
3306 EXPORT_SYMBOL_GPL(gpiod_direction_input);
3308 static int gpiod_direction_output_raw_commit(struct gpio_desc *desc, int value)
3310 struct gpio_chip *gc = desc->gdev->chip;
3315 * It's OK not to specify .direction_output() if the gpiochip is
3316 * output-only, but if there is then not even a .set() operation it
3317 * is pretty tricky to drive the output line.
3319 if (!gc->set && !gc->direction_output) {
3321 "%s: missing set() and direction_output() operations\n",
3326 if (gc->direction_output) {
3327 ret = gc->direction_output(gc, gpio_chip_hwgpio(desc), val);
3329 /* Check that we are in output mode if we can */
3330 if (gc->get_direction &&
3331 gc->get_direction(gc, gpio_chip_hwgpio(desc))) {
3333 "%s: missing direction_output() operation\n",
3338 * If we can't actively set the direction, we are some
3339 * output-only chip, so just drive the output as desired.
3341 gc->set(gc, gpio_chip_hwgpio(desc), val);
3345 set_bit(FLAG_IS_OUT, &desc->flags);
3346 trace_gpio_value(desc_to_gpio(desc), 0, val);
3347 trace_gpio_direction(desc_to_gpio(desc), 0, ret);
3352 * gpiod_direction_output_raw - set the GPIO direction to output
3353 * @desc: GPIO to set to output
3354 * @value: initial output value of the GPIO
3356 * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
3357 * be called safely on it. The initial value of the output must be specified
3358 * as raw value on the physical line without regard for the ACTIVE_LOW status.
3360 * Return 0 in case of success, else an error code.
3362 int gpiod_direction_output_raw(struct gpio_desc *desc, int value)
3364 VALIDATE_DESC(desc);
3365 return gpiod_direction_output_raw_commit(desc, value);
3367 EXPORT_SYMBOL_GPL(gpiod_direction_output_raw);
3370 * gpiod_direction_output - set the GPIO direction to output
3371 * @desc: GPIO to set to output
3372 * @value: initial output value of the GPIO
3374 * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
3375 * be called safely on it. The initial value of the output must be specified
3376 * as the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
3379 * Return 0 in case of success, else an error code.
3381 int gpiod_direction_output(struct gpio_desc *desc, int value)
3385 VALIDATE_DESC(desc);
3386 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3391 /* GPIOs used for enabled IRQs shall not be set as output */
3392 if (test_bit(FLAG_USED_AS_IRQ, &desc->flags) &&
3393 test_bit(FLAG_IRQ_IS_ENABLED, &desc->flags)) {
3395 "%s: tried to set a GPIO tied to an IRQ as output\n",
3400 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags)) {
3401 /* First see if we can enable open drain in hardware */
3402 ret = gpio_set_config(desc, PIN_CONFIG_DRIVE_OPEN_DRAIN);
3404 goto set_output_value;
3405 /* Emulate open drain by not actively driving the line high */
3407 ret = gpiod_direction_input(desc);
3408 goto set_output_flag;
3411 else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags)) {
3412 ret = gpio_set_config(desc, PIN_CONFIG_DRIVE_OPEN_SOURCE);
3414 goto set_output_value;
3415 /* Emulate open source by not actively driving the line low */
3417 ret = gpiod_direction_input(desc);
3418 goto set_output_flag;
3421 gpio_set_config(desc, PIN_CONFIG_DRIVE_PUSH_PULL);
3425 ret = gpio_set_bias(desc);
3428 return gpiod_direction_output_raw_commit(desc, value);
3432 * When emulating open-source or open-drain functionalities by not
3433 * actively driving the line (setting mode to input) we still need to
3434 * set the IS_OUT flag or otherwise we won't be able to set the line
3438 set_bit(FLAG_IS_OUT, &desc->flags);
3441 EXPORT_SYMBOL_GPL(gpiod_direction_output);
3444 * gpiod_set_config - sets @config for a GPIO
3445 * @desc: descriptor of the GPIO for which to set the configuration
3446 * @config: Same packed config format as generic pinconf
3449 * 0 on success, %-ENOTSUPP if the controller doesn't support setting the
3452 int gpiod_set_config(struct gpio_desc *desc, unsigned long config)
3454 struct gpio_chip *gc;
3456 VALIDATE_DESC(desc);
3457 gc = desc->gdev->chip;
3459 return gpio_do_set_config(gc, gpio_chip_hwgpio(desc), config);
3461 EXPORT_SYMBOL_GPL(gpiod_set_config);
3464 * gpiod_set_debounce - sets @debounce time for a GPIO
3465 * @desc: descriptor of the GPIO for which to set debounce time
3466 * @debounce: debounce time in microseconds
3469 * 0 on success, %-ENOTSUPP if the controller doesn't support setting the
3472 int gpiod_set_debounce(struct gpio_desc *desc, unsigned debounce)
3474 unsigned long config;
3476 config = pinconf_to_config_packed(PIN_CONFIG_INPUT_DEBOUNCE, debounce);
3477 return gpiod_set_config(desc, config);
3479 EXPORT_SYMBOL_GPL(gpiod_set_debounce);
3482 * gpiod_set_transitory - Lose or retain GPIO state on suspend or reset
3483 * @desc: descriptor of the GPIO for which to configure persistence
3484 * @transitory: True to lose state on suspend or reset, false for persistence
3487 * 0 on success, otherwise a negative error code.
3489 int gpiod_set_transitory(struct gpio_desc *desc, bool transitory)
3491 struct gpio_chip *gc;
3492 unsigned long packed;
3496 VALIDATE_DESC(desc);
3498 * Handle FLAG_TRANSITORY first, enabling queries to gpiolib for
3499 * persistence state.
3501 assign_bit(FLAG_TRANSITORY, &desc->flags, transitory);
3503 /* If the driver supports it, set the persistence state now */
3504 gc = desc->gdev->chip;
3505 if (!gc->set_config)
3508 packed = pinconf_to_config_packed(PIN_CONFIG_PERSIST_STATE,
3510 gpio = gpio_chip_hwgpio(desc);
3511 rc = gpio_do_set_config(gc, gpio, packed);
3512 if (rc == -ENOTSUPP) {
3513 dev_dbg(&desc->gdev->dev, "Persistence not supported for GPIO %d\n",
3520 EXPORT_SYMBOL_GPL(gpiod_set_transitory);
3523 * gpiod_is_active_low - test whether a GPIO is active-low or not
3524 * @desc: the gpio descriptor to test
3526 * Returns 1 if the GPIO is active-low, 0 otherwise.
3528 int gpiod_is_active_low(const struct gpio_desc *desc)
3530 VALIDATE_DESC(desc);
3531 return test_bit(FLAG_ACTIVE_LOW, &desc->flags);
3533 EXPORT_SYMBOL_GPL(gpiod_is_active_low);
3536 * gpiod_toggle_active_low - toggle whether a GPIO is active-low or not
3537 * @desc: the gpio descriptor to change
3539 void gpiod_toggle_active_low(struct gpio_desc *desc)
3541 VALIDATE_DESC_VOID(desc);
3542 change_bit(FLAG_ACTIVE_LOW, &desc->flags);
3544 EXPORT_SYMBOL_GPL(gpiod_toggle_active_low);
3546 /* I/O calls are only valid after configuration completed; the relevant
3547 * "is this a valid GPIO" error checks should already have been done.
3549 * "Get" operations are often inlinable as reading a pin value register,
3550 * and masking the relevant bit in that register.
3552 * When "set" operations are inlinable, they involve writing that mask to
3553 * one register to set a low value, or a different register to set it high.
3554 * Otherwise locking is needed, so there may be little value to inlining.
3556 *------------------------------------------------------------------------
3558 * IMPORTANT!!! The hot paths -- get/set value -- assume that callers
3559 * have requested the GPIO. That can include implicit requesting by
3560 * a direction setting call. Marking a gpio as requested locks its chip
3561 * in memory, guaranteeing that these table lookups need no more locking
3562 * and that gpiochip_remove() will fail.
3564 * REVISIT when debugging, consider adding some instrumentation to ensure
3565 * that the GPIO was actually requested.
3568 static int gpiod_get_raw_value_commit(const struct gpio_desc *desc)
3570 struct gpio_chip *gc;
3574 gc = desc->gdev->chip;
3575 offset = gpio_chip_hwgpio(desc);
3576 value = gc->get ? gc->get(gc, offset) : -EIO;
3577 value = value < 0 ? value : !!value;
3578 trace_gpio_value(desc_to_gpio(desc), 1, value);
3582 static int gpio_chip_get_multiple(struct gpio_chip *gc,
3583 unsigned long *mask, unsigned long *bits)
3585 if (gc->get_multiple) {
3586 return gc->get_multiple(gc, mask, bits);
3587 } else if (gc->get) {
3590 for_each_set_bit(i, mask, gc->ngpio) {
3591 value = gc->get(gc, i);
3594 __assign_bit(i, bits, value);
3601 int gpiod_get_array_value_complex(bool raw, bool can_sleep,
3602 unsigned int array_size,
3603 struct gpio_desc **desc_array,
3604 struct gpio_array *array_info,
3605 unsigned long *value_bitmap)
3610 * Validate array_info against desc_array and its size.
3611 * It should immediately follow desc_array if both
3612 * have been obtained from the same gpiod_get_array() call.
3614 if (array_info && array_info->desc == desc_array &&
3615 array_size <= array_info->size &&
3616 (void *)array_info == desc_array + array_info->size) {
3618 WARN_ON(array_info->chip->can_sleep);
3620 ret = gpio_chip_get_multiple(array_info->chip,
3621 array_info->get_mask,
3626 if (!raw && !bitmap_empty(array_info->invert_mask, array_size))
3627 bitmap_xor(value_bitmap, value_bitmap,
3628 array_info->invert_mask, array_size);
3630 if (bitmap_full(array_info->get_mask, array_size))
3633 i = find_first_zero_bit(array_info->get_mask, array_size);
3638 while (i < array_size) {
3639 struct gpio_chip *gc = desc_array[i]->gdev->chip;
3640 unsigned long fastpath[2 * BITS_TO_LONGS(FASTPATH_NGPIO)];
3641 unsigned long *mask, *bits;
3644 if (likely(gc->ngpio <= FASTPATH_NGPIO)) {
3647 mask = kmalloc_array(2 * BITS_TO_LONGS(gc->ngpio),
3649 can_sleep ? GFP_KERNEL : GFP_ATOMIC);
3654 bits = mask + BITS_TO_LONGS(gc->ngpio);
3655 bitmap_zero(mask, gc->ngpio);
3658 WARN_ON(gc->can_sleep);
3660 /* collect all inputs belonging to the same chip */
3663 const struct gpio_desc *desc = desc_array[i];
3664 int hwgpio = gpio_chip_hwgpio(desc);
3666 __set_bit(hwgpio, mask);
3670 i = find_next_zero_bit(array_info->get_mask,
3672 } while ((i < array_size) &&
3673 (desc_array[i]->gdev->chip == gc));
3675 ret = gpio_chip_get_multiple(gc, mask, bits);
3677 if (mask != fastpath)
3682 for (j = first; j < i; ) {
3683 const struct gpio_desc *desc = desc_array[j];
3684 int hwgpio = gpio_chip_hwgpio(desc);
3685 int value = test_bit(hwgpio, bits);
3687 if (!raw && test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3689 __assign_bit(j, value_bitmap, value);
3690 trace_gpio_value(desc_to_gpio(desc), 1, value);
3694 j = find_next_zero_bit(array_info->get_mask, i,
3698 if (mask != fastpath)
3705 * gpiod_get_raw_value() - return a gpio's raw value
3706 * @desc: gpio whose value will be returned
3708 * Return the GPIO's raw value, i.e. the value of the physical line disregarding
3709 * its ACTIVE_LOW status, or negative errno on failure.
3711 * This function can be called from contexts where we cannot sleep, and will
3712 * complain if the GPIO chip functions potentially sleep.
3714 int gpiod_get_raw_value(const struct gpio_desc *desc)
3716 VALIDATE_DESC(desc);
3717 /* Should be using gpiod_get_raw_value_cansleep() */
3718 WARN_ON(desc->gdev->chip->can_sleep);
3719 return gpiod_get_raw_value_commit(desc);
3721 EXPORT_SYMBOL_GPL(gpiod_get_raw_value);
3724 * gpiod_get_value() - return a gpio's value
3725 * @desc: gpio whose value will be returned
3727 * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
3728 * account, or negative errno on failure.
3730 * This function can be called from contexts where we cannot sleep, and will
3731 * complain if the GPIO chip functions potentially sleep.
3733 int gpiod_get_value(const struct gpio_desc *desc)
3737 VALIDATE_DESC(desc);
3738 /* Should be using gpiod_get_value_cansleep() */
3739 WARN_ON(desc->gdev->chip->can_sleep);
3741 value = gpiod_get_raw_value_commit(desc);
3745 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3750 EXPORT_SYMBOL_GPL(gpiod_get_value);
3753 * gpiod_get_raw_array_value() - read raw values from an array of GPIOs
3754 * @array_size: number of elements in the descriptor array / value bitmap
3755 * @desc_array: array of GPIO descriptors whose values will be read
3756 * @array_info: information on applicability of fast bitmap processing path
3757 * @value_bitmap: bitmap to store the read values
3759 * Read the raw values of the GPIOs, i.e. the values of the physical lines
3760 * without regard for their ACTIVE_LOW status. Return 0 in case of success,
3761 * else an error code.
3763 * This function can be called from contexts where we cannot sleep,
3764 * and it will complain if the GPIO chip functions potentially sleep.
3766 int gpiod_get_raw_array_value(unsigned int array_size,
3767 struct gpio_desc **desc_array,
3768 struct gpio_array *array_info,
3769 unsigned long *value_bitmap)
3773 return gpiod_get_array_value_complex(true, false, array_size,
3774 desc_array, array_info,
3777 EXPORT_SYMBOL_GPL(gpiod_get_raw_array_value);
3780 * gpiod_get_array_value() - read values from an array of GPIOs
3781 * @array_size: number of elements in the descriptor array / value bitmap
3782 * @desc_array: array of GPIO descriptors whose values will be read
3783 * @array_info: information on applicability of fast bitmap processing path
3784 * @value_bitmap: bitmap to store the read values
3786 * Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3787 * into account. Return 0 in case of success, else an error code.
3789 * This function can be called from contexts where we cannot sleep,
3790 * and it will complain if the GPIO chip functions potentially sleep.
3792 int gpiod_get_array_value(unsigned int array_size,
3793 struct gpio_desc **desc_array,
3794 struct gpio_array *array_info,
3795 unsigned long *value_bitmap)
3799 return gpiod_get_array_value_complex(false, false, array_size,
3800 desc_array, array_info,
3803 EXPORT_SYMBOL_GPL(gpiod_get_array_value);
3806 * gpio_set_open_drain_value_commit() - Set the open drain gpio's value.
3807 * @desc: gpio descriptor whose state need to be set.
3808 * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
3810 static void gpio_set_open_drain_value_commit(struct gpio_desc *desc, bool value)
3813 struct gpio_chip *gc = desc->gdev->chip;
3814 int offset = gpio_chip_hwgpio(desc);
3817 ret = gc->direction_input(gc, offset);
3819 ret = gc->direction_output(gc, offset, 0);
3821 set_bit(FLAG_IS_OUT, &desc->flags);
3823 trace_gpio_direction(desc_to_gpio(desc), value, ret);
3826 "%s: Error in set_value for open drain err %d\n",
3831 * _gpio_set_open_source_value() - Set the open source gpio's value.
3832 * @desc: gpio descriptor whose state need to be set.
3833 * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
3835 static void gpio_set_open_source_value_commit(struct gpio_desc *desc, bool value)
3838 struct gpio_chip *gc = desc->gdev->chip;
3839 int offset = gpio_chip_hwgpio(desc);
3842 ret = gc->direction_output(gc, offset, 1);
3844 set_bit(FLAG_IS_OUT, &desc->flags);
3846 ret = gc->direction_input(gc, offset);
3848 trace_gpio_direction(desc_to_gpio(desc), !value, ret);
3851 "%s: Error in set_value for open source err %d\n",
3855 static void gpiod_set_raw_value_commit(struct gpio_desc *desc, bool value)
3857 struct gpio_chip *gc;
3859 gc = desc->gdev->chip;
3860 trace_gpio_value(desc_to_gpio(desc), 0, value);
3861 gc->set(gc, gpio_chip_hwgpio(desc), value);
3865 * set multiple outputs on the same chip;
3866 * use the chip's set_multiple function if available;
3867 * otherwise set the outputs sequentially;
3868 * @chip: the GPIO chip we operate on
3869 * @mask: bit mask array; one bit per output; BITS_PER_LONG bits per word
3870 * defines which outputs are to be changed
3871 * @bits: bit value array; one bit per output; BITS_PER_LONG bits per word
3872 * defines the values the outputs specified by mask are to be set to
3874 static void gpio_chip_set_multiple(struct gpio_chip *gc,
3875 unsigned long *mask, unsigned long *bits)
3877 if (gc->set_multiple) {
3878 gc->set_multiple(gc, mask, bits);
3882 /* set outputs if the corresponding mask bit is set */
3883 for_each_set_bit(i, mask, gc->ngpio)
3884 gc->set(gc, i, test_bit(i, bits));
3888 int gpiod_set_array_value_complex(bool raw, bool can_sleep,
3889 unsigned int array_size,
3890 struct gpio_desc **desc_array,
3891 struct gpio_array *array_info,
3892 unsigned long *value_bitmap)
3897 * Validate array_info against desc_array and its size.
3898 * It should immediately follow desc_array if both
3899 * have been obtained from the same gpiod_get_array() call.
3901 if (array_info && array_info->desc == desc_array &&
3902 array_size <= array_info->size &&
3903 (void *)array_info == desc_array + array_info->size) {
3905 WARN_ON(array_info->chip->can_sleep);
3907 if (!raw && !bitmap_empty(array_info->invert_mask, array_size))
3908 bitmap_xor(value_bitmap, value_bitmap,
3909 array_info->invert_mask, array_size);
3911 gpio_chip_set_multiple(array_info->chip, array_info->set_mask,
3914 if (bitmap_full(array_info->set_mask, array_size))
3917 i = find_first_zero_bit(array_info->set_mask, array_size);
3922 while (i < array_size) {
3923 struct gpio_chip *gc = desc_array[i]->gdev->chip;
3924 unsigned long fastpath[2 * BITS_TO_LONGS(FASTPATH_NGPIO)];
3925 unsigned long *mask, *bits;
3928 if (likely(gc->ngpio <= FASTPATH_NGPIO)) {
3931 mask = kmalloc_array(2 * BITS_TO_LONGS(gc->ngpio),
3933 can_sleep ? GFP_KERNEL : GFP_ATOMIC);
3938 bits = mask + BITS_TO_LONGS(gc->ngpio);
3939 bitmap_zero(mask, gc->ngpio);
3942 WARN_ON(gc->can_sleep);
3945 struct gpio_desc *desc = desc_array[i];
3946 int hwgpio = gpio_chip_hwgpio(desc);
3947 int value = test_bit(i, value_bitmap);
3950 * Pins applicable for fast input but not for
3951 * fast output processing may have been already
3952 * inverted inside the fast path, skip them.
3954 if (!raw && !(array_info &&
3955 test_bit(i, array_info->invert_mask)) &&
3956 test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3958 trace_gpio_value(desc_to_gpio(desc), 0, value);
3960 * collect all normal outputs belonging to the same chip
3961 * open drain and open source outputs are set individually
3963 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags) && !raw) {
3964 gpio_set_open_drain_value_commit(desc, value);
3965 } else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags) && !raw) {
3966 gpio_set_open_source_value_commit(desc, value);
3968 __set_bit(hwgpio, mask);
3969 __assign_bit(hwgpio, bits, value);
3975 i = find_next_zero_bit(array_info->set_mask,
3977 } while ((i < array_size) &&
3978 (desc_array[i]->gdev->chip == gc));
3979 /* push collected bits to outputs */
3981 gpio_chip_set_multiple(gc, mask, bits);
3983 if (mask != fastpath)
3990 * gpiod_set_raw_value() - assign a gpio's raw value
3991 * @desc: gpio whose value will be assigned
3992 * @value: value to assign
3994 * Set the raw value of the GPIO, i.e. the value of its physical line without
3995 * regard for its ACTIVE_LOW status.
3997 * This function can be called from contexts where we cannot sleep, and will
3998 * complain if the GPIO chip functions potentially sleep.
4000 void gpiod_set_raw_value(struct gpio_desc *desc, int value)
4002 VALIDATE_DESC_VOID(desc);
4003 /* Should be using gpiod_set_raw_value_cansleep() */
4004 WARN_ON(desc->gdev->chip->can_sleep);
4005 gpiod_set_raw_value_commit(desc, value);
4007 EXPORT_SYMBOL_GPL(gpiod_set_raw_value);
4010 * gpiod_set_value_nocheck() - set a GPIO line value without checking
4011 * @desc: the descriptor to set the value on
4012 * @value: value to set
4014 * This sets the value of a GPIO line backing a descriptor, applying
4015 * different semantic quirks like active low and open drain/source
4018 static void gpiod_set_value_nocheck(struct gpio_desc *desc, int value)
4020 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
4022 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
4023 gpio_set_open_drain_value_commit(desc, value);
4024 else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
4025 gpio_set_open_source_value_commit(desc, value);
4027 gpiod_set_raw_value_commit(desc, value);
4031 * gpiod_set_value() - assign a gpio's value
4032 * @desc: gpio whose value will be assigned
4033 * @value: value to assign
4035 * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW,
4036 * OPEN_DRAIN and OPEN_SOURCE flags into account.
4038 * This function can be called from contexts where we cannot sleep, and will
4039 * complain if the GPIO chip functions potentially sleep.
4041 void gpiod_set_value(struct gpio_desc *desc, int value)
4043 VALIDATE_DESC_VOID(desc);
4044 /* Should be using gpiod_set_value_cansleep() */
4045 WARN_ON(desc->gdev->chip->can_sleep);
4046 gpiod_set_value_nocheck(desc, value);
4048 EXPORT_SYMBOL_GPL(gpiod_set_value);
4051 * gpiod_set_raw_array_value() - assign values to an array of GPIOs
4052 * @array_size: number of elements in the descriptor array / value bitmap
4053 * @desc_array: array of GPIO descriptors whose values will be assigned
4054 * @array_info: information on applicability of fast bitmap processing path
4055 * @value_bitmap: bitmap of values to assign
4057 * Set the raw values of the GPIOs, i.e. the values of the physical lines
4058 * without regard for their ACTIVE_LOW status.
4060 * This function can be called from contexts where we cannot sleep, and will
4061 * complain if the GPIO chip functions potentially sleep.
4063 int gpiod_set_raw_array_value(unsigned int array_size,
4064 struct gpio_desc **desc_array,
4065 struct gpio_array *array_info,
4066 unsigned long *value_bitmap)
4070 return gpiod_set_array_value_complex(true, false, array_size,
4071 desc_array, array_info, value_bitmap);
4073 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value);
4076 * gpiod_set_array_value() - assign values to an array of GPIOs
4077 * @array_size: number of elements in the descriptor array / value bitmap
4078 * @desc_array: array of GPIO descriptors whose values will be assigned
4079 * @array_info: information on applicability of fast bitmap processing path
4080 * @value_bitmap: bitmap of values to assign
4082 * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
4085 * This function can be called from contexts where we cannot sleep, and will
4086 * complain if the GPIO chip functions potentially sleep.
4088 int gpiod_set_array_value(unsigned int array_size,
4089 struct gpio_desc **desc_array,
4090 struct gpio_array *array_info,
4091 unsigned long *value_bitmap)
4095 return gpiod_set_array_value_complex(false, false, array_size,
4096 desc_array, array_info,
4099 EXPORT_SYMBOL_GPL(gpiod_set_array_value);
4102 * gpiod_cansleep() - report whether gpio value access may sleep
4103 * @desc: gpio to check
4106 int gpiod_cansleep(const struct gpio_desc *desc)
4108 VALIDATE_DESC(desc);
4109 return desc->gdev->chip->can_sleep;
4111 EXPORT_SYMBOL_GPL(gpiod_cansleep);
4114 * gpiod_set_consumer_name() - set the consumer name for the descriptor
4115 * @desc: gpio to set the consumer name on
4116 * @name: the new consumer name
4118 int gpiod_set_consumer_name(struct gpio_desc *desc, const char *name)
4120 VALIDATE_DESC(desc);
4122 name = kstrdup_const(name, GFP_KERNEL);
4127 kfree_const(desc->label);
4128 desc_set_label(desc, name);
4132 EXPORT_SYMBOL_GPL(gpiod_set_consumer_name);
4135 * gpiod_to_irq() - return the IRQ corresponding to a GPIO
4136 * @desc: gpio whose IRQ will be returned (already requested)
4138 * Return the IRQ corresponding to the passed GPIO, or an error code in case of
4141 int gpiod_to_irq(const struct gpio_desc *desc)
4143 struct gpio_chip *gc;
4147 * Cannot VALIDATE_DESC() here as gpiod_to_irq() consumer semantics
4148 * requires this function to not return zero on an invalid descriptor
4149 * but rather a negative error number.
4151 if (!desc || IS_ERR(desc) || !desc->gdev || !desc->gdev->chip)
4154 gc = desc->gdev->chip;
4155 offset = gpio_chip_hwgpio(desc);
4157 int retirq = gc->to_irq(gc, offset);
4159 /* Zero means NO_IRQ */
4167 EXPORT_SYMBOL_GPL(gpiod_to_irq);
4170 * gpiochip_lock_as_irq() - lock a GPIO to be used as IRQ
4171 * @gc: the chip the GPIO to lock belongs to
4172 * @offset: the offset of the GPIO to lock as IRQ
4174 * This is used directly by GPIO drivers that want to lock down
4175 * a certain GPIO line to be used for IRQs.
4177 int gpiochip_lock_as_irq(struct gpio_chip *gc, unsigned int offset)
4179 struct gpio_desc *desc;
4181 desc = gpiochip_get_desc(gc, offset);
4183 return PTR_ERR(desc);
4186 * If it's fast: flush the direction setting if something changed
4189 if (!gc->can_sleep && gc->get_direction) {
4190 int dir = gpiod_get_direction(desc);
4193 chip_err(gc, "%s: cannot get GPIO direction\n",
4199 if (test_bit(FLAG_IS_OUT, &desc->flags)) {
4201 "%s: tried to flag a GPIO set as output for IRQ\n",
4206 set_bit(FLAG_USED_AS_IRQ, &desc->flags);
4207 set_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
4210 * If the consumer has not set up a label (such as when the
4211 * IRQ is referenced from .to_irq()) we set up a label here
4212 * so it is clear this is used as an interrupt.
4215 desc_set_label(desc, "interrupt");
4219 EXPORT_SYMBOL_GPL(gpiochip_lock_as_irq);
4222 * gpiochip_unlock_as_irq() - unlock a GPIO used as IRQ
4223 * @gc: the chip the GPIO to lock belongs to
4224 * @offset: the offset of the GPIO to lock as IRQ
4226 * This is used directly by GPIO drivers that want to indicate
4227 * that a certain GPIO is no longer used exclusively for IRQ.
4229 void gpiochip_unlock_as_irq(struct gpio_chip *gc, unsigned int offset)
4231 struct gpio_desc *desc;
4233 desc = gpiochip_get_desc(gc, offset);
4237 clear_bit(FLAG_USED_AS_IRQ, &desc->flags);
4238 clear_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
4240 /* If we only had this marking, erase it */
4241 if (desc->label && !strcmp(desc->label, "interrupt"))
4242 desc_set_label(desc, NULL);
4244 EXPORT_SYMBOL_GPL(gpiochip_unlock_as_irq);
4246 void gpiochip_disable_irq(struct gpio_chip *gc, unsigned int offset)
4248 struct gpio_desc *desc = gpiochip_get_desc(gc, offset);
4250 if (!IS_ERR(desc) &&
4251 !WARN_ON(!test_bit(FLAG_USED_AS_IRQ, &desc->flags)))
4252 clear_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
4254 EXPORT_SYMBOL_GPL(gpiochip_disable_irq);
4256 void gpiochip_enable_irq(struct gpio_chip *gc, unsigned int offset)
4258 struct gpio_desc *desc = gpiochip_get_desc(gc, offset);
4260 if (!IS_ERR(desc) &&
4261 !WARN_ON(!test_bit(FLAG_USED_AS_IRQ, &desc->flags))) {
4262 WARN_ON(test_bit(FLAG_IS_OUT, &desc->flags));
4263 set_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
4266 EXPORT_SYMBOL_GPL(gpiochip_enable_irq);
4268 bool gpiochip_line_is_irq(struct gpio_chip *gc, unsigned int offset)
4270 if (offset >= gc->ngpio)
4273 return test_bit(FLAG_USED_AS_IRQ, &gc->gpiodev->descs[offset].flags);
4275 EXPORT_SYMBOL_GPL(gpiochip_line_is_irq);
4277 int gpiochip_reqres_irq(struct gpio_chip *gc, unsigned int offset)
4281 if (!try_module_get(gc->gpiodev->owner))
4284 ret = gpiochip_lock_as_irq(gc, offset);
4286 chip_err(gc, "unable to lock HW IRQ %u for IRQ\n", offset);
4287 module_put(gc->gpiodev->owner);
4292 EXPORT_SYMBOL_GPL(gpiochip_reqres_irq);
4294 void gpiochip_relres_irq(struct gpio_chip *gc, unsigned int offset)
4296 gpiochip_unlock_as_irq(gc, offset);
4297 module_put(gc->gpiodev->owner);
4299 EXPORT_SYMBOL_GPL(gpiochip_relres_irq);
4301 bool gpiochip_line_is_open_drain(struct gpio_chip *gc, unsigned int offset)
4303 if (offset >= gc->ngpio)
4306 return test_bit(FLAG_OPEN_DRAIN, &gc->gpiodev->descs[offset].flags);
4308 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_drain);
4310 bool gpiochip_line_is_open_source(struct gpio_chip *gc, unsigned int offset)
4312 if (offset >= gc->ngpio)
4315 return test_bit(FLAG_OPEN_SOURCE, &gc->gpiodev->descs[offset].flags);
4317 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_source);
4319 bool gpiochip_line_is_persistent(struct gpio_chip *gc, unsigned int offset)
4321 if (offset >= gc->ngpio)
4324 return !test_bit(FLAG_TRANSITORY, &gc->gpiodev->descs[offset].flags);
4326 EXPORT_SYMBOL_GPL(gpiochip_line_is_persistent);
4329 * gpiod_get_raw_value_cansleep() - return a gpio's raw value
4330 * @desc: gpio whose value will be returned
4332 * Return the GPIO's raw value, i.e. the value of the physical line disregarding
4333 * its ACTIVE_LOW status, or negative errno on failure.
4335 * This function is to be called from contexts that can sleep.
4337 int gpiod_get_raw_value_cansleep(const struct gpio_desc *desc)
4339 might_sleep_if(extra_checks);
4340 VALIDATE_DESC(desc);
4341 return gpiod_get_raw_value_commit(desc);
4343 EXPORT_SYMBOL_GPL(gpiod_get_raw_value_cansleep);
4346 * gpiod_get_value_cansleep() - return a gpio's value
4347 * @desc: gpio whose value will be returned
4349 * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
4350 * account, or negative errno on failure.
4352 * This function is to be called from contexts that can sleep.
4354 int gpiod_get_value_cansleep(const struct gpio_desc *desc)
4358 might_sleep_if(extra_checks);
4359 VALIDATE_DESC(desc);
4360 value = gpiod_get_raw_value_commit(desc);
4364 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
4369 EXPORT_SYMBOL_GPL(gpiod_get_value_cansleep);
4372 * gpiod_get_raw_array_value_cansleep() - read raw values from an array of GPIOs
4373 * @array_size: number of elements in the descriptor array / value bitmap
4374 * @desc_array: array of GPIO descriptors whose values will be read
4375 * @array_info: information on applicability of fast bitmap processing path
4376 * @value_bitmap: bitmap to store the read values
4378 * Read the raw values of the GPIOs, i.e. the values of the physical lines
4379 * without regard for their ACTIVE_LOW status. Return 0 in case of success,
4380 * else an error code.
4382 * This function is to be called from contexts that can sleep.
4384 int gpiod_get_raw_array_value_cansleep(unsigned int array_size,
4385 struct gpio_desc **desc_array,
4386 struct gpio_array *array_info,
4387 unsigned long *value_bitmap)
4389 might_sleep_if(extra_checks);
4392 return gpiod_get_array_value_complex(true, true, array_size,
4393 desc_array, array_info,
4396 EXPORT_SYMBOL_GPL(gpiod_get_raw_array_value_cansleep);
4399 * gpiod_get_array_value_cansleep() - read values from an array of GPIOs
4400 * @array_size: number of elements in the descriptor array / value bitmap
4401 * @desc_array: array of GPIO descriptors whose values will be read
4402 * @array_info: information on applicability of fast bitmap processing path
4403 * @value_bitmap: bitmap to store the read values
4405 * Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
4406 * into account. Return 0 in case of success, else an error code.
4408 * This function is to be called from contexts that can sleep.
4410 int gpiod_get_array_value_cansleep(unsigned int array_size,
4411 struct gpio_desc **desc_array,
4412 struct gpio_array *array_info,
4413 unsigned long *value_bitmap)
4415 might_sleep_if(extra_checks);
4418 return gpiod_get_array_value_complex(false, true, array_size,
4419 desc_array, array_info,
4422 EXPORT_SYMBOL_GPL(gpiod_get_array_value_cansleep);
4425 * gpiod_set_raw_value_cansleep() - assign a gpio's raw value
4426 * @desc: gpio whose value will be assigned
4427 * @value: value to assign
4429 * Set the raw value of the GPIO, i.e. the value of its physical line without
4430 * regard for its ACTIVE_LOW status.
4432 * This function is to be called from contexts that can sleep.
4434 void gpiod_set_raw_value_cansleep(struct gpio_desc *desc, int value)
4436 might_sleep_if(extra_checks);
4437 VALIDATE_DESC_VOID(desc);
4438 gpiod_set_raw_value_commit(desc, value);
4440 EXPORT_SYMBOL_GPL(gpiod_set_raw_value_cansleep);
4443 * gpiod_set_value_cansleep() - assign a gpio's value
4444 * @desc: gpio whose value will be assigned
4445 * @value: value to assign
4447 * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
4450 * This function is to be called from contexts that can sleep.
4452 void gpiod_set_value_cansleep(struct gpio_desc *desc, int value)
4454 might_sleep_if(extra_checks);
4455 VALIDATE_DESC_VOID(desc);
4456 gpiod_set_value_nocheck(desc, value);
4458 EXPORT_SYMBOL_GPL(gpiod_set_value_cansleep);
4461 * gpiod_set_raw_array_value_cansleep() - assign values to an array of GPIOs
4462 * @array_size: number of elements in the descriptor array / value bitmap
4463 * @desc_array: array of GPIO descriptors whose values will be assigned
4464 * @array_info: information on applicability of fast bitmap processing path
4465 * @value_bitmap: bitmap of values to assign
4467 * Set the raw values of the GPIOs, i.e. the values of the physical lines
4468 * without regard for their ACTIVE_LOW status.
4470 * This function is to be called from contexts that can sleep.
4472 int gpiod_set_raw_array_value_cansleep(unsigned int array_size,
4473 struct gpio_desc **desc_array,
4474 struct gpio_array *array_info,
4475 unsigned long *value_bitmap)
4477 might_sleep_if(extra_checks);
4480 return gpiod_set_array_value_complex(true, true, array_size, desc_array,
4481 array_info, value_bitmap);
4483 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value_cansleep);
4486 * gpiod_add_lookup_tables() - register GPIO device consumers
4487 * @tables: list of tables of consumers to register
4488 * @n: number of tables in the list
4490 void gpiod_add_lookup_tables(struct gpiod_lookup_table **tables, size_t n)
4494 mutex_lock(&gpio_lookup_lock);
4496 for (i = 0; i < n; i++)
4497 list_add_tail(&tables[i]->list, &gpio_lookup_list);
4499 mutex_unlock(&gpio_lookup_lock);
4503 * gpiod_set_array_value_cansleep() - assign values to an array of GPIOs
4504 * @array_size: number of elements in the descriptor array / value bitmap
4505 * @desc_array: array of GPIO descriptors whose values will be assigned
4506 * @array_info: information on applicability of fast bitmap processing path
4507 * @value_bitmap: bitmap of values to assign
4509 * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
4512 * This function is to be called from contexts that can sleep.
4514 int gpiod_set_array_value_cansleep(unsigned int array_size,
4515 struct gpio_desc **desc_array,
4516 struct gpio_array *array_info,
4517 unsigned long *value_bitmap)
4519 might_sleep_if(extra_checks);
4522 return gpiod_set_array_value_complex(false, true, array_size,
4523 desc_array, array_info,
4526 EXPORT_SYMBOL_GPL(gpiod_set_array_value_cansleep);
4529 * gpiod_add_lookup_table() - register GPIO device consumers
4530 * @table: table of consumers to register
4532 void gpiod_add_lookup_table(struct gpiod_lookup_table *table)
4534 mutex_lock(&gpio_lookup_lock);
4536 list_add_tail(&table->list, &gpio_lookup_list);
4538 mutex_unlock(&gpio_lookup_lock);
4540 EXPORT_SYMBOL_GPL(gpiod_add_lookup_table);
4543 * gpiod_remove_lookup_table() - unregister GPIO device consumers
4544 * @table: table of consumers to unregister
4546 void gpiod_remove_lookup_table(struct gpiod_lookup_table *table)
4548 mutex_lock(&gpio_lookup_lock);
4550 list_del(&table->list);
4552 mutex_unlock(&gpio_lookup_lock);
4554 EXPORT_SYMBOL_GPL(gpiod_remove_lookup_table);
4557 * gpiod_add_hogs() - register a set of GPIO hogs from machine code
4558 * @hogs: table of gpio hog entries with a zeroed sentinel at the end
4560 void gpiod_add_hogs(struct gpiod_hog *hogs)
4562 struct gpio_chip *gc;
4563 struct gpiod_hog *hog;
4565 mutex_lock(&gpio_machine_hogs_mutex);
4567 for (hog = &hogs[0]; hog->chip_label; hog++) {
4568 list_add_tail(&hog->list, &gpio_machine_hogs);
4571 * The chip may have been registered earlier, so check if it
4572 * exists and, if so, try to hog the line now.
4574 gc = find_chip_by_name(hog->chip_label);
4576 gpiochip_machine_hog(gc, hog);
4579 mutex_unlock(&gpio_machine_hogs_mutex);
4581 EXPORT_SYMBOL_GPL(gpiod_add_hogs);
4583 static struct gpiod_lookup_table *gpiod_find_lookup_table(struct device *dev)
4585 const char *dev_id = dev ? dev_name(dev) : NULL;
4586 struct gpiod_lookup_table *table;
4588 mutex_lock(&gpio_lookup_lock);
4590 list_for_each_entry(table, &gpio_lookup_list, list) {
4591 if (table->dev_id && dev_id) {
4593 * Valid strings on both ends, must be identical to have
4596 if (!strcmp(table->dev_id, dev_id))
4600 * One of the pointers is NULL, so both must be to have
4603 if (dev_id == table->dev_id)
4610 mutex_unlock(&gpio_lookup_lock);
4614 static struct gpio_desc *gpiod_find(struct device *dev, const char *con_id,
4615 unsigned int idx, unsigned long *flags)
4617 struct gpio_desc *desc = ERR_PTR(-ENOENT);
4618 struct gpiod_lookup_table *table;
4619 struct gpiod_lookup *p;
4621 table = gpiod_find_lookup_table(dev);
4625 for (p = &table->table[0]; p->chip_label; p++) {
4626 struct gpio_chip *gc;
4628 /* idx must always match exactly */
4632 /* If the lookup entry has a con_id, require exact match */
4633 if (p->con_id && (!con_id || strcmp(p->con_id, con_id)))
4636 gc = find_chip_by_name(p->chip_label);
4640 * As the lookup table indicates a chip with
4641 * p->chip_label should exist, assume it may
4642 * still appear later and let the interested
4643 * consumer be probed again or let the Deferred
4644 * Probe infrastructure handle the error.
4646 dev_warn(dev, "cannot find GPIO chip %s, deferring\n",
4648 return ERR_PTR(-EPROBE_DEFER);
4651 if (gc->ngpio <= p->chip_hwnum) {
4653 "requested GPIO %u (%u) is out of range [0..%u] for chip %s\n",
4654 idx, p->chip_hwnum, gc->ngpio - 1,
4656 return ERR_PTR(-EINVAL);
4659 desc = gpiochip_get_desc(gc, p->chip_hwnum);
4668 static int platform_gpio_count(struct device *dev, const char *con_id)
4670 struct gpiod_lookup_table *table;
4671 struct gpiod_lookup *p;
4672 unsigned int count = 0;
4674 table = gpiod_find_lookup_table(dev);
4678 for (p = &table->table[0]; p->chip_label; p++) {
4679 if ((con_id && p->con_id && !strcmp(con_id, p->con_id)) ||
4680 (!con_id && !p->con_id))
4690 * fwnode_gpiod_get_index - obtain a GPIO from firmware node
4691 * @fwnode: handle of the firmware node
4692 * @con_id: function within the GPIO consumer
4693 * @index: index of the GPIO to obtain for the consumer
4694 * @flags: GPIO initialization flags
4695 * @label: label to attach to the requested GPIO
4697 * This function can be used for drivers that get their configuration
4698 * from opaque firmware.
4700 * The function properly finds the corresponding GPIO using whatever is the
4701 * underlying firmware interface and then makes sure that the GPIO
4702 * descriptor is requested before it is returned to the caller.
4705 * On successful request the GPIO pin is configured in accordance with
4708 * In case of error an ERR_PTR() is returned.
4710 struct gpio_desc *fwnode_gpiod_get_index(struct fwnode_handle *fwnode,
4711 const char *con_id, int index,
4712 enum gpiod_flags flags,
4715 struct gpio_desc *desc;
4716 char prop_name[32]; /* 32 is max size of property name */
4719 for (i = 0; i < ARRAY_SIZE(gpio_suffixes); i++) {
4721 snprintf(prop_name, sizeof(prop_name), "%s-%s",
4722 con_id, gpio_suffixes[i]);
4724 snprintf(prop_name, sizeof(prop_name), "%s",
4727 desc = fwnode_get_named_gpiod(fwnode, prop_name, index, flags,
4729 if (!IS_ERR(desc) || (PTR_ERR(desc) != -ENOENT))
4735 EXPORT_SYMBOL_GPL(fwnode_gpiod_get_index);
4738 * gpiod_count - return the number of GPIOs associated with a device / function
4739 * or -ENOENT if no GPIO has been assigned to the requested function
4740 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4741 * @con_id: function within the GPIO consumer
4743 int gpiod_count(struct device *dev, const char *con_id)
4745 int count = -ENOENT;
4747 if (IS_ENABLED(CONFIG_OF) && dev && dev->of_node)
4748 count = of_gpio_get_count(dev, con_id);
4749 else if (IS_ENABLED(CONFIG_ACPI) && dev && ACPI_HANDLE(dev))
4750 count = acpi_gpio_count(dev, con_id);
4753 count = platform_gpio_count(dev, con_id);
4757 EXPORT_SYMBOL_GPL(gpiod_count);
4760 * gpiod_get - obtain a GPIO for a given GPIO function
4761 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4762 * @con_id: function within the GPIO consumer
4763 * @flags: optional GPIO initialization flags
4765 * Return the GPIO descriptor corresponding to the function con_id of device
4766 * dev, -ENOENT if no GPIO has been assigned to the requested function, or
4767 * another IS_ERR() code if an error occurred while trying to acquire the GPIO.
4769 struct gpio_desc *__must_check gpiod_get(struct device *dev, const char *con_id,
4770 enum gpiod_flags flags)
4772 return gpiod_get_index(dev, con_id, 0, flags);
4774 EXPORT_SYMBOL_GPL(gpiod_get);
4777 * gpiod_get_optional - obtain an optional GPIO for a given GPIO function
4778 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4779 * @con_id: function within the GPIO consumer
4780 * @flags: optional GPIO initialization flags
4782 * This is equivalent to gpiod_get(), except that when no GPIO was assigned to
4783 * the requested function it will return NULL. This is convenient for drivers
4784 * that need to handle optional GPIOs.
4786 struct gpio_desc *__must_check gpiod_get_optional(struct device *dev,
4788 enum gpiod_flags flags)
4790 return gpiod_get_index_optional(dev, con_id, 0, flags);
4792 EXPORT_SYMBOL_GPL(gpiod_get_optional);
4796 * gpiod_configure_flags - helper function to configure a given GPIO
4797 * @desc: gpio whose value will be assigned
4798 * @con_id: function within the GPIO consumer
4799 * @lflags: bitmask of gpio_lookup_flags GPIO_* values - returned from
4800 * of_find_gpio() or of_get_gpio_hog()
4801 * @dflags: gpiod_flags - optional GPIO initialization flags
4803 * Return 0 on success, -ENOENT if no GPIO has been assigned to the
4804 * requested function and/or index, or another IS_ERR() code if an error
4805 * occurred while trying to acquire the GPIO.
4807 int gpiod_configure_flags(struct gpio_desc *desc, const char *con_id,
4808 unsigned long lflags, enum gpiod_flags dflags)
4812 if (lflags & GPIO_ACTIVE_LOW)
4813 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
4815 if (lflags & GPIO_OPEN_DRAIN)
4816 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
4817 else if (dflags & GPIOD_FLAGS_BIT_OPEN_DRAIN) {
4819 * This enforces open drain mode from the consumer side.
4820 * This is necessary for some busses like I2C, but the lookup
4821 * should *REALLY* have specified them as open drain in the
4822 * first place, so print a little warning here.
4824 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
4826 "enforced open drain please flag it properly in DT/ACPI DSDT/board file\n");
4829 if (lflags & GPIO_OPEN_SOURCE)
4830 set_bit(FLAG_OPEN_SOURCE, &desc->flags);
4832 if ((lflags & GPIO_PULL_UP) && (lflags & GPIO_PULL_DOWN)) {
4834 "both pull-up and pull-down enabled, invalid configuration\n");
4838 if (lflags & GPIO_PULL_UP)
4839 set_bit(FLAG_PULL_UP, &desc->flags);
4840 else if (lflags & GPIO_PULL_DOWN)
4841 set_bit(FLAG_PULL_DOWN, &desc->flags);
4843 ret = gpiod_set_transitory(desc, (lflags & GPIO_TRANSITORY));
4847 /* No particular flag request, return here... */
4848 if (!(dflags & GPIOD_FLAGS_BIT_DIR_SET)) {
4849 gpiod_dbg(desc, "no flags found for %s\n", con_id);
4854 if (dflags & GPIOD_FLAGS_BIT_DIR_OUT)
4855 ret = gpiod_direction_output(desc,
4856 !!(dflags & GPIOD_FLAGS_BIT_DIR_VAL));
4858 ret = gpiod_direction_input(desc);
4864 * gpiod_get_index - obtain a GPIO from a multi-index GPIO function
4865 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4866 * @con_id: function within the GPIO consumer
4867 * @idx: index of the GPIO to obtain in the consumer
4868 * @flags: optional GPIO initialization flags
4870 * This variant of gpiod_get() allows to access GPIOs other than the first
4871 * defined one for functions that define several GPIOs.
4873 * Return a valid GPIO descriptor, -ENOENT if no GPIO has been assigned to the
4874 * requested function and/or index, or another IS_ERR() code if an error
4875 * occurred while trying to acquire the GPIO.
4877 struct gpio_desc *__must_check gpiod_get_index(struct device *dev,
4880 enum gpiod_flags flags)
4882 unsigned long lookupflags = GPIO_LOOKUP_FLAGS_DEFAULT;
4883 struct gpio_desc *desc = NULL;
4885 /* Maybe we have a device name, maybe not */
4886 const char *devname = dev ? dev_name(dev) : "?";
4888 dev_dbg(dev, "GPIO lookup for consumer %s\n", con_id);
4891 /* Using device tree? */
4892 if (IS_ENABLED(CONFIG_OF) && dev->of_node) {
4893 dev_dbg(dev, "using device tree for GPIO lookup\n");
4894 desc = of_find_gpio(dev, con_id, idx, &lookupflags);
4895 } else if (ACPI_COMPANION(dev)) {
4896 dev_dbg(dev, "using ACPI for GPIO lookup\n");
4897 desc = acpi_find_gpio(dev, con_id, idx, &flags, &lookupflags);
4902 * Either we are not using DT or ACPI, or their lookup did not return
4903 * a result. In that case, use platform lookup as a fallback.
4905 if (!desc || desc == ERR_PTR(-ENOENT)) {
4906 dev_dbg(dev, "using lookup tables for GPIO lookup\n");
4907 desc = gpiod_find(dev, con_id, idx, &lookupflags);
4911 dev_dbg(dev, "No GPIO consumer %s found\n", con_id);
4916 * If a connection label was passed use that, else attempt to use
4917 * the device name as label
4919 ret = gpiod_request(desc, con_id ? con_id : devname);
4921 if (ret == -EBUSY && flags & GPIOD_FLAGS_BIT_NONEXCLUSIVE) {
4923 * This happens when there are several consumers for
4924 * the same GPIO line: we just return here without
4925 * further initialization. It is a bit if a hack.
4926 * This is necessary to support fixed regulators.
4928 * FIXME: Make this more sane and safe.
4930 dev_info(dev, "nonexclusive access to GPIO for %s\n",
4931 con_id ? con_id : devname);
4934 return ERR_PTR(ret);
4938 ret = gpiod_configure_flags(desc, con_id, lookupflags, flags);
4940 dev_dbg(dev, "setup of GPIO %s failed\n", con_id);
4942 return ERR_PTR(ret);
4947 EXPORT_SYMBOL_GPL(gpiod_get_index);
4950 * fwnode_get_named_gpiod - obtain a GPIO from firmware node
4951 * @fwnode: handle of the firmware node
4952 * @propname: name of the firmware property representing the GPIO
4953 * @index: index of the GPIO to obtain for the consumer
4954 * @dflags: GPIO initialization flags
4955 * @label: label to attach to the requested GPIO
4957 * This function can be used for drivers that get their configuration
4958 * from opaque firmware.
4960 * The function properly finds the corresponding GPIO using whatever is the
4961 * underlying firmware interface and then makes sure that the GPIO
4962 * descriptor is requested before it is returned to the caller.
4965 * On successful request the GPIO pin is configured in accordance with
4968 * In case of error an ERR_PTR() is returned.
4970 struct gpio_desc *fwnode_get_named_gpiod(struct fwnode_handle *fwnode,
4971 const char *propname, int index,
4972 enum gpiod_flags dflags,
4975 unsigned long lflags = GPIO_LOOKUP_FLAGS_DEFAULT;
4976 struct gpio_desc *desc = ERR_PTR(-ENODEV);
4980 return ERR_PTR(-EINVAL);
4982 if (is_of_node(fwnode)) {
4983 desc = gpiod_get_from_of_node(to_of_node(fwnode),
4988 } else if (is_acpi_node(fwnode)) {
4989 struct acpi_gpio_info info;
4991 desc = acpi_node_get_gpiod(fwnode, propname, index, &info);
4995 acpi_gpio_update_gpiod_flags(&dflags, &info);
4996 acpi_gpio_update_gpiod_lookup_flags(&lflags, &info);
4999 /* Currently only ACPI takes this path */
5000 ret = gpiod_request(desc, label);
5002 return ERR_PTR(ret);
5004 ret = gpiod_configure_flags(desc, propname, lflags, dflags);
5007 return ERR_PTR(ret);
5012 EXPORT_SYMBOL_GPL(fwnode_get_named_gpiod);
5015 * gpiod_get_index_optional - obtain an optional GPIO from a multi-index GPIO
5017 * @dev: GPIO consumer, can be NULL for system-global GPIOs
5018 * @con_id: function within the GPIO consumer
5019 * @index: index of the GPIO to obtain in the consumer
5020 * @flags: optional GPIO initialization flags
5022 * This is equivalent to gpiod_get_index(), except that when no GPIO with the
5023 * specified index was assigned to the requested function it will return NULL.
5024 * This is convenient for drivers that need to handle optional GPIOs.
5026 struct gpio_desc *__must_check gpiod_get_index_optional(struct device *dev,
5029 enum gpiod_flags flags)
5031 struct gpio_desc *desc;
5033 desc = gpiod_get_index(dev, con_id, index, flags);
5035 if (PTR_ERR(desc) == -ENOENT)
5041 EXPORT_SYMBOL_GPL(gpiod_get_index_optional);
5044 * gpiod_hog - Hog the specified GPIO desc given the provided flags
5045 * @desc: gpio whose value will be assigned
5046 * @name: gpio line name
5047 * @lflags: bitmask of gpio_lookup_flags GPIO_* values - returned from
5048 * of_find_gpio() or of_get_gpio_hog()
5049 * @dflags: gpiod_flags - optional GPIO initialization flags
5051 int gpiod_hog(struct gpio_desc *desc, const char *name,
5052 unsigned long lflags, enum gpiod_flags dflags)
5054 struct gpio_chip *gc;
5055 struct gpio_desc *local_desc;
5059 gc = gpiod_to_chip(desc);
5060 hwnum = gpio_chip_hwgpio(desc);
5062 local_desc = gpiochip_request_own_desc(gc, hwnum, name,
5064 if (IS_ERR(local_desc)) {
5065 ret = PTR_ERR(local_desc);
5066 pr_err("requesting hog GPIO %s (chip %s, offset %d) failed, %d\n",
5067 name, gc->label, hwnum, ret);
5071 /* Mark GPIO as hogged so it can be identified and removed later */
5072 set_bit(FLAG_IS_HOGGED, &desc->flags);
5074 gpiod_info(desc, "hogged as %s%s\n",
5075 (dflags & GPIOD_FLAGS_BIT_DIR_OUT) ? "output" : "input",
5076 (dflags & GPIOD_FLAGS_BIT_DIR_OUT) ?
5077 (dflags & GPIOD_FLAGS_BIT_DIR_VAL) ? "/high" : "/low" : "");
5083 * gpiochip_free_hogs - Scan gpio-controller chip and release GPIO hog
5084 * @gc: gpio chip to act on
5086 static void gpiochip_free_hogs(struct gpio_chip *gc)
5090 for (id = 0; id < gc->ngpio; id++) {
5091 if (test_bit(FLAG_IS_HOGGED, &gc->gpiodev->descs[id].flags))
5092 gpiochip_free_own_desc(&gc->gpiodev->descs[id]);
5097 * gpiod_get_array - obtain multiple GPIOs from a multi-index GPIO function
5098 * @dev: GPIO consumer, can be NULL for system-global GPIOs
5099 * @con_id: function within the GPIO consumer
5100 * @flags: optional GPIO initialization flags
5102 * This function acquires all the GPIOs defined under a given function.
5104 * Return a struct gpio_descs containing an array of descriptors, -ENOENT if
5105 * no GPIO has been assigned to the requested function, or another IS_ERR()
5106 * code if an error occurred while trying to acquire the GPIOs.
5108 struct gpio_descs *__must_check gpiod_get_array(struct device *dev,
5110 enum gpiod_flags flags)
5112 struct gpio_desc *desc;
5113 struct gpio_descs *descs;
5114 struct gpio_array *array_info = NULL;
5115 struct gpio_chip *gc;
5116 int count, bitmap_size;
5118 count = gpiod_count(dev, con_id);
5120 return ERR_PTR(count);
5122 descs = kzalloc(struct_size(descs, desc, count), GFP_KERNEL);
5124 return ERR_PTR(-ENOMEM);
5126 for (descs->ndescs = 0; descs->ndescs < count; ) {
5127 desc = gpiod_get_index(dev, con_id, descs->ndescs, flags);
5129 gpiod_put_array(descs);
5130 return ERR_CAST(desc);
5133 descs->desc[descs->ndescs] = desc;
5135 gc = gpiod_to_chip(desc);
5137 * If pin hardware number of array member 0 is also 0, select
5138 * its chip as a candidate for fast bitmap processing path.
5140 if (descs->ndescs == 0 && gpio_chip_hwgpio(desc) == 0) {
5141 struct gpio_descs *array;
5143 bitmap_size = BITS_TO_LONGS(gc->ngpio > count ?
5146 array = kzalloc(struct_size(descs, desc, count) +
5147 struct_size(array_info, invert_mask,
5148 3 * bitmap_size), GFP_KERNEL);
5150 gpiod_put_array(descs);
5151 return ERR_PTR(-ENOMEM);
5154 memcpy(array, descs,
5155 struct_size(descs, desc, descs->ndescs + 1));
5159 array_info = (void *)(descs->desc + count);
5160 array_info->get_mask = array_info->invert_mask +
5162 array_info->set_mask = array_info->get_mask +
5165 array_info->desc = descs->desc;
5166 array_info->size = count;
5167 array_info->chip = gc;
5168 bitmap_set(array_info->get_mask, descs->ndescs,
5169 count - descs->ndescs);
5170 bitmap_set(array_info->set_mask, descs->ndescs,
5171 count - descs->ndescs);
5172 descs->info = array_info;
5174 /* Unmark array members which don't belong to the 'fast' chip */
5175 if (array_info && array_info->chip != gc) {
5176 __clear_bit(descs->ndescs, array_info->get_mask);
5177 __clear_bit(descs->ndescs, array_info->set_mask);
5180 * Detect array members which belong to the 'fast' chip
5181 * but their pins are not in hardware order.
5183 else if (array_info &&
5184 gpio_chip_hwgpio(desc) != descs->ndescs) {
5186 * Don't use fast path if all array members processed so
5187 * far belong to the same chip as this one but its pin
5188 * hardware number is different from its array index.
5190 if (bitmap_full(array_info->get_mask, descs->ndescs)) {
5193 __clear_bit(descs->ndescs,
5194 array_info->get_mask);
5195 __clear_bit(descs->ndescs,
5196 array_info->set_mask);
5198 } else if (array_info) {
5199 /* Exclude open drain or open source from fast output */
5200 if (gpiochip_line_is_open_drain(gc, descs->ndescs) ||
5201 gpiochip_line_is_open_source(gc, descs->ndescs))
5202 __clear_bit(descs->ndescs,
5203 array_info->set_mask);
5204 /* Identify 'fast' pins which require invertion */
5205 if (gpiod_is_active_low(desc))
5206 __set_bit(descs->ndescs,
5207 array_info->invert_mask);
5214 "GPIO array info: chip=%s, size=%d, get_mask=%lx, set_mask=%lx, invert_mask=%lx\n",
5215 array_info->chip->label, array_info->size,
5216 *array_info->get_mask, *array_info->set_mask,
5217 *array_info->invert_mask);
5220 EXPORT_SYMBOL_GPL(gpiod_get_array);
5223 * gpiod_get_array_optional - obtain multiple GPIOs from a multi-index GPIO
5225 * @dev: GPIO consumer, can be NULL for system-global GPIOs
5226 * @con_id: function within the GPIO consumer
5227 * @flags: optional GPIO initialization flags
5229 * This is equivalent to gpiod_get_array(), except that when no GPIO was
5230 * assigned to the requested function it will return NULL.
5232 struct gpio_descs *__must_check gpiod_get_array_optional(struct device *dev,
5234 enum gpiod_flags flags)
5236 struct gpio_descs *descs;
5238 descs = gpiod_get_array(dev, con_id, flags);
5239 if (PTR_ERR(descs) == -ENOENT)
5244 EXPORT_SYMBOL_GPL(gpiod_get_array_optional);
5247 * gpiod_put - dispose of a GPIO descriptor
5248 * @desc: GPIO descriptor to dispose of
5250 * No descriptor can be used after gpiod_put() has been called on it.
5252 void gpiod_put(struct gpio_desc *desc)
5257 EXPORT_SYMBOL_GPL(gpiod_put);
5260 * gpiod_put_array - dispose of multiple GPIO descriptors
5261 * @descs: struct gpio_descs containing an array of descriptors
5263 void gpiod_put_array(struct gpio_descs *descs)
5267 for (i = 0; i < descs->ndescs; i++)
5268 gpiod_put(descs->desc[i]);
5272 EXPORT_SYMBOL_GPL(gpiod_put_array);
5274 static int __init gpiolib_dev_init(void)
5278 /* Register GPIO sysfs bus */
5279 ret = bus_register(&gpio_bus_type);
5281 pr_err("gpiolib: could not register GPIO bus type\n");
5285 ret = alloc_chrdev_region(&gpio_devt, 0, GPIO_DEV_MAX, GPIOCHIP_NAME);
5287 pr_err("gpiolib: failed to allocate char dev region\n");
5288 bus_unregister(&gpio_bus_type);
5292 gpiolib_initialized = true;
5293 gpiochip_setup_devs();
5295 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
5296 WARN_ON(of_reconfig_notifier_register(&gpio_of_notifier));
5300 core_initcall(gpiolib_dev_init);
5302 #ifdef CONFIG_DEBUG_FS
5304 static void gpiolib_dbg_show(struct seq_file *s, struct gpio_device *gdev)
5307 struct gpio_chip *gc = gdev->chip;
5308 unsigned gpio = gdev->base;
5309 struct gpio_desc *gdesc = &gdev->descs[0];
5314 for (i = 0; i < gdev->ngpio; i++, gpio++, gdesc++) {
5315 if (!test_bit(FLAG_REQUESTED, &gdesc->flags)) {
5317 seq_printf(s, " gpio-%-3d (%-20.20s)\n",
5323 gpiod_get_direction(gdesc);
5324 is_out = test_bit(FLAG_IS_OUT, &gdesc->flags);
5325 is_irq = test_bit(FLAG_USED_AS_IRQ, &gdesc->flags);
5326 active_low = test_bit(FLAG_ACTIVE_LOW, &gdesc->flags);
5327 seq_printf(s, " gpio-%-3d (%-20.20s|%-20.20s) %s %s %s%s",
5328 gpio, gdesc->name ? gdesc->name : "", gdesc->label,
5329 is_out ? "out" : "in ",
5330 gc->get ? (gc->get(gc, i) ? "hi" : "lo") : "? ",
5331 is_irq ? "IRQ " : "",
5332 active_low ? "ACTIVE LOW" : "");
5333 seq_printf(s, "\n");
5337 static void *gpiolib_seq_start(struct seq_file *s, loff_t *pos)
5339 unsigned long flags;
5340 struct gpio_device *gdev = NULL;
5341 loff_t index = *pos;
5345 spin_lock_irqsave(&gpio_lock, flags);
5346 list_for_each_entry(gdev, &gpio_devices, list)
5348 spin_unlock_irqrestore(&gpio_lock, flags);
5351 spin_unlock_irqrestore(&gpio_lock, flags);
5356 static void *gpiolib_seq_next(struct seq_file *s, void *v, loff_t *pos)
5358 unsigned long flags;
5359 struct gpio_device *gdev = v;
5362 spin_lock_irqsave(&gpio_lock, flags);
5363 if (list_is_last(&gdev->list, &gpio_devices))
5366 ret = list_entry(gdev->list.next, struct gpio_device, list);
5367 spin_unlock_irqrestore(&gpio_lock, flags);
5375 static void gpiolib_seq_stop(struct seq_file *s, void *v)
5379 static int gpiolib_seq_show(struct seq_file *s, void *v)
5381 struct gpio_device *gdev = v;
5382 struct gpio_chip *gc = gdev->chip;
5383 struct device *parent;
5386 seq_printf(s, "%s%s: (dangling chip)", (char *)s->private,
5387 dev_name(&gdev->dev));
5391 seq_printf(s, "%s%s: GPIOs %d-%d", (char *)s->private,
5392 dev_name(&gdev->dev),
5393 gdev->base, gdev->base + gdev->ngpio - 1);
5394 parent = gc->parent;
5396 seq_printf(s, ", parent: %s/%s",
5397 parent->bus ? parent->bus->name : "no-bus",
5400 seq_printf(s, ", %s", gc->label);
5402 seq_printf(s, ", can sleep");
5403 seq_printf(s, ":\n");
5406 gc->dbg_show(s, gc);
5408 gpiolib_dbg_show(s, gdev);
5413 static const struct seq_operations gpiolib_seq_ops = {
5414 .start = gpiolib_seq_start,
5415 .next = gpiolib_seq_next,
5416 .stop = gpiolib_seq_stop,
5417 .show = gpiolib_seq_show,
5420 static int gpiolib_open(struct inode *inode, struct file *file)
5422 return seq_open(file, &gpiolib_seq_ops);
5425 static const struct file_operations gpiolib_operations = {
5426 .owner = THIS_MODULE,
5427 .open = gpiolib_open,
5429 .llseek = seq_lseek,
5430 .release = seq_release,
5433 static int __init gpiolib_debugfs_init(void)
5435 /* /sys/kernel/debug/gpio */
5436 debugfs_create_file("gpio", S_IFREG | S_IRUGO, NULL, NULL,
5437 &gpiolib_operations);
5440 subsys_initcall(gpiolib_debugfs_init);
5442 #endif /* DEBUG_FS */