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);
738 atomic_notifier_call_chain(&desc->gdev->notifier,
739 GPIOLINE_CHANGED_REQUESTED, desc);
741 dev_dbg(&gdev->dev, "registered chardev handle for line %d\n",
744 /* Let i point at the last handle */
746 lh->numdescs = handlereq.lines;
748 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
754 file = anon_inode_getfile("gpio-linehandle",
757 O_RDONLY | O_CLOEXEC);
760 goto out_put_unused_fd;
764 if (copy_to_user(ip, &handlereq, sizeof(handlereq))) {
766 * fput() will trigger the release() callback, so do not go onto
767 * the regular error cleanup path here.
774 fd_install(fd, file);
776 dev_dbg(&gdev->dev, "registered chardev handle for %d lines\n",
784 for (i = 0; i < count; i++)
785 gpiod_free(lh->descs[i]);
789 put_device(&gdev->dev);
794 * GPIO line event management
798 * struct lineevent_state - contains the state of a userspace event
799 * @gdev: the GPIO device the event pertains to
800 * @label: consumer label used to tag descriptors
801 * @desc: the GPIO descriptor held by this event
802 * @eflags: the event flags this line was requested with
803 * @irq: the interrupt that trigger in response to events on this GPIO
804 * @wait: wait queue that handles blocking reads of events
805 * @events: KFIFO for the GPIO events
806 * @timestamp: cache for the timestamp storing it between hardirq
807 * and IRQ thread, used to bring the timestamp close to the actual
810 struct lineevent_state {
811 struct gpio_device *gdev;
813 struct gpio_desc *desc;
816 wait_queue_head_t wait;
817 DECLARE_KFIFO(events, struct gpioevent_data, 16);
821 #define GPIOEVENT_REQUEST_VALID_FLAGS \
822 (GPIOEVENT_REQUEST_RISING_EDGE | \
823 GPIOEVENT_REQUEST_FALLING_EDGE)
825 static __poll_t lineevent_poll(struct file *filep,
826 struct poll_table_struct *wait)
828 struct lineevent_state *le = filep->private_data;
831 poll_wait(filep, &le->wait, wait);
833 if (!kfifo_is_empty_spinlocked_noirqsave(&le->events, &le->wait.lock))
834 events = EPOLLIN | EPOLLRDNORM;
840 static ssize_t lineevent_read(struct file *filep,
845 struct lineevent_state *le = filep->private_data;
846 struct gpioevent_data ge;
847 ssize_t bytes_read = 0;
850 if (count < sizeof(ge))
854 spin_lock(&le->wait.lock);
855 if (kfifo_is_empty(&le->events)) {
857 spin_unlock(&le->wait.lock);
861 if (filep->f_flags & O_NONBLOCK) {
862 spin_unlock(&le->wait.lock);
866 ret = wait_event_interruptible_locked(le->wait,
867 !kfifo_is_empty(&le->events));
869 spin_unlock(&le->wait.lock);
874 ret = kfifo_out(&le->events, &ge, 1);
875 spin_unlock(&le->wait.lock);
878 * This should never happen - we were holding the lock
879 * from the moment we learned the fifo is no longer
886 if (copy_to_user(buf + bytes_read, &ge, sizeof(ge)))
888 bytes_read += sizeof(ge);
889 } while (count >= bytes_read + sizeof(ge));
894 static int lineevent_release(struct inode *inode, struct file *filep)
896 struct lineevent_state *le = filep->private_data;
897 struct gpio_device *gdev = le->gdev;
899 free_irq(le->irq, le);
900 gpiod_free(le->desc);
903 put_device(&gdev->dev);
907 static long lineevent_ioctl(struct file *filep, unsigned int cmd,
910 struct lineevent_state *le = filep->private_data;
911 void __user *ip = (void __user *)arg;
912 struct gpiohandle_data ghd;
915 * We can get the value for an event line but not set it,
916 * because it is input by definition.
918 if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
921 memset(&ghd, 0, sizeof(ghd));
923 val = gpiod_get_value_cansleep(le->desc);
928 if (copy_to_user(ip, &ghd, sizeof(ghd)))
937 static long lineevent_ioctl_compat(struct file *filep, unsigned int cmd,
940 return lineevent_ioctl(filep, cmd, (unsigned long)compat_ptr(arg));
944 static const struct file_operations lineevent_fileops = {
945 .release = lineevent_release,
946 .read = lineevent_read,
947 .poll = lineevent_poll,
948 .owner = THIS_MODULE,
949 .llseek = noop_llseek,
950 .unlocked_ioctl = lineevent_ioctl,
952 .compat_ioctl = lineevent_ioctl_compat,
956 static irqreturn_t lineevent_irq_thread(int irq, void *p)
958 struct lineevent_state *le = p;
959 struct gpioevent_data ge;
962 /* Do not leak kernel stack to userspace */
963 memset(&ge, 0, sizeof(ge));
966 * We may be running from a nested threaded interrupt in which case
967 * we didn't get the timestamp from lineevent_irq_handler().
970 ge.timestamp = ktime_get_ns();
972 ge.timestamp = le->timestamp;
974 if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE
975 && le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
976 int level = gpiod_get_value_cansleep(le->desc);
978 /* Emit low-to-high event */
979 ge.id = GPIOEVENT_EVENT_RISING_EDGE;
981 /* Emit high-to-low event */
982 ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
983 } else if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE) {
984 /* Emit low-to-high event */
985 ge.id = GPIOEVENT_EVENT_RISING_EDGE;
986 } else if (le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
987 /* Emit high-to-low event */
988 ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
993 ret = kfifo_in_spinlocked_noirqsave(&le->events, &ge,
996 wake_up_poll(&le->wait, EPOLLIN);
998 pr_debug_ratelimited("event FIFO is full - event dropped\n");
1003 static irqreturn_t lineevent_irq_handler(int irq, void *p)
1005 struct lineevent_state *le = p;
1008 * Just store the timestamp in hardirq context so we get it as
1009 * close in time as possible to the actual event.
1011 le->timestamp = ktime_get_ns();
1013 return IRQ_WAKE_THREAD;
1016 static int lineevent_create(struct gpio_device *gdev, void __user *ip)
1018 struct gpioevent_request eventreq;
1019 struct lineevent_state *le;
1020 struct gpio_desc *desc;
1029 if (copy_from_user(&eventreq, ip, sizeof(eventreq)))
1032 offset = eventreq.lineoffset;
1033 lflags = eventreq.handleflags;
1034 eflags = eventreq.eventflags;
1036 desc = gpiochip_get_desc(gdev->chip, offset);
1038 return PTR_ERR(desc);
1040 /* Return an error if a unknown flag is set */
1041 if ((lflags & ~GPIOHANDLE_REQUEST_VALID_FLAGS) ||
1042 (eflags & ~GPIOEVENT_REQUEST_VALID_FLAGS))
1045 /* This is just wrong: we don't look for events on output lines */
1046 if ((lflags & GPIOHANDLE_REQUEST_OUTPUT) ||
1047 (lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN) ||
1048 (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE))
1051 /* Only one bias flag can be set. */
1052 if (((lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE) &&
1053 (lflags & (GPIOHANDLE_REQUEST_BIAS_PULL_DOWN |
1054 GPIOHANDLE_REQUEST_BIAS_PULL_UP))) ||
1055 ((lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN) &&
1056 (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)))
1059 le = kzalloc(sizeof(*le), GFP_KERNEL);
1063 get_device(&gdev->dev);
1065 /* Make sure this is terminated */
1066 eventreq.consumer_label[sizeof(eventreq.consumer_label)-1] = '\0';
1067 if (strlen(eventreq.consumer_label)) {
1068 le->label = kstrdup(eventreq.consumer_label,
1076 ret = gpiod_request(desc, le->label);
1078 goto out_free_label;
1080 le->eflags = eflags;
1082 if (lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW)
1083 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
1084 if (lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE)
1085 set_bit(FLAG_BIAS_DISABLE, &desc->flags);
1086 if (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN)
1087 set_bit(FLAG_PULL_DOWN, &desc->flags);
1088 if (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)
1089 set_bit(FLAG_PULL_UP, &desc->flags);
1091 ret = gpiod_direction_input(desc);
1095 atomic_notifier_call_chain(&desc->gdev->notifier,
1096 GPIOLINE_CHANGED_REQUESTED, desc);
1098 le->irq = gpiod_to_irq(desc);
1104 if (eflags & GPIOEVENT_REQUEST_RISING_EDGE)
1105 irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
1106 IRQF_TRIGGER_FALLING : IRQF_TRIGGER_RISING;
1107 if (eflags & GPIOEVENT_REQUEST_FALLING_EDGE)
1108 irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
1109 IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING;
1110 irqflags |= IRQF_ONESHOT;
1112 INIT_KFIFO(le->events);
1113 init_waitqueue_head(&le->wait);
1115 /* Request a thread to read the events */
1116 ret = request_threaded_irq(le->irq,
1117 lineevent_irq_handler,
1118 lineevent_irq_thread,
1125 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
1131 file = anon_inode_getfile("gpio-event",
1134 O_RDONLY | O_CLOEXEC);
1136 ret = PTR_ERR(file);
1137 goto out_put_unused_fd;
1141 if (copy_to_user(ip, &eventreq, sizeof(eventreq))) {
1143 * fput() will trigger the release() callback, so do not go onto
1144 * the regular error cleanup path here.
1151 fd_install(fd, file);
1158 free_irq(le->irq, le);
1160 gpiod_free(le->desc);
1165 put_device(&gdev->dev);
1169 static void gpio_desc_to_lineinfo(struct gpio_desc *desc,
1170 struct gpioline_info *info)
1172 struct gpio_chip *gc = desc->gdev->chip;
1173 bool ok_for_pinctrl;
1174 unsigned long flags;
1177 * This function takes a mutex so we must check this before taking
1180 * FIXME: find a non-racy way to retrieve this information. Maybe a
1181 * lock common to both frameworks?
1184 pinctrl_gpio_can_use_line(gc->base + info->line_offset);
1186 spin_lock_irqsave(&gpio_lock, flags);
1189 strncpy(info->name, desc->name, sizeof(info->name));
1190 info->name[sizeof(info->name) - 1] = '\0';
1192 info->name[0] = '\0';
1196 strncpy(info->consumer, desc->label, sizeof(info->consumer));
1197 info->consumer[sizeof(info->consumer) - 1] = '\0';
1199 info->consumer[0] = '\0';
1203 * Userspace only need to know that the kernel is using this GPIO so
1207 if (test_bit(FLAG_REQUESTED, &desc->flags) ||
1208 test_bit(FLAG_IS_HOGGED, &desc->flags) ||
1209 test_bit(FLAG_USED_AS_IRQ, &desc->flags) ||
1210 test_bit(FLAG_EXPORT, &desc->flags) ||
1211 test_bit(FLAG_SYSFS, &desc->flags) ||
1213 info->flags |= GPIOLINE_FLAG_KERNEL;
1214 if (test_bit(FLAG_IS_OUT, &desc->flags))
1215 info->flags |= GPIOLINE_FLAG_IS_OUT;
1216 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
1217 info->flags |= GPIOLINE_FLAG_ACTIVE_LOW;
1218 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
1219 info->flags |= (GPIOLINE_FLAG_OPEN_DRAIN |
1220 GPIOLINE_FLAG_IS_OUT);
1221 if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
1222 info->flags |= (GPIOLINE_FLAG_OPEN_SOURCE |
1223 GPIOLINE_FLAG_IS_OUT);
1224 if (test_bit(FLAG_BIAS_DISABLE, &desc->flags))
1225 info->flags |= GPIOLINE_FLAG_BIAS_DISABLE;
1226 if (test_bit(FLAG_PULL_DOWN, &desc->flags))
1227 info->flags |= GPIOLINE_FLAG_BIAS_PULL_DOWN;
1228 if (test_bit(FLAG_PULL_UP, &desc->flags))
1229 info->flags |= GPIOLINE_FLAG_BIAS_PULL_UP;
1231 spin_unlock_irqrestore(&gpio_lock, flags);
1234 struct gpio_chardev_data {
1235 struct gpio_device *gdev;
1236 wait_queue_head_t wait;
1237 DECLARE_KFIFO(events, struct gpioline_info_changed, 32);
1238 struct notifier_block lineinfo_changed_nb;
1239 unsigned long *watched_lines;
1243 * gpio_ioctl() - ioctl handler for the GPIO chardev
1245 static long gpio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1247 struct gpio_chardev_data *priv = filp->private_data;
1248 struct gpio_device *gdev = priv->gdev;
1249 struct gpio_chip *gc = gdev->chip;
1250 void __user *ip = (void __user *)arg;
1251 struct gpio_desc *desc;
1255 /* We fail any subsequent ioctl():s when the chip is gone */
1259 /* Fill in the struct and pass to userspace */
1260 if (cmd == GPIO_GET_CHIPINFO_IOCTL) {
1261 struct gpiochip_info chipinfo;
1263 memset(&chipinfo, 0, sizeof(chipinfo));
1265 strncpy(chipinfo.name, dev_name(&gdev->dev),
1266 sizeof(chipinfo.name));
1267 chipinfo.name[sizeof(chipinfo.name)-1] = '\0';
1268 strncpy(chipinfo.label, gdev->label,
1269 sizeof(chipinfo.label));
1270 chipinfo.label[sizeof(chipinfo.label)-1] = '\0';
1271 chipinfo.lines = gdev->ngpio;
1272 if (copy_to_user(ip, &chipinfo, sizeof(chipinfo)))
1275 } else if (cmd == GPIO_GET_LINEINFO_IOCTL) {
1276 struct gpioline_info lineinfo;
1278 if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
1281 desc = gpiochip_get_desc(gc, lineinfo.line_offset);
1283 return PTR_ERR(desc);
1285 hwgpio = gpio_chip_hwgpio(desc);
1287 gpio_desc_to_lineinfo(desc, &lineinfo);
1289 if (copy_to_user(ip, &lineinfo, sizeof(lineinfo)))
1292 } else if (cmd == GPIO_GET_LINEHANDLE_IOCTL) {
1293 return linehandle_create(gdev, ip);
1294 } else if (cmd == GPIO_GET_LINEEVENT_IOCTL) {
1295 return lineevent_create(gdev, ip);
1296 } else if (cmd == GPIO_GET_LINEINFO_WATCH_IOCTL) {
1297 struct gpioline_info lineinfo;
1299 if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
1302 desc = gpiochip_get_desc(gc, lineinfo.line_offset);
1304 return PTR_ERR(desc);
1306 hwgpio = gpio_chip_hwgpio(desc);
1308 if (test_bit(hwgpio, priv->watched_lines))
1311 gpio_desc_to_lineinfo(desc, &lineinfo);
1313 if (copy_to_user(ip, &lineinfo, sizeof(lineinfo)))
1316 set_bit(hwgpio, priv->watched_lines);
1318 } else if (cmd == GPIO_GET_LINEINFO_UNWATCH_IOCTL) {
1319 if (copy_from_user(&offset, ip, sizeof(offset)))
1322 desc = gpiochip_get_desc(gc, offset);
1324 return PTR_ERR(desc);
1326 hwgpio = gpio_chip_hwgpio(desc);
1328 if (!test_bit(hwgpio, priv->watched_lines))
1331 clear_bit(hwgpio, priv->watched_lines);
1337 #ifdef CONFIG_COMPAT
1338 static long gpio_ioctl_compat(struct file *filp, unsigned int cmd,
1341 return gpio_ioctl(filp, cmd, (unsigned long)compat_ptr(arg));
1345 static struct gpio_chardev_data *
1346 to_gpio_chardev_data(struct notifier_block *nb)
1348 return container_of(nb, struct gpio_chardev_data, lineinfo_changed_nb);
1351 static int lineinfo_changed_notify(struct notifier_block *nb,
1352 unsigned long action, void *data)
1354 struct gpio_chardev_data *priv = to_gpio_chardev_data(nb);
1355 struct gpioline_info_changed chg;
1356 struct gpio_desc *desc = data;
1359 if (!test_bit(gpio_chip_hwgpio(desc), priv->watched_lines))
1362 memset(&chg, 0, sizeof(chg));
1363 chg.info.line_offset = gpio_chip_hwgpio(desc);
1364 chg.event_type = action;
1365 chg.timestamp = ktime_get_ns();
1366 gpio_desc_to_lineinfo(desc, &chg.info);
1368 ret = kfifo_in_spinlocked(&priv->events, &chg, 1, &priv->wait.lock);
1370 wake_up_poll(&priv->wait, EPOLLIN);
1372 pr_debug_ratelimited("lineinfo event FIFO is full - event dropped\n");
1377 static __poll_t lineinfo_watch_poll(struct file *filep,
1378 struct poll_table_struct *pollt)
1380 struct gpio_chardev_data *priv = filep->private_data;
1381 __poll_t events = 0;
1383 poll_wait(filep, &priv->wait, pollt);
1385 if (!kfifo_is_empty_spinlocked_noirqsave(&priv->events,
1387 events = EPOLLIN | EPOLLRDNORM;
1392 static ssize_t lineinfo_watch_read(struct file *filep, char __user *buf,
1393 size_t count, loff_t *off)
1395 struct gpio_chardev_data *priv = filep->private_data;
1396 struct gpioline_info_changed event;
1397 ssize_t bytes_read = 0;
1400 if (count < sizeof(event))
1404 spin_lock(&priv->wait.lock);
1405 if (kfifo_is_empty(&priv->events)) {
1407 spin_unlock(&priv->wait.lock);
1411 if (filep->f_flags & O_NONBLOCK) {
1412 spin_unlock(&priv->wait.lock);
1416 ret = wait_event_interruptible_locked(priv->wait,
1417 !kfifo_is_empty(&priv->events));
1419 spin_unlock(&priv->wait.lock);
1424 ret = kfifo_out(&priv->events, &event, 1);
1425 spin_unlock(&priv->wait.lock);
1429 /* We should never get here. See lineevent_read(). */
1432 if (copy_to_user(buf + bytes_read, &event, sizeof(event)))
1434 bytes_read += sizeof(event);
1435 } while (count >= bytes_read + sizeof(event));
1441 * gpio_chrdev_open() - open the chardev for ioctl operations
1442 * @inode: inode for this chardev
1443 * @filp: file struct for storing private data
1444 * Returns 0 on success
1446 static int gpio_chrdev_open(struct inode *inode, struct file *filp)
1448 struct gpio_device *gdev = container_of(inode->i_cdev,
1449 struct gpio_device, chrdev);
1450 struct gpio_chardev_data *priv;
1453 /* Fail on open if the backing gpiochip is gone */
1457 priv = kzalloc(sizeof(*priv), GFP_KERNEL);
1461 priv->watched_lines = bitmap_zalloc(gdev->chip->ngpio, GFP_KERNEL);
1462 if (!priv->watched_lines)
1465 init_waitqueue_head(&priv->wait);
1466 INIT_KFIFO(priv->events);
1469 priv->lineinfo_changed_nb.notifier_call = lineinfo_changed_notify;
1470 ret = atomic_notifier_chain_register(&gdev->notifier,
1471 &priv->lineinfo_changed_nb);
1473 goto out_free_bitmap;
1475 get_device(&gdev->dev);
1476 filp->private_data = priv;
1478 ret = nonseekable_open(inode, filp);
1480 goto out_unregister_notifier;
1484 out_unregister_notifier:
1485 atomic_notifier_chain_unregister(&gdev->notifier,
1486 &priv->lineinfo_changed_nb);
1488 bitmap_free(priv->watched_lines);
1495 * gpio_chrdev_release() - close chardev after ioctl operations
1496 * @inode: inode for this chardev
1497 * @filp: file struct for storing private data
1498 * Returns 0 on success
1500 static int gpio_chrdev_release(struct inode *inode, struct file *filp)
1502 struct gpio_chardev_data *priv = filp->private_data;
1503 struct gpio_device *gdev = priv->gdev;
1505 bitmap_free(priv->watched_lines);
1506 atomic_notifier_chain_unregister(&gdev->notifier,
1507 &priv->lineinfo_changed_nb);
1508 put_device(&gdev->dev);
1514 static const struct file_operations gpio_fileops = {
1515 .release = gpio_chrdev_release,
1516 .open = gpio_chrdev_open,
1517 .poll = lineinfo_watch_poll,
1518 .read = lineinfo_watch_read,
1519 .owner = THIS_MODULE,
1520 .llseek = no_llseek,
1521 .unlocked_ioctl = gpio_ioctl,
1522 #ifdef CONFIG_COMPAT
1523 .compat_ioctl = gpio_ioctl_compat,
1527 static void gpiodevice_release(struct device *dev)
1529 struct gpio_device *gdev = dev_get_drvdata(dev);
1531 list_del(&gdev->list);
1532 ida_simple_remove(&gpio_ida, gdev->id);
1533 kfree_const(gdev->label);
1538 static int gpiochip_setup_dev(struct gpio_device *gdev)
1542 cdev_init(&gdev->chrdev, &gpio_fileops);
1543 gdev->chrdev.owner = THIS_MODULE;
1544 gdev->dev.devt = MKDEV(MAJOR(gpio_devt), gdev->id);
1546 ret = cdev_device_add(&gdev->chrdev, &gdev->dev);
1550 chip_dbg(gdev->chip, "added GPIO chardev (%d:%d)\n",
1551 MAJOR(gpio_devt), gdev->id);
1553 ret = gpiochip_sysfs_register(gdev);
1555 goto err_remove_device;
1557 /* From this point, the .release() function cleans up gpio_device */
1558 gdev->dev.release = gpiodevice_release;
1559 dev_dbg(&gdev->dev, "registered GPIOs %d to %d on %s\n", gdev->base,
1560 gdev->base + gdev->ngpio - 1, gdev->chip->label ? : "generic");
1565 cdev_device_del(&gdev->chrdev, &gdev->dev);
1569 static void gpiochip_machine_hog(struct gpio_chip *gc, struct gpiod_hog *hog)
1571 struct gpio_desc *desc;
1574 desc = gpiochip_get_desc(gc, hog->chip_hwnum);
1576 chip_err(gc, "%s: unable to get GPIO desc: %ld\n", __func__,
1581 if (test_bit(FLAG_IS_HOGGED, &desc->flags))
1584 rv = gpiod_hog(desc, hog->line_name, hog->lflags, hog->dflags);
1586 gpiod_err(desc, "%s: unable to hog GPIO line (%s:%u): %d\n",
1587 __func__, gc->label, hog->chip_hwnum, rv);
1590 static void machine_gpiochip_add(struct gpio_chip *gc)
1592 struct gpiod_hog *hog;
1594 mutex_lock(&gpio_machine_hogs_mutex);
1596 list_for_each_entry(hog, &gpio_machine_hogs, list) {
1597 if (!strcmp(gc->label, hog->chip_label))
1598 gpiochip_machine_hog(gc, hog);
1601 mutex_unlock(&gpio_machine_hogs_mutex);
1604 static void gpiochip_setup_devs(void)
1606 struct gpio_device *gdev;
1609 list_for_each_entry(gdev, &gpio_devices, list) {
1610 ret = gpiochip_setup_dev(gdev);
1613 "Failed to initialize gpio device (%d)\n", ret);
1617 int gpiochip_add_data_with_key(struct gpio_chip *gc, void *data,
1618 struct lock_class_key *lock_key,
1619 struct lock_class_key *request_key)
1621 unsigned long flags;
1624 int base = gc->base;
1625 struct gpio_device *gdev;
1628 * First: allocate and populate the internal stat container, and
1629 * set up the struct device.
1631 gdev = kzalloc(sizeof(*gdev), GFP_KERNEL);
1634 gdev->dev.bus = &gpio_bus_type;
1638 gdev->dev.parent = gc->parent;
1639 gdev->dev.of_node = gc->parent->of_node;
1642 #ifdef CONFIG_OF_GPIO
1643 /* If the gpiochip has an assigned OF node this takes precedence */
1645 gdev->dev.of_node = gc->of_node;
1647 gc->of_node = gdev->dev.of_node;
1650 gdev->id = ida_simple_get(&gpio_ida, 0, 0, GFP_KERNEL);
1655 dev_set_name(&gdev->dev, GPIOCHIP_NAME "%d", gdev->id);
1656 device_initialize(&gdev->dev);
1657 dev_set_drvdata(&gdev->dev, gdev);
1658 if (gc->parent && gc->parent->driver)
1659 gdev->owner = gc->parent->driver->owner;
1661 /* TODO: remove chip->owner */
1662 gdev->owner = gc->owner;
1664 gdev->owner = THIS_MODULE;
1666 gdev->descs = kcalloc(gc->ngpio, sizeof(gdev->descs[0]), GFP_KERNEL);
1672 if (gc->ngpio == 0) {
1673 chip_err(gc, "tried to insert a GPIO chip with zero lines\n");
1675 goto err_free_descs;
1678 if (gc->ngpio > FASTPATH_NGPIO)
1679 chip_warn(gc, "line cnt %u is greater than fast path cnt %u\n",
1680 gc->ngpio, FASTPATH_NGPIO);
1682 gdev->label = kstrdup_const(gc->label ?: "unknown", GFP_KERNEL);
1685 goto err_free_descs;
1688 gdev->ngpio = gc->ngpio;
1691 spin_lock_irqsave(&gpio_lock, flags);
1694 * TODO: this allocates a Linux GPIO number base in the global
1695 * GPIO numberspace for this chip. In the long run we want to
1696 * get *rid* of this numberspace and use only descriptors, but
1697 * it may be a pipe dream. It will not happen before we get rid
1698 * of the sysfs interface anyways.
1701 base = gpiochip_find_base(gc->ngpio);
1704 spin_unlock_irqrestore(&gpio_lock, flags);
1705 goto err_free_label;
1708 * TODO: it should not be necessary to reflect the assigned
1709 * base outside of the GPIO subsystem. Go over drivers and
1710 * see if anyone makes use of this, else drop this and assign
1717 ret = gpiodev_add_to_list(gdev);
1719 spin_unlock_irqrestore(&gpio_lock, flags);
1720 goto err_free_label;
1723 for (i = 0; i < gc->ngpio; i++)
1724 gdev->descs[i].gdev = gdev;
1726 spin_unlock_irqrestore(&gpio_lock, flags);
1728 ATOMIC_INIT_NOTIFIER_HEAD(&gdev->notifier);
1730 #ifdef CONFIG_PINCTRL
1731 INIT_LIST_HEAD(&gdev->pin_ranges);
1734 ret = gpiochip_set_desc_names(gc);
1736 goto err_remove_from_list;
1738 ret = gpiochip_alloc_valid_mask(gc);
1740 goto err_remove_from_list;
1742 ret = of_gpiochip_add(gc);
1744 goto err_free_gpiochip_mask;
1746 ret = gpiochip_init_valid_mask(gc);
1748 goto err_remove_of_chip;
1750 for (i = 0; i < gc->ngpio; i++) {
1751 struct gpio_desc *desc = &gdev->descs[i];
1753 if (gc->get_direction && gpiochip_line_is_valid(gc, i)) {
1754 assign_bit(FLAG_IS_OUT,
1755 &desc->flags, !gc->get_direction(gc, i));
1757 assign_bit(FLAG_IS_OUT,
1758 &desc->flags, !gc->direction_input);
1762 ret = gpiochip_add_pin_ranges(gc);
1764 goto err_remove_of_chip;
1766 acpi_gpiochip_add(gc);
1768 machine_gpiochip_add(gc);
1770 ret = gpiochip_irqchip_init_valid_mask(gc);
1772 goto err_remove_acpi_chip;
1774 ret = gpiochip_irqchip_init_hw(gc);
1776 goto err_remove_acpi_chip;
1778 ret = gpiochip_add_irqchip(gc, lock_key, request_key);
1780 goto err_remove_irqchip_mask;
1783 * By first adding the chardev, and then adding the device,
1784 * we get a device node entry in sysfs under
1785 * /sys/bus/gpio/devices/gpiochipN/dev that can be used for
1786 * coldplug of device nodes and other udev business.
1787 * We can do this only if gpiolib has been initialized.
1788 * Otherwise, defer until later.
1790 if (gpiolib_initialized) {
1791 ret = gpiochip_setup_dev(gdev);
1793 goto err_remove_irqchip;
1798 gpiochip_irqchip_remove(gc);
1799 err_remove_irqchip_mask:
1800 gpiochip_irqchip_free_valid_mask(gc);
1801 err_remove_acpi_chip:
1802 acpi_gpiochip_remove(gc);
1804 gpiochip_free_hogs(gc);
1805 of_gpiochip_remove(gc);
1806 err_free_gpiochip_mask:
1807 gpiochip_remove_pin_ranges(gc);
1808 gpiochip_free_valid_mask(gc);
1809 err_remove_from_list:
1810 spin_lock_irqsave(&gpio_lock, flags);
1811 list_del(&gdev->list);
1812 spin_unlock_irqrestore(&gpio_lock, flags);
1814 kfree_const(gdev->label);
1818 ida_simple_remove(&gpio_ida, gdev->id);
1820 /* failures here can mean systems won't boot... */
1821 pr_err("%s: GPIOs %d..%d (%s) failed to register, %d\n", __func__,
1822 gdev->base, gdev->base + gdev->ngpio - 1,
1823 gc->label ? : "generic", ret);
1827 EXPORT_SYMBOL_GPL(gpiochip_add_data_with_key);
1830 * gpiochip_get_data() - get per-subdriver data for the chip
1834 * The per-subdriver data for the chip.
1836 void *gpiochip_get_data(struct gpio_chip *gc)
1838 return gc->gpiodev->data;
1840 EXPORT_SYMBOL_GPL(gpiochip_get_data);
1843 * gpiochip_remove() - unregister a gpio_chip
1844 * @gc: the chip to unregister
1846 * A gpio_chip with any GPIOs still requested may not be removed.
1848 void gpiochip_remove(struct gpio_chip *gc)
1850 struct gpio_device *gdev = gc->gpiodev;
1851 unsigned long flags;
1854 /* FIXME: should the legacy sysfs handling be moved to gpio_device? */
1855 gpiochip_sysfs_unregister(gdev);
1856 gpiochip_free_hogs(gc);
1857 /* Numb the device, cancelling all outstanding operations */
1859 gpiochip_irqchip_remove(gc);
1860 acpi_gpiochip_remove(gc);
1861 of_gpiochip_remove(gc);
1862 gpiochip_remove_pin_ranges(gc);
1863 gpiochip_free_valid_mask(gc);
1865 * We accept no more calls into the driver from this point, so
1866 * NULL the driver data pointer
1870 spin_lock_irqsave(&gpio_lock, flags);
1871 for (i = 0; i < gdev->ngpio; i++) {
1872 if (gpiochip_is_requested(gc, i))
1875 spin_unlock_irqrestore(&gpio_lock, flags);
1877 if (i != gdev->ngpio)
1878 dev_crit(&gdev->dev,
1879 "REMOVING GPIOCHIP WITH GPIOS STILL REQUESTED\n");
1882 * The gpiochip side puts its use of the device to rest here:
1883 * if there are no userspace clients, the chardev and device will
1884 * be removed, else it will be dangling until the last user is
1887 cdev_device_del(&gdev->chrdev, &gdev->dev);
1888 put_device(&gdev->dev);
1890 EXPORT_SYMBOL_GPL(gpiochip_remove);
1893 * gpiochip_find() - iterator for locating a specific gpio_chip
1894 * @data: data to pass to match function
1895 * @match: Callback function to check gpio_chip
1897 * Similar to bus_find_device. It returns a reference to a gpio_chip as
1898 * determined by a user supplied @match callback. The callback should return
1899 * 0 if the device doesn't match and non-zero if it does. If the callback is
1900 * non-zero, this function will return to the caller and not iterate over any
1903 struct gpio_chip *gpiochip_find(void *data,
1904 int (*match)(struct gpio_chip *gc,
1907 struct gpio_device *gdev;
1908 struct gpio_chip *gc = NULL;
1909 unsigned long flags;
1911 spin_lock_irqsave(&gpio_lock, flags);
1912 list_for_each_entry(gdev, &gpio_devices, list)
1913 if (gdev->chip && match(gdev->chip, data)) {
1918 spin_unlock_irqrestore(&gpio_lock, flags);
1922 EXPORT_SYMBOL_GPL(gpiochip_find);
1924 static int gpiochip_match_name(struct gpio_chip *gc, void *data)
1926 const char *name = data;
1928 return !strcmp(gc->label, name);
1931 static struct gpio_chip *find_chip_by_name(const char *name)
1933 return gpiochip_find((void *)name, gpiochip_match_name);
1936 #ifdef CONFIG_GPIOLIB_IRQCHIP
1939 * The following is irqchip helper code for gpiochips.
1942 static int gpiochip_irqchip_init_hw(struct gpio_chip *gc)
1944 struct gpio_irq_chip *girq = &gc->irq;
1949 return girq->init_hw(gc);
1952 static int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gc)
1954 struct gpio_irq_chip *girq = &gc->irq;
1956 if (!girq->init_valid_mask)
1959 girq->valid_mask = gpiochip_allocate_mask(gc);
1960 if (!girq->valid_mask)
1963 girq->init_valid_mask(gc, girq->valid_mask, gc->ngpio);
1968 static void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gc)
1970 bitmap_free(gc->irq.valid_mask);
1971 gc->irq.valid_mask = NULL;
1974 bool gpiochip_irqchip_irq_valid(const struct gpio_chip *gc,
1975 unsigned int offset)
1977 if (!gpiochip_line_is_valid(gc, offset))
1979 /* No mask means all valid */
1980 if (likely(!gc->irq.valid_mask))
1982 return test_bit(offset, gc->irq.valid_mask);
1984 EXPORT_SYMBOL_GPL(gpiochip_irqchip_irq_valid);
1987 * gpiochip_set_cascaded_irqchip() - connects a cascaded irqchip to a gpiochip
1988 * @gc: the gpiochip to set the irqchip chain to
1989 * @parent_irq: the irq number corresponding to the parent IRQ for this
1991 * @parent_handler: the parent interrupt handler for the accumulated IRQ
1992 * coming out of the gpiochip. If the interrupt is nested rather than
1993 * cascaded, pass NULL in this handler argument
1995 static void gpiochip_set_cascaded_irqchip(struct gpio_chip *gc,
1996 unsigned int parent_irq,
1997 irq_flow_handler_t parent_handler)
1999 struct gpio_irq_chip *girq = &gc->irq;
2000 struct device *dev = &gc->gpiodev->dev;
2002 if (!girq->domain) {
2003 chip_err(gc, "called %s before setting up irqchip\n",
2008 if (parent_handler) {
2009 if (gc->can_sleep) {
2011 "you cannot have chained interrupts on a chip that may sleep\n");
2014 girq->parents = devm_kcalloc(dev, 1,
2015 sizeof(*girq->parents),
2017 if (!girq->parents) {
2018 chip_err(gc, "out of memory allocating parent IRQ\n");
2021 girq->parents[0] = parent_irq;
2022 girq->num_parents = 1;
2024 * The parent irqchip is already using the chip_data for this
2025 * irqchip, so our callbacks simply use the handler_data.
2027 irq_set_chained_handler_and_data(parent_irq, parent_handler,
2033 * gpiochip_set_nested_irqchip() - connects a nested irqchip to a gpiochip
2034 * @gc: the gpiochip to set the irqchip nested handler to
2035 * @irqchip: the irqchip to nest to the gpiochip
2036 * @parent_irq: the irq number corresponding to the parent IRQ for this
2039 void gpiochip_set_nested_irqchip(struct gpio_chip *gc,
2040 struct irq_chip *irqchip,
2041 unsigned int parent_irq)
2043 gpiochip_set_cascaded_irqchip(gc, parent_irq, NULL);
2045 EXPORT_SYMBOL_GPL(gpiochip_set_nested_irqchip);
2047 #ifdef CONFIG_IRQ_DOMAIN_HIERARCHY
2050 * gpiochip_set_hierarchical_irqchip() - connects a hierarchical irqchip
2052 * @gc: the gpiochip to set the irqchip hierarchical handler to
2053 * @irqchip: the irqchip to handle this level of the hierarchy, the interrupt
2054 * will then percolate up to the parent
2056 static void gpiochip_set_hierarchical_irqchip(struct gpio_chip *gc,
2057 struct irq_chip *irqchip)
2059 /* DT will deal with mapping each IRQ as we go along */
2060 if (is_of_node(gc->irq.fwnode))
2064 * This is for legacy and boardfile "irqchip" fwnodes: allocate
2065 * irqs upfront instead of dynamically since we don't have the
2066 * dynamic type of allocation that hardware description languages
2067 * provide. Once all GPIO drivers using board files are gone from
2068 * the kernel we can delete this code, but for a transitional period
2069 * it is necessary to keep this around.
2071 if (is_fwnode_irqchip(gc->irq.fwnode)) {
2075 for (i = 0; i < gc->ngpio; i++) {
2076 struct irq_fwspec fwspec;
2077 unsigned int parent_hwirq;
2078 unsigned int parent_type;
2079 struct gpio_irq_chip *girq = &gc->irq;
2082 * We call the child to parent translation function
2083 * only to check if the child IRQ is valid or not.
2084 * Just pick the rising edge type here as that is what
2085 * we likely need to support.
2087 ret = girq->child_to_parent_hwirq(gc, i,
2088 IRQ_TYPE_EDGE_RISING,
2092 chip_err(gc, "skip set-up on hwirq %d\n",
2097 fwspec.fwnode = gc->irq.fwnode;
2098 /* This is the hwirq for the GPIO line side of things */
2099 fwspec.param[0] = girq->child_offset_to_irq(gc, i);
2100 /* Just pick something */
2101 fwspec.param[1] = IRQ_TYPE_EDGE_RISING;
2102 fwspec.param_count = 2;
2103 ret = __irq_domain_alloc_irqs(gc->irq.domain,
2104 /* just pick something */
2113 "can not allocate irq for GPIO line %d parent hwirq %d in hierarchy domain: %d\n",
2120 chip_err(gc, "%s unknown fwnode type proceed anyway\n", __func__);
2125 static int gpiochip_hierarchy_irq_domain_translate(struct irq_domain *d,
2126 struct irq_fwspec *fwspec,
2127 unsigned long *hwirq,
2130 /* We support standard DT translation */
2131 if (is_of_node(fwspec->fwnode) && fwspec->param_count == 2) {
2132 return irq_domain_translate_twocell(d, fwspec, hwirq, type);
2135 /* This is for board files and others not using DT */
2136 if (is_fwnode_irqchip(fwspec->fwnode)) {
2139 ret = irq_domain_translate_twocell(d, fwspec, hwirq, type);
2142 WARN_ON(*type == IRQ_TYPE_NONE);
2148 static int gpiochip_hierarchy_irq_domain_alloc(struct irq_domain *d,
2150 unsigned int nr_irqs,
2153 struct gpio_chip *gc = d->host_data;
2154 irq_hw_number_t hwirq;
2155 unsigned int type = IRQ_TYPE_NONE;
2156 struct irq_fwspec *fwspec = data;
2158 unsigned int parent_hwirq;
2159 unsigned int parent_type;
2160 struct gpio_irq_chip *girq = &gc->irq;
2164 * The nr_irqs parameter is always one except for PCI multi-MSI
2165 * so this should not happen.
2167 WARN_ON(nr_irqs != 1);
2169 ret = gc->irq.child_irq_domain_ops.translate(d, fwspec, &hwirq, &type);
2173 chip_dbg(gc, "allocate IRQ %d, hwirq %lu\n", irq, hwirq);
2175 ret = girq->child_to_parent_hwirq(gc, hwirq, type,
2176 &parent_hwirq, &parent_type);
2178 chip_err(gc, "can't look up hwirq %lu\n", hwirq);
2181 chip_dbg(gc, "found parent hwirq %u\n", parent_hwirq);
2184 * We set handle_bad_irq because the .set_type() should
2185 * always be invoked and set the right type of handler.
2187 irq_domain_set_info(d,
2196 /* This parent only handles asserted level IRQs */
2197 parent_arg = girq->populate_parent_alloc_arg(gc, parent_hwirq, parent_type);
2201 chip_dbg(gc, "alloc_irqs_parent for %d parent hwirq %d\n",
2203 irq_set_lockdep_class(irq, gc->irq.lock_key, gc->irq.request_key);
2204 ret = irq_domain_alloc_irqs_parent(d, irq, 1, parent_arg);
2206 * If the parent irqdomain is msi, the interrupts have already
2207 * been allocated, so the EEXIST is good.
2209 if (irq_domain_is_msi(d->parent) && (ret == -EEXIST))
2213 "failed to allocate parent hwirq %d for hwirq %lu\n",
2214 parent_hwirq, hwirq);
2220 static unsigned int gpiochip_child_offset_to_irq_noop(struct gpio_chip *gc,
2221 unsigned int offset)
2226 static void gpiochip_hierarchy_setup_domain_ops(struct irq_domain_ops *ops)
2228 ops->activate = gpiochip_irq_domain_activate;
2229 ops->deactivate = gpiochip_irq_domain_deactivate;
2230 ops->alloc = gpiochip_hierarchy_irq_domain_alloc;
2231 ops->free = irq_domain_free_irqs_common;
2234 * We only allow overriding the translate() function for
2235 * hierarchical chips, and this should only be done if the user
2236 * really need something other than 1:1 translation.
2238 if (!ops->translate)
2239 ops->translate = gpiochip_hierarchy_irq_domain_translate;
2242 static int gpiochip_hierarchy_add_domain(struct gpio_chip *gc)
2244 if (!gc->irq.child_to_parent_hwirq ||
2246 chip_err(gc, "missing irqdomain vital data\n");
2250 if (!gc->irq.child_offset_to_irq)
2251 gc->irq.child_offset_to_irq = gpiochip_child_offset_to_irq_noop;
2253 if (!gc->irq.populate_parent_alloc_arg)
2254 gc->irq.populate_parent_alloc_arg =
2255 gpiochip_populate_parent_fwspec_twocell;
2257 gpiochip_hierarchy_setup_domain_ops(&gc->irq.child_irq_domain_ops);
2259 gc->irq.domain = irq_domain_create_hierarchy(
2260 gc->irq.parent_domain,
2264 &gc->irq.child_irq_domain_ops,
2267 if (!gc->irq.domain)
2270 gpiochip_set_hierarchical_irqchip(gc, gc->irq.chip);
2275 static bool gpiochip_hierarchy_is_hierarchical(struct gpio_chip *gc)
2277 return !!gc->irq.parent_domain;
2280 void *gpiochip_populate_parent_fwspec_twocell(struct gpio_chip *gc,
2281 unsigned int parent_hwirq,
2282 unsigned int parent_type)
2284 struct irq_fwspec *fwspec;
2286 fwspec = kmalloc(sizeof(*fwspec), GFP_KERNEL);
2290 fwspec->fwnode = gc->irq.parent_domain->fwnode;
2291 fwspec->param_count = 2;
2292 fwspec->param[0] = parent_hwirq;
2293 fwspec->param[1] = parent_type;
2297 EXPORT_SYMBOL_GPL(gpiochip_populate_parent_fwspec_twocell);
2299 void *gpiochip_populate_parent_fwspec_fourcell(struct gpio_chip *gc,
2300 unsigned int parent_hwirq,
2301 unsigned int parent_type)
2303 struct irq_fwspec *fwspec;
2305 fwspec = kmalloc(sizeof(*fwspec), GFP_KERNEL);
2309 fwspec->fwnode = gc->irq.parent_domain->fwnode;
2310 fwspec->param_count = 4;
2311 fwspec->param[0] = 0;
2312 fwspec->param[1] = parent_hwirq;
2313 fwspec->param[2] = 0;
2314 fwspec->param[3] = parent_type;
2318 EXPORT_SYMBOL_GPL(gpiochip_populate_parent_fwspec_fourcell);
2322 static int gpiochip_hierarchy_add_domain(struct gpio_chip *gc)
2327 static bool gpiochip_hierarchy_is_hierarchical(struct gpio_chip *gc)
2332 #endif /* CONFIG_IRQ_DOMAIN_HIERARCHY */
2335 * gpiochip_irq_map() - maps an IRQ into a GPIO irqchip
2336 * @d: the irqdomain used by this irqchip
2337 * @irq: the global irq number used by this GPIO irqchip irq
2338 * @hwirq: the local IRQ/GPIO line offset on this gpiochip
2340 * This function will set up the mapping for a certain IRQ line on a
2341 * gpiochip by assigning the gpiochip as chip data, and using the irqchip
2342 * stored inside the gpiochip.
2344 int gpiochip_irq_map(struct irq_domain *d, unsigned int irq,
2345 irq_hw_number_t hwirq)
2347 struct gpio_chip *gc = d->host_data;
2350 if (!gpiochip_irqchip_irq_valid(gc, hwirq))
2353 irq_set_chip_data(irq, gc);
2355 * This lock class tells lockdep that GPIO irqs are in a different
2356 * category than their parents, so it won't report false recursion.
2358 irq_set_lockdep_class(irq, gc->irq.lock_key, gc->irq.request_key);
2359 irq_set_chip_and_handler(irq, gc->irq.chip, gc->irq.handler);
2360 /* Chips that use nested thread handlers have them marked */
2361 if (gc->irq.threaded)
2362 irq_set_nested_thread(irq, 1);
2363 irq_set_noprobe(irq);
2365 if (gc->irq.num_parents == 1)
2366 ret = irq_set_parent(irq, gc->irq.parents[0]);
2367 else if (gc->irq.map)
2368 ret = irq_set_parent(irq, gc->irq.map[hwirq]);
2374 * No set-up of the hardware will happen if IRQ_TYPE_NONE
2375 * is passed as default type.
2377 if (gc->irq.default_type != IRQ_TYPE_NONE)
2378 irq_set_irq_type(irq, gc->irq.default_type);
2382 EXPORT_SYMBOL_GPL(gpiochip_irq_map);
2384 void gpiochip_irq_unmap(struct irq_domain *d, unsigned int irq)
2386 struct gpio_chip *gc = d->host_data;
2388 if (gc->irq.threaded)
2389 irq_set_nested_thread(irq, 0);
2390 irq_set_chip_and_handler(irq, NULL, NULL);
2391 irq_set_chip_data(irq, NULL);
2393 EXPORT_SYMBOL_GPL(gpiochip_irq_unmap);
2395 static const struct irq_domain_ops gpiochip_domain_ops = {
2396 .map = gpiochip_irq_map,
2397 .unmap = gpiochip_irq_unmap,
2398 /* Virtually all GPIO irqchips are twocell:ed */
2399 .xlate = irq_domain_xlate_twocell,
2403 * TODO: move these activate/deactivate in under the hierarchicial
2404 * irqchip implementation as static once SPMI and SSBI (all external
2405 * users) are phased over.
2408 * gpiochip_irq_domain_activate() - Lock a GPIO to be used as an IRQ
2409 * @domain: The IRQ domain used by this IRQ chip
2410 * @data: Outermost irq_data associated with the IRQ
2411 * @reserve: If set, only reserve an interrupt vector instead of assigning one
2413 * This function is a wrapper that calls gpiochip_lock_as_irq() and is to be
2414 * used as the activate function for the &struct irq_domain_ops. The host_data
2415 * for the IRQ domain must be the &struct gpio_chip.
2417 int gpiochip_irq_domain_activate(struct irq_domain *domain,
2418 struct irq_data *data, bool reserve)
2420 struct gpio_chip *gc = domain->host_data;
2422 return gpiochip_lock_as_irq(gc, data->hwirq);
2424 EXPORT_SYMBOL_GPL(gpiochip_irq_domain_activate);
2427 * gpiochip_irq_domain_deactivate() - Unlock a GPIO used as an IRQ
2428 * @domain: The IRQ domain used by this IRQ chip
2429 * @data: Outermost irq_data associated with the IRQ
2431 * This function is a wrapper that will call gpiochip_unlock_as_irq() and is to
2432 * be used as the deactivate function for the &struct irq_domain_ops. The
2433 * host_data for the IRQ domain must be the &struct gpio_chip.
2435 void gpiochip_irq_domain_deactivate(struct irq_domain *domain,
2436 struct irq_data *data)
2438 struct gpio_chip *gc = domain->host_data;
2440 return gpiochip_unlock_as_irq(gc, data->hwirq);
2442 EXPORT_SYMBOL_GPL(gpiochip_irq_domain_deactivate);
2444 static int gpiochip_to_irq(struct gpio_chip *gc, unsigned offset)
2446 struct irq_domain *domain = gc->irq.domain;
2448 if (!gpiochip_irqchip_irq_valid(gc, offset))
2451 #ifdef CONFIG_IRQ_DOMAIN_HIERARCHY
2452 if (irq_domain_is_hierarchy(domain)) {
2453 struct irq_fwspec spec;
2455 spec.fwnode = domain->fwnode;
2456 spec.param_count = 2;
2457 spec.param[0] = gc->irq.child_offset_to_irq(gc, offset);
2458 spec.param[1] = IRQ_TYPE_NONE;
2460 return irq_create_fwspec_mapping(&spec);
2464 return irq_create_mapping(domain, offset);
2467 static int gpiochip_irq_reqres(struct irq_data *d)
2469 struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
2471 return gpiochip_reqres_irq(gc, d->hwirq);
2474 static void gpiochip_irq_relres(struct irq_data *d)
2476 struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
2478 gpiochip_relres_irq(gc, d->hwirq);
2481 static void gpiochip_irq_mask(struct irq_data *d)
2483 struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
2485 if (gc->irq.irq_mask)
2486 gc->irq.irq_mask(d);
2487 gpiochip_disable_irq(gc, d->hwirq);
2490 static void gpiochip_irq_unmask(struct irq_data *d)
2492 struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
2494 gpiochip_enable_irq(gc, d->hwirq);
2495 if (gc->irq.irq_unmask)
2496 gc->irq.irq_unmask(d);
2499 static void gpiochip_irq_enable(struct irq_data *d)
2501 struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
2503 gpiochip_enable_irq(gc, d->hwirq);
2504 gc->irq.irq_enable(d);
2507 static void gpiochip_irq_disable(struct irq_data *d)
2509 struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
2511 gc->irq.irq_disable(d);
2512 gpiochip_disable_irq(gc, d->hwirq);
2515 static void gpiochip_set_irq_hooks(struct gpio_chip *gc)
2517 struct irq_chip *irqchip = gc->irq.chip;
2519 if (!irqchip->irq_request_resources &&
2520 !irqchip->irq_release_resources) {
2521 irqchip->irq_request_resources = gpiochip_irq_reqres;
2522 irqchip->irq_release_resources = gpiochip_irq_relres;
2524 if (WARN_ON(gc->irq.irq_enable))
2526 /* Check if the irqchip already has this hook... */
2527 if (irqchip->irq_enable == gpiochip_irq_enable) {
2529 * ...and if so, give a gentle warning that this is bad
2533 "detected irqchip that is shared with multiple gpiochips: please fix the driver.\n");
2537 if (irqchip->irq_disable) {
2538 gc->irq.irq_disable = irqchip->irq_disable;
2539 irqchip->irq_disable = gpiochip_irq_disable;
2541 gc->irq.irq_mask = irqchip->irq_mask;
2542 irqchip->irq_mask = gpiochip_irq_mask;
2545 if (irqchip->irq_enable) {
2546 gc->irq.irq_enable = irqchip->irq_enable;
2547 irqchip->irq_enable = gpiochip_irq_enable;
2549 gc->irq.irq_unmask = irqchip->irq_unmask;
2550 irqchip->irq_unmask = gpiochip_irq_unmask;
2555 * gpiochip_add_irqchip() - adds an IRQ chip to a GPIO chip
2556 * @gc: the GPIO chip to add the IRQ chip to
2557 * @lock_key: lockdep class for IRQ lock
2558 * @request_key: lockdep class for IRQ request
2560 static int gpiochip_add_irqchip(struct gpio_chip *gc,
2561 struct lock_class_key *lock_key,
2562 struct lock_class_key *request_key)
2564 struct irq_chip *irqchip = gc->irq.chip;
2565 const struct irq_domain_ops *ops = NULL;
2566 struct device_node *np;
2573 if (gc->irq.parent_handler && gc->can_sleep) {
2574 chip_err(gc, "you cannot have chained interrupts on a chip that may sleep\n");
2578 np = gc->gpiodev->dev.of_node;
2579 type = gc->irq.default_type;
2582 * Specifying a default trigger is a terrible idea if DT or ACPI is
2583 * used to configure the interrupts, as you may end up with
2584 * conflicting triggers. Tell the user, and reset to NONE.
2586 if (WARN(np && type != IRQ_TYPE_NONE,
2587 "%s: Ignoring %u default trigger\n", np->full_name, type))
2588 type = IRQ_TYPE_NONE;
2590 if (has_acpi_companion(gc->parent) && type != IRQ_TYPE_NONE) {
2591 acpi_handle_warn(ACPI_HANDLE(gc->parent),
2592 "Ignoring %u default trigger\n", type);
2593 type = IRQ_TYPE_NONE;
2596 gc->to_irq = gpiochip_to_irq;
2597 gc->irq.default_type = type;
2598 gc->irq.lock_key = lock_key;
2599 gc->irq.request_key = request_key;
2601 /* If a parent irqdomain is provided, let's build a hierarchy */
2602 if (gpiochip_hierarchy_is_hierarchical(gc)) {
2603 int ret = gpiochip_hierarchy_add_domain(gc);
2607 /* Some drivers provide custom irqdomain ops */
2608 if (gc->irq.domain_ops)
2609 ops = gc->irq.domain_ops;
2612 ops = &gpiochip_domain_ops;
2613 gc->irq.domain = irq_domain_add_simple(np,
2617 if (!gc->irq.domain)
2621 if (gc->irq.parent_handler) {
2622 void *data = gc->irq.parent_handler_data ?: gc;
2624 for (i = 0; i < gc->irq.num_parents; i++) {
2626 * The parent IRQ chip is already using the chip_data
2627 * for this IRQ chip, so our callbacks simply use the
2630 irq_set_chained_handler_and_data(gc->irq.parents[i],
2631 gc->irq.parent_handler,
2636 gpiochip_set_irq_hooks(gc);
2638 acpi_gpiochip_request_interrupts(gc);
2644 * gpiochip_irqchip_remove() - removes an irqchip added to a gpiochip
2645 * @gc: the gpiochip to remove the irqchip from
2647 * This is called only from gpiochip_remove()
2649 static void gpiochip_irqchip_remove(struct gpio_chip *gc)
2651 struct irq_chip *irqchip = gc->irq.chip;
2652 unsigned int offset;
2654 acpi_gpiochip_free_interrupts(gc);
2656 if (irqchip && gc->irq.parent_handler) {
2657 struct gpio_irq_chip *irq = &gc->irq;
2660 for (i = 0; i < irq->num_parents; i++)
2661 irq_set_chained_handler_and_data(irq->parents[i],
2665 /* Remove all IRQ mappings and delete the domain */
2666 if (gc->irq.domain) {
2669 for (offset = 0; offset < gc->ngpio; offset++) {
2670 if (!gpiochip_irqchip_irq_valid(gc, offset))
2673 irq = irq_find_mapping(gc->irq.domain, offset);
2674 irq_dispose_mapping(irq);
2677 irq_domain_remove(gc->irq.domain);
2681 if (irqchip->irq_request_resources == gpiochip_irq_reqres) {
2682 irqchip->irq_request_resources = NULL;
2683 irqchip->irq_release_resources = NULL;
2685 if (irqchip->irq_enable == gpiochip_irq_enable) {
2686 irqchip->irq_enable = gc->irq.irq_enable;
2687 irqchip->irq_disable = gc->irq.irq_disable;
2690 gc->irq.irq_enable = NULL;
2691 gc->irq.irq_disable = NULL;
2692 gc->irq.chip = NULL;
2694 gpiochip_irqchip_free_valid_mask(gc);
2698 * gpiochip_irqchip_add_key() - adds an irqchip to a gpiochip
2699 * @gc: the gpiochip to add the irqchip to
2700 * @irqchip: the irqchip to add to the gpiochip
2701 * @first_irq: if not dynamically assigned, the base (first) IRQ to
2702 * allocate gpiochip irqs from
2703 * @handler: the irq handler to use (often a predefined irq core function)
2704 * @type: the default type for IRQs on this irqchip, pass IRQ_TYPE_NONE
2705 * to have the core avoid setting up any default type in the hardware.
2706 * @threaded: whether this irqchip uses a nested thread handler
2707 * @lock_key: lockdep class for IRQ lock
2708 * @request_key: lockdep class for IRQ request
2710 * This function closely associates a certain irqchip with a certain
2711 * gpiochip, providing an irq domain to translate the local IRQs to
2712 * global irqs in the gpiolib core, and making sure that the gpiochip
2713 * is passed as chip data to all related functions. Driver callbacks
2714 * need to use gpiochip_get_data() to get their local state containers back
2715 * from the gpiochip passed as chip data. An irqdomain will be stored
2716 * in the gpiochip that shall be used by the driver to handle IRQ number
2717 * translation. The gpiochip will need to be initialized and registered
2718 * before calling this function.
2720 * This function will handle two cell:ed simple IRQs and assumes all
2721 * the pins on the gpiochip can generate a unique IRQ. Everything else
2722 * need to be open coded.
2724 int gpiochip_irqchip_add_key(struct gpio_chip *gc,
2725 struct irq_chip *irqchip,
2726 unsigned int first_irq,
2727 irq_flow_handler_t handler,
2730 struct lock_class_key *lock_key,
2731 struct lock_class_key *request_key)
2733 struct device_node *of_node;
2735 if (!gc || !irqchip)
2739 chip_err(gc, "missing gpiochip .dev parent pointer\n");
2742 gc->irq.threaded = threaded;
2743 of_node = gc->parent->of_node;
2744 #ifdef CONFIG_OF_GPIO
2746 * If the gpiochip has an assigned OF node this takes precedence
2747 * FIXME: get rid of this and use gc->parent->of_node
2751 of_node = gc->of_node;
2754 * Specifying a default trigger is a terrible idea if DT or ACPI is
2755 * used to configure the interrupts, as you may end-up with
2756 * conflicting triggers. Tell the user, and reset to NONE.
2758 if (WARN(of_node && type != IRQ_TYPE_NONE,
2759 "%pOF: Ignoring %d default trigger\n", of_node, type))
2760 type = IRQ_TYPE_NONE;
2761 if (has_acpi_companion(gc->parent) && type != IRQ_TYPE_NONE) {
2762 acpi_handle_warn(ACPI_HANDLE(gc->parent),
2763 "Ignoring %d default trigger\n", type);
2764 type = IRQ_TYPE_NONE;
2767 gc->irq.chip = irqchip;
2768 gc->irq.handler = handler;
2769 gc->irq.default_type = type;
2770 gc->to_irq = gpiochip_to_irq;
2771 gc->irq.lock_key = lock_key;
2772 gc->irq.request_key = request_key;
2773 gc->irq.domain = irq_domain_add_simple(of_node,
2774 gc->ngpio, first_irq,
2775 &gpiochip_domain_ops, gc);
2776 if (!gc->irq.domain) {
2777 gc->irq.chip = NULL;
2781 gpiochip_set_irq_hooks(gc);
2783 acpi_gpiochip_request_interrupts(gc);
2787 EXPORT_SYMBOL_GPL(gpiochip_irqchip_add_key);
2790 * gpiochip_irqchip_add_domain() - adds an irqdomain to a gpiochip
2791 * @gc: the gpiochip to add the irqchip to
2792 * @domain: the irqdomain to add to the gpiochip
2794 * This function adds an IRQ domain to the gpiochip.
2796 int gpiochip_irqchip_add_domain(struct gpio_chip *gc,
2797 struct irq_domain *domain)
2802 gc->to_irq = gpiochip_to_irq;
2803 gc->irq.domain = domain;
2807 EXPORT_SYMBOL_GPL(gpiochip_irqchip_add_domain);
2809 #else /* CONFIG_GPIOLIB_IRQCHIP */
2811 static inline int gpiochip_add_irqchip(struct gpio_chip *gc,
2812 struct lock_class_key *lock_key,
2813 struct lock_class_key *request_key)
2817 static void gpiochip_irqchip_remove(struct gpio_chip *gc) {}
2819 static inline int gpiochip_irqchip_init_hw(struct gpio_chip *gc)
2824 static inline int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gc)
2828 static inline void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gc)
2831 #endif /* CONFIG_GPIOLIB_IRQCHIP */
2834 * gpiochip_generic_request() - request the gpio function for a pin
2835 * @gc: the gpiochip owning the GPIO
2836 * @offset: the offset of the GPIO to request for GPIO function
2838 int gpiochip_generic_request(struct gpio_chip *gc, unsigned offset)
2840 #ifdef CONFIG_PINCTRL
2841 if (list_empty(&gc->gpiodev->pin_ranges))
2845 return pinctrl_gpio_request(gc->gpiodev->base + offset);
2847 EXPORT_SYMBOL_GPL(gpiochip_generic_request);
2850 * gpiochip_generic_free() - free the gpio function from a pin
2851 * @gc: the gpiochip to request the gpio function for
2852 * @offset: the offset of the GPIO to free from GPIO function
2854 void gpiochip_generic_free(struct gpio_chip *gc, unsigned offset)
2856 pinctrl_gpio_free(gc->gpiodev->base + offset);
2858 EXPORT_SYMBOL_GPL(gpiochip_generic_free);
2861 * gpiochip_generic_config() - apply configuration for a pin
2862 * @gc: the gpiochip owning the GPIO
2863 * @offset: the offset of the GPIO to apply the configuration
2864 * @config: the configuration to be applied
2866 int gpiochip_generic_config(struct gpio_chip *gc, unsigned offset,
2867 unsigned long config)
2869 return pinctrl_gpio_set_config(gc->gpiodev->base + offset, config);
2871 EXPORT_SYMBOL_GPL(gpiochip_generic_config);
2873 #ifdef CONFIG_PINCTRL
2876 * gpiochip_add_pingroup_range() - add a range for GPIO <-> pin mapping
2877 * @gc: the gpiochip to add the range for
2878 * @pctldev: the pin controller to map to
2879 * @gpio_offset: the start offset in the current gpio_chip number space
2880 * @pin_group: name of the pin group inside the pin controller
2882 * Calling this function directly from a DeviceTree-supported
2883 * pinctrl driver is DEPRECATED. Please see Section 2.1 of
2884 * Documentation/devicetree/bindings/gpio/gpio.txt on how to
2885 * bind pinctrl and gpio drivers via the "gpio-ranges" property.
2887 int gpiochip_add_pingroup_range(struct gpio_chip *gc,
2888 struct pinctrl_dev *pctldev,
2889 unsigned int gpio_offset, const char *pin_group)
2891 struct gpio_pin_range *pin_range;
2892 struct gpio_device *gdev = gc->gpiodev;
2895 pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
2897 chip_err(gc, "failed to allocate pin ranges\n");
2901 /* Use local offset as range ID */
2902 pin_range->range.id = gpio_offset;
2903 pin_range->range.gc = gc;
2904 pin_range->range.name = gc->label;
2905 pin_range->range.base = gdev->base + gpio_offset;
2906 pin_range->pctldev = pctldev;
2908 ret = pinctrl_get_group_pins(pctldev, pin_group,
2909 &pin_range->range.pins,
2910 &pin_range->range.npins);
2916 pinctrl_add_gpio_range(pctldev, &pin_range->range);
2918 chip_dbg(gc, "created GPIO range %d->%d ==> %s PINGRP %s\n",
2919 gpio_offset, gpio_offset + pin_range->range.npins - 1,
2920 pinctrl_dev_get_devname(pctldev), pin_group);
2922 list_add_tail(&pin_range->node, &gdev->pin_ranges);
2926 EXPORT_SYMBOL_GPL(gpiochip_add_pingroup_range);
2929 * gpiochip_add_pin_range() - add a range for GPIO <-> pin mapping
2930 * @gc: the gpiochip to add the range for
2931 * @pinctl_name: the dev_name() of the pin controller to map to
2932 * @gpio_offset: the start offset in the current gpio_chip number space
2933 * @pin_offset: the start offset in the pin controller number space
2934 * @npins: the number of pins from the offset of each pin space (GPIO and
2935 * pin controller) to accumulate in this range
2938 * 0 on success, or a negative error-code on failure.
2940 * Calling this function directly from a DeviceTree-supported
2941 * pinctrl driver is DEPRECATED. Please see Section 2.1 of
2942 * Documentation/devicetree/bindings/gpio/gpio.txt on how to
2943 * bind pinctrl and gpio drivers via the "gpio-ranges" property.
2945 int gpiochip_add_pin_range(struct gpio_chip *gc, const char *pinctl_name,
2946 unsigned int gpio_offset, unsigned int pin_offset,
2949 struct gpio_pin_range *pin_range;
2950 struct gpio_device *gdev = gc->gpiodev;
2953 pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
2955 chip_err(gc, "failed to allocate pin ranges\n");
2959 /* Use local offset as range ID */
2960 pin_range->range.id = gpio_offset;
2961 pin_range->range.gc = gc;
2962 pin_range->range.name = gc->label;
2963 pin_range->range.base = gdev->base + gpio_offset;
2964 pin_range->range.pin_base = pin_offset;
2965 pin_range->range.npins = npins;
2966 pin_range->pctldev = pinctrl_find_and_add_gpio_range(pinctl_name,
2968 if (IS_ERR(pin_range->pctldev)) {
2969 ret = PTR_ERR(pin_range->pctldev);
2970 chip_err(gc, "could not create pin range\n");
2974 chip_dbg(gc, "created GPIO range %d->%d ==> %s PIN %d->%d\n",
2975 gpio_offset, gpio_offset + npins - 1,
2977 pin_offset, pin_offset + npins - 1);
2979 list_add_tail(&pin_range->node, &gdev->pin_ranges);
2983 EXPORT_SYMBOL_GPL(gpiochip_add_pin_range);
2986 * gpiochip_remove_pin_ranges() - remove all the GPIO <-> pin mappings
2987 * @gc: the chip to remove all the mappings for
2989 void gpiochip_remove_pin_ranges(struct gpio_chip *gc)
2991 struct gpio_pin_range *pin_range, *tmp;
2992 struct gpio_device *gdev = gc->gpiodev;
2994 list_for_each_entry_safe(pin_range, tmp, &gdev->pin_ranges, node) {
2995 list_del(&pin_range->node);
2996 pinctrl_remove_gpio_range(pin_range->pctldev,
3001 EXPORT_SYMBOL_GPL(gpiochip_remove_pin_ranges);
3003 #endif /* CONFIG_PINCTRL */
3005 /* These "optional" allocation calls help prevent drivers from stomping
3006 * on each other, and help provide better diagnostics in debugfs.
3007 * They're called even less than the "set direction" calls.
3009 static int gpiod_request_commit(struct gpio_desc *desc, const char *label)
3011 struct gpio_chip *gc = desc->gdev->chip;
3013 unsigned long flags;
3017 label = kstrdup_const(label, GFP_KERNEL);
3022 spin_lock_irqsave(&gpio_lock, flags);
3024 /* NOTE: gpio_request() can be called in early boot,
3025 * before IRQs are enabled, for non-sleeping (SOC) GPIOs.
3028 if (test_and_set_bit(FLAG_REQUESTED, &desc->flags) == 0) {
3029 desc_set_label(desc, label ? : "?");
3038 /* gc->request may sleep */
3039 spin_unlock_irqrestore(&gpio_lock, flags);
3040 offset = gpio_chip_hwgpio(desc);
3041 if (gpiochip_line_is_valid(gc, offset))
3042 ret = gc->request(gc, offset);
3045 spin_lock_irqsave(&gpio_lock, flags);
3048 desc_set_label(desc, NULL);
3050 clear_bit(FLAG_REQUESTED, &desc->flags);
3054 if (gc->get_direction) {
3055 /* gc->get_direction may sleep */
3056 spin_unlock_irqrestore(&gpio_lock, flags);
3057 gpiod_get_direction(desc);
3058 spin_lock_irqsave(&gpio_lock, flags);
3061 spin_unlock_irqrestore(&gpio_lock, flags);
3066 * This descriptor validation needs to be inserted verbatim into each
3067 * function taking a descriptor, so we need to use a preprocessor
3068 * macro to avoid endless duplication. If the desc is NULL it is an
3069 * optional GPIO and calls should just bail out.
3071 static int validate_desc(const struct gpio_desc *desc, const char *func)
3076 pr_warn("%s: invalid GPIO (errorpointer)\n", func);
3077 return PTR_ERR(desc);
3080 pr_warn("%s: invalid GPIO (no device)\n", func);
3083 if (!desc->gdev->chip) {
3084 dev_warn(&desc->gdev->dev,
3085 "%s: backing chip is gone\n", func);
3091 #define VALIDATE_DESC(desc) do { \
3092 int __valid = validate_desc(desc, __func__); \
3097 #define VALIDATE_DESC_VOID(desc) do { \
3098 int __valid = validate_desc(desc, __func__); \
3103 int gpiod_request(struct gpio_desc *desc, const char *label)
3105 int ret = -EPROBE_DEFER;
3106 struct gpio_device *gdev;
3108 VALIDATE_DESC(desc);
3111 if (try_module_get(gdev->owner)) {
3112 ret = gpiod_request_commit(desc, label);
3114 module_put(gdev->owner);
3116 get_device(&gdev->dev);
3120 gpiod_dbg(desc, "%s: status %d\n", __func__, ret);
3125 static bool gpiod_free_commit(struct gpio_desc *desc)
3128 unsigned long flags;
3129 struct gpio_chip *gc;
3133 gpiod_unexport(desc);
3135 spin_lock_irqsave(&gpio_lock, flags);
3137 gc = desc->gdev->chip;
3138 if (gc && test_bit(FLAG_REQUESTED, &desc->flags)) {
3140 spin_unlock_irqrestore(&gpio_lock, flags);
3141 might_sleep_if(gc->can_sleep);
3142 gc->free(gc, gpio_chip_hwgpio(desc));
3143 spin_lock_irqsave(&gpio_lock, flags);
3145 kfree_const(desc->label);
3146 desc_set_label(desc, NULL);
3147 clear_bit(FLAG_ACTIVE_LOW, &desc->flags);
3148 clear_bit(FLAG_REQUESTED, &desc->flags);
3149 clear_bit(FLAG_OPEN_DRAIN, &desc->flags);
3150 clear_bit(FLAG_OPEN_SOURCE, &desc->flags);
3151 clear_bit(FLAG_PULL_UP, &desc->flags);
3152 clear_bit(FLAG_PULL_DOWN, &desc->flags);
3153 clear_bit(FLAG_BIAS_DISABLE, &desc->flags);
3154 clear_bit(FLAG_IS_HOGGED, &desc->flags);
3155 #ifdef CONFIG_OF_DYNAMIC
3161 spin_unlock_irqrestore(&gpio_lock, flags);
3162 atomic_notifier_call_chain(&desc->gdev->notifier,
3163 GPIOLINE_CHANGED_RELEASED, desc);
3168 void gpiod_free(struct gpio_desc *desc)
3170 if (desc && desc->gdev && gpiod_free_commit(desc)) {
3171 module_put(desc->gdev->owner);
3172 put_device(&desc->gdev->dev);
3174 WARN_ON(extra_checks);
3179 * gpiochip_is_requested - return string iff signal was requested
3180 * @gc: controller managing the signal
3181 * @offset: of signal within controller's 0..(ngpio - 1) range
3183 * Returns NULL if the GPIO is not currently requested, else a string.
3184 * The string returned is the label passed to gpio_request(); if none has been
3185 * passed it is a meaningless, non-NULL constant.
3187 * This function is for use by GPIO controller drivers. The label can
3188 * help with diagnostics, and knowing that the signal is used as a GPIO
3189 * can help avoid accidentally multiplexing it to another controller.
3191 const char *gpiochip_is_requested(struct gpio_chip *gc, unsigned offset)
3193 struct gpio_desc *desc;
3195 if (offset >= gc->ngpio)
3198 desc = gpiochip_get_desc(gc, offset);
3202 if (test_bit(FLAG_REQUESTED, &desc->flags) == 0)
3206 EXPORT_SYMBOL_GPL(gpiochip_is_requested);
3209 * gpiochip_request_own_desc - Allow GPIO chip to request its own descriptor
3211 * @hwnum: hardware number of the GPIO for which to request the descriptor
3212 * @label: label for the GPIO
3213 * @lflags: lookup flags for this GPIO or 0 if default, this can be used to
3214 * specify things like line inversion semantics with the machine flags
3215 * such as GPIO_OUT_LOW
3216 * @dflags: descriptor request flags for this GPIO or 0 if default, this
3217 * can be used to specify consumer semantics such as open drain
3219 * Function allows GPIO chip drivers to request and use their own GPIO
3220 * descriptors via gpiolib API. Difference to gpiod_request() is that this
3221 * function will not increase reference count of the GPIO chip module. This
3222 * allows the GPIO chip module to be unloaded as needed (we assume that the
3223 * GPIO chip driver handles freeing the GPIOs it has requested).
3226 * A pointer to the GPIO descriptor, or an ERR_PTR()-encoded negative error
3229 struct gpio_desc *gpiochip_request_own_desc(struct gpio_chip *gc,
3232 enum gpio_lookup_flags lflags,
3233 enum gpiod_flags dflags)
3235 struct gpio_desc *desc = gpiochip_get_desc(gc, hwnum);
3239 chip_err(gc, "failed to get GPIO descriptor\n");
3243 ret = gpiod_request_commit(desc, label);
3245 return ERR_PTR(ret);
3247 ret = gpiod_configure_flags(desc, label, lflags, dflags);
3249 chip_err(gc, "setup of own GPIO %s failed\n", label);
3250 gpiod_free_commit(desc);
3251 return ERR_PTR(ret);
3256 EXPORT_SYMBOL_GPL(gpiochip_request_own_desc);
3259 * gpiochip_free_own_desc - Free GPIO requested by the chip driver
3260 * @desc: GPIO descriptor to free
3262 * Function frees the given GPIO requested previously with
3263 * gpiochip_request_own_desc().
3265 void gpiochip_free_own_desc(struct gpio_desc *desc)
3268 gpiod_free_commit(desc);
3270 EXPORT_SYMBOL_GPL(gpiochip_free_own_desc);
3273 * Drivers MUST set GPIO direction before making get/set calls. In
3274 * some cases this is done in early boot, before IRQs are enabled.
3276 * As a rule these aren't called more than once (except for drivers
3277 * using the open-drain emulation idiom) so these are natural places
3278 * to accumulate extra debugging checks. Note that we can't (yet)
3279 * rely on gpio_request() having been called beforehand.
3282 static int gpio_do_set_config(struct gpio_chip *gc, unsigned int offset,
3283 unsigned long config)
3285 if (!gc->set_config)
3288 return gc->set_config(gc, offset, config);
3291 static int gpio_set_config(struct gpio_desc *desc, enum pin_config_param mode)
3293 struct gpio_chip *gc = desc->gdev->chip;
3294 unsigned long config;
3298 case PIN_CONFIG_BIAS_PULL_DOWN:
3299 case PIN_CONFIG_BIAS_PULL_UP:
3307 config = PIN_CONF_PACKED(mode, arg);
3308 return gpio_do_set_config(gc, gpio_chip_hwgpio(desc), config);
3311 static int gpio_set_bias(struct gpio_desc *desc)
3316 if (test_bit(FLAG_BIAS_DISABLE, &desc->flags))
3317 bias = PIN_CONFIG_BIAS_DISABLE;
3318 else if (test_bit(FLAG_PULL_UP, &desc->flags))
3319 bias = PIN_CONFIG_BIAS_PULL_UP;
3320 else if (test_bit(FLAG_PULL_DOWN, &desc->flags))
3321 bias = PIN_CONFIG_BIAS_PULL_DOWN;
3324 ret = gpio_set_config(desc, bias);
3325 if (ret != -ENOTSUPP)
3332 * gpiod_direction_input - set the GPIO direction to input
3333 * @desc: GPIO to set to input
3335 * Set the direction of the passed GPIO to input, such as gpiod_get_value() can
3336 * be called safely on it.
3338 * Return 0 in case of success, else an error code.
3340 int gpiod_direction_input(struct gpio_desc *desc)
3342 struct gpio_chip *gc;
3345 VALIDATE_DESC(desc);
3346 gc = desc->gdev->chip;
3349 * It is legal to have no .get() and .direction_input() specified if
3350 * the chip is output-only, but you can't specify .direction_input()
3351 * and not support the .get() operation, that doesn't make sense.
3353 if (!gc->get && gc->direction_input) {
3355 "%s: missing get() but have direction_input()\n",
3361 * If we have a .direction_input() callback, things are simple,
3362 * just call it. Else we are some input-only chip so try to check the
3363 * direction (if .get_direction() is supported) else we silently
3364 * assume we are in input mode after this.
3366 if (gc->direction_input) {
3367 ret = gc->direction_input(gc, gpio_chip_hwgpio(desc));
3368 } else if (gc->get_direction &&
3369 (gc->get_direction(gc, gpio_chip_hwgpio(desc)) != 1)) {
3371 "%s: missing direction_input() operation and line is output\n",
3376 clear_bit(FLAG_IS_OUT, &desc->flags);
3377 ret = gpio_set_bias(desc);
3380 trace_gpio_direction(desc_to_gpio(desc), 1, ret);
3384 EXPORT_SYMBOL_GPL(gpiod_direction_input);
3386 static int gpiod_direction_output_raw_commit(struct gpio_desc *desc, int value)
3388 struct gpio_chip *gc = desc->gdev->chip;
3393 * It's OK not to specify .direction_output() if the gpiochip is
3394 * output-only, but if there is then not even a .set() operation it
3395 * is pretty tricky to drive the output line.
3397 if (!gc->set && !gc->direction_output) {
3399 "%s: missing set() and direction_output() operations\n",
3404 if (gc->direction_output) {
3405 ret = gc->direction_output(gc, gpio_chip_hwgpio(desc), val);
3407 /* Check that we are in output mode if we can */
3408 if (gc->get_direction &&
3409 gc->get_direction(gc, gpio_chip_hwgpio(desc))) {
3411 "%s: missing direction_output() operation\n",
3416 * If we can't actively set the direction, we are some
3417 * output-only chip, so just drive the output as desired.
3419 gc->set(gc, gpio_chip_hwgpio(desc), val);
3423 set_bit(FLAG_IS_OUT, &desc->flags);
3424 trace_gpio_value(desc_to_gpio(desc), 0, val);
3425 trace_gpio_direction(desc_to_gpio(desc), 0, ret);
3430 * gpiod_direction_output_raw - set the GPIO direction to output
3431 * @desc: GPIO to set to output
3432 * @value: initial output value of the GPIO
3434 * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
3435 * be called safely on it. The initial value of the output must be specified
3436 * as raw value on the physical line without regard for the ACTIVE_LOW status.
3438 * Return 0 in case of success, else an error code.
3440 int gpiod_direction_output_raw(struct gpio_desc *desc, int value)
3442 VALIDATE_DESC(desc);
3443 return gpiod_direction_output_raw_commit(desc, value);
3445 EXPORT_SYMBOL_GPL(gpiod_direction_output_raw);
3448 * gpiod_direction_output - set the GPIO direction to output
3449 * @desc: GPIO to set to output
3450 * @value: initial output value of the GPIO
3452 * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
3453 * be called safely on it. The initial value of the output must be specified
3454 * as the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
3457 * Return 0 in case of success, else an error code.
3459 int gpiod_direction_output(struct gpio_desc *desc, int value)
3463 VALIDATE_DESC(desc);
3464 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3469 /* GPIOs used for enabled IRQs shall not be set as output */
3470 if (test_bit(FLAG_USED_AS_IRQ, &desc->flags) &&
3471 test_bit(FLAG_IRQ_IS_ENABLED, &desc->flags)) {
3473 "%s: tried to set a GPIO tied to an IRQ as output\n",
3478 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags)) {
3479 /* First see if we can enable open drain in hardware */
3480 ret = gpio_set_config(desc, PIN_CONFIG_DRIVE_OPEN_DRAIN);
3482 goto set_output_value;
3483 /* Emulate open drain by not actively driving the line high */
3485 ret = gpiod_direction_input(desc);
3486 goto set_output_flag;
3489 else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags)) {
3490 ret = gpio_set_config(desc, PIN_CONFIG_DRIVE_OPEN_SOURCE);
3492 goto set_output_value;
3493 /* Emulate open source by not actively driving the line low */
3495 ret = gpiod_direction_input(desc);
3496 goto set_output_flag;
3499 gpio_set_config(desc, PIN_CONFIG_DRIVE_PUSH_PULL);
3503 ret = gpio_set_bias(desc);
3506 return gpiod_direction_output_raw_commit(desc, value);
3510 * When emulating open-source or open-drain functionalities by not
3511 * actively driving the line (setting mode to input) we still need to
3512 * set the IS_OUT flag or otherwise we won't be able to set the line
3516 set_bit(FLAG_IS_OUT, &desc->flags);
3519 EXPORT_SYMBOL_GPL(gpiod_direction_output);
3522 * gpiod_set_config - sets @config for a GPIO
3523 * @desc: descriptor of the GPIO for which to set the configuration
3524 * @config: Same packed config format as generic pinconf
3527 * 0 on success, %-ENOTSUPP if the controller doesn't support setting the
3530 int gpiod_set_config(struct gpio_desc *desc, unsigned long config)
3532 struct gpio_chip *gc;
3534 VALIDATE_DESC(desc);
3535 gc = desc->gdev->chip;
3537 return gpio_do_set_config(gc, gpio_chip_hwgpio(desc), config);
3539 EXPORT_SYMBOL_GPL(gpiod_set_config);
3542 * gpiod_set_debounce - sets @debounce time for a GPIO
3543 * @desc: descriptor of the GPIO for which to set debounce time
3544 * @debounce: debounce time in microseconds
3547 * 0 on success, %-ENOTSUPP if the controller doesn't support setting the
3550 int gpiod_set_debounce(struct gpio_desc *desc, unsigned debounce)
3552 unsigned long config;
3554 config = pinconf_to_config_packed(PIN_CONFIG_INPUT_DEBOUNCE, debounce);
3555 return gpiod_set_config(desc, config);
3557 EXPORT_SYMBOL_GPL(gpiod_set_debounce);
3560 * gpiod_set_transitory - Lose or retain GPIO state on suspend or reset
3561 * @desc: descriptor of the GPIO for which to configure persistence
3562 * @transitory: True to lose state on suspend or reset, false for persistence
3565 * 0 on success, otherwise a negative error code.
3567 int gpiod_set_transitory(struct gpio_desc *desc, bool transitory)
3569 struct gpio_chip *gc;
3570 unsigned long packed;
3574 VALIDATE_DESC(desc);
3576 * Handle FLAG_TRANSITORY first, enabling queries to gpiolib for
3577 * persistence state.
3579 assign_bit(FLAG_TRANSITORY, &desc->flags, transitory);
3581 /* If the driver supports it, set the persistence state now */
3582 gc = desc->gdev->chip;
3583 if (!gc->set_config)
3586 packed = pinconf_to_config_packed(PIN_CONFIG_PERSIST_STATE,
3588 gpio = gpio_chip_hwgpio(desc);
3589 rc = gpio_do_set_config(gc, gpio, packed);
3590 if (rc == -ENOTSUPP) {
3591 dev_dbg(&desc->gdev->dev, "Persistence not supported for GPIO %d\n",
3598 EXPORT_SYMBOL_GPL(gpiod_set_transitory);
3601 * gpiod_is_active_low - test whether a GPIO is active-low or not
3602 * @desc: the gpio descriptor to test
3604 * Returns 1 if the GPIO is active-low, 0 otherwise.
3606 int gpiod_is_active_low(const struct gpio_desc *desc)
3608 VALIDATE_DESC(desc);
3609 return test_bit(FLAG_ACTIVE_LOW, &desc->flags);
3611 EXPORT_SYMBOL_GPL(gpiod_is_active_low);
3614 * gpiod_toggle_active_low - toggle whether a GPIO is active-low or not
3615 * @desc: the gpio descriptor to change
3617 void gpiod_toggle_active_low(struct gpio_desc *desc)
3619 VALIDATE_DESC_VOID(desc);
3620 change_bit(FLAG_ACTIVE_LOW, &desc->flags);
3622 EXPORT_SYMBOL_GPL(gpiod_toggle_active_low);
3624 /* I/O calls are only valid after configuration completed; the relevant
3625 * "is this a valid GPIO" error checks should already have been done.
3627 * "Get" operations are often inlinable as reading a pin value register,
3628 * and masking the relevant bit in that register.
3630 * When "set" operations are inlinable, they involve writing that mask to
3631 * one register to set a low value, or a different register to set it high.
3632 * Otherwise locking is needed, so there may be little value to inlining.
3634 *------------------------------------------------------------------------
3636 * IMPORTANT!!! The hot paths -- get/set value -- assume that callers
3637 * have requested the GPIO. That can include implicit requesting by
3638 * a direction setting call. Marking a gpio as requested locks its chip
3639 * in memory, guaranteeing that these table lookups need no more locking
3640 * and that gpiochip_remove() will fail.
3642 * REVISIT when debugging, consider adding some instrumentation to ensure
3643 * that the GPIO was actually requested.
3646 static int gpiod_get_raw_value_commit(const struct gpio_desc *desc)
3648 struct gpio_chip *gc;
3652 gc = desc->gdev->chip;
3653 offset = gpio_chip_hwgpio(desc);
3654 value = gc->get ? gc->get(gc, offset) : -EIO;
3655 value = value < 0 ? value : !!value;
3656 trace_gpio_value(desc_to_gpio(desc), 1, value);
3660 static int gpio_chip_get_multiple(struct gpio_chip *gc,
3661 unsigned long *mask, unsigned long *bits)
3663 if (gc->get_multiple) {
3664 return gc->get_multiple(gc, mask, bits);
3665 } else if (gc->get) {
3668 for_each_set_bit(i, mask, gc->ngpio) {
3669 value = gc->get(gc, i);
3672 __assign_bit(i, bits, value);
3679 int gpiod_get_array_value_complex(bool raw, bool can_sleep,
3680 unsigned int array_size,
3681 struct gpio_desc **desc_array,
3682 struct gpio_array *array_info,
3683 unsigned long *value_bitmap)
3688 * Validate array_info against desc_array and its size.
3689 * It should immediately follow desc_array if both
3690 * have been obtained from the same gpiod_get_array() call.
3692 if (array_info && array_info->desc == desc_array &&
3693 array_size <= array_info->size &&
3694 (void *)array_info == desc_array + array_info->size) {
3696 WARN_ON(array_info->chip->can_sleep);
3698 ret = gpio_chip_get_multiple(array_info->chip,
3699 array_info->get_mask,
3704 if (!raw && !bitmap_empty(array_info->invert_mask, array_size))
3705 bitmap_xor(value_bitmap, value_bitmap,
3706 array_info->invert_mask, array_size);
3708 if (bitmap_full(array_info->get_mask, array_size))
3711 i = find_first_zero_bit(array_info->get_mask, array_size);
3716 while (i < array_size) {
3717 struct gpio_chip *gc = desc_array[i]->gdev->chip;
3718 unsigned long fastpath[2 * BITS_TO_LONGS(FASTPATH_NGPIO)];
3719 unsigned long *mask, *bits;
3722 if (likely(gc->ngpio <= FASTPATH_NGPIO)) {
3725 mask = kmalloc_array(2 * BITS_TO_LONGS(gc->ngpio),
3727 can_sleep ? GFP_KERNEL : GFP_ATOMIC);
3732 bits = mask + BITS_TO_LONGS(gc->ngpio);
3733 bitmap_zero(mask, gc->ngpio);
3736 WARN_ON(gc->can_sleep);
3738 /* collect all inputs belonging to the same chip */
3741 const struct gpio_desc *desc = desc_array[i];
3742 int hwgpio = gpio_chip_hwgpio(desc);
3744 __set_bit(hwgpio, mask);
3748 i = find_next_zero_bit(array_info->get_mask,
3750 } while ((i < array_size) &&
3751 (desc_array[i]->gdev->chip == gc));
3753 ret = gpio_chip_get_multiple(gc, mask, bits);
3755 if (mask != fastpath)
3760 for (j = first; j < i; ) {
3761 const struct gpio_desc *desc = desc_array[j];
3762 int hwgpio = gpio_chip_hwgpio(desc);
3763 int value = test_bit(hwgpio, bits);
3765 if (!raw && test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3767 __assign_bit(j, value_bitmap, value);
3768 trace_gpio_value(desc_to_gpio(desc), 1, value);
3772 j = find_next_zero_bit(array_info->get_mask, i,
3776 if (mask != fastpath)
3783 * gpiod_get_raw_value() - return a gpio's raw value
3784 * @desc: gpio whose value will be returned
3786 * Return the GPIO's raw value, i.e. the value of the physical line disregarding
3787 * its ACTIVE_LOW status, or negative errno on failure.
3789 * This function can be called from contexts where we cannot sleep, and will
3790 * complain if the GPIO chip functions potentially sleep.
3792 int gpiod_get_raw_value(const struct gpio_desc *desc)
3794 VALIDATE_DESC(desc);
3795 /* Should be using gpiod_get_raw_value_cansleep() */
3796 WARN_ON(desc->gdev->chip->can_sleep);
3797 return gpiod_get_raw_value_commit(desc);
3799 EXPORT_SYMBOL_GPL(gpiod_get_raw_value);
3802 * gpiod_get_value() - return a gpio's value
3803 * @desc: gpio whose value will be returned
3805 * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
3806 * account, or negative errno on failure.
3808 * This function can be called from contexts where we cannot sleep, and will
3809 * complain if the GPIO chip functions potentially sleep.
3811 int gpiod_get_value(const struct gpio_desc *desc)
3815 VALIDATE_DESC(desc);
3816 /* Should be using gpiod_get_value_cansleep() */
3817 WARN_ON(desc->gdev->chip->can_sleep);
3819 value = gpiod_get_raw_value_commit(desc);
3823 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3828 EXPORT_SYMBOL_GPL(gpiod_get_value);
3831 * gpiod_get_raw_array_value() - read raw values from an array of GPIOs
3832 * @array_size: number of elements in the descriptor array / value bitmap
3833 * @desc_array: array of GPIO descriptors whose values will be read
3834 * @array_info: information on applicability of fast bitmap processing path
3835 * @value_bitmap: bitmap to store the read values
3837 * Read the raw values of the GPIOs, i.e. the values of the physical lines
3838 * without regard for their ACTIVE_LOW status. Return 0 in case of success,
3839 * else an error code.
3841 * This function can be called from contexts where we cannot sleep,
3842 * and it will complain if the GPIO chip functions potentially sleep.
3844 int gpiod_get_raw_array_value(unsigned int array_size,
3845 struct gpio_desc **desc_array,
3846 struct gpio_array *array_info,
3847 unsigned long *value_bitmap)
3851 return gpiod_get_array_value_complex(true, false, array_size,
3852 desc_array, array_info,
3855 EXPORT_SYMBOL_GPL(gpiod_get_raw_array_value);
3858 * gpiod_get_array_value() - read values from an array of GPIOs
3859 * @array_size: number of elements in the descriptor array / value bitmap
3860 * @desc_array: array of GPIO descriptors whose values will be read
3861 * @array_info: information on applicability of fast bitmap processing path
3862 * @value_bitmap: bitmap to store the read values
3864 * Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3865 * into account. Return 0 in case of success, else an error code.
3867 * This function can be called from contexts where we cannot sleep,
3868 * and it will complain if the GPIO chip functions potentially sleep.
3870 int gpiod_get_array_value(unsigned int array_size,
3871 struct gpio_desc **desc_array,
3872 struct gpio_array *array_info,
3873 unsigned long *value_bitmap)
3877 return gpiod_get_array_value_complex(false, false, array_size,
3878 desc_array, array_info,
3881 EXPORT_SYMBOL_GPL(gpiod_get_array_value);
3884 * gpio_set_open_drain_value_commit() - Set the open drain gpio's value.
3885 * @desc: gpio descriptor whose state need to be set.
3886 * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
3888 static void gpio_set_open_drain_value_commit(struct gpio_desc *desc, bool value)
3891 struct gpio_chip *gc = desc->gdev->chip;
3892 int offset = gpio_chip_hwgpio(desc);
3895 ret = gc->direction_input(gc, offset);
3897 ret = gc->direction_output(gc, offset, 0);
3899 set_bit(FLAG_IS_OUT, &desc->flags);
3901 trace_gpio_direction(desc_to_gpio(desc), value, ret);
3904 "%s: Error in set_value for open drain err %d\n",
3909 * _gpio_set_open_source_value() - Set the open source gpio's value.
3910 * @desc: gpio descriptor whose state need to be set.
3911 * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
3913 static void gpio_set_open_source_value_commit(struct gpio_desc *desc, bool value)
3916 struct gpio_chip *gc = desc->gdev->chip;
3917 int offset = gpio_chip_hwgpio(desc);
3920 ret = gc->direction_output(gc, offset, 1);
3922 set_bit(FLAG_IS_OUT, &desc->flags);
3924 ret = gc->direction_input(gc, offset);
3926 trace_gpio_direction(desc_to_gpio(desc), !value, ret);
3929 "%s: Error in set_value for open source err %d\n",
3933 static void gpiod_set_raw_value_commit(struct gpio_desc *desc, bool value)
3935 struct gpio_chip *gc;
3937 gc = desc->gdev->chip;
3938 trace_gpio_value(desc_to_gpio(desc), 0, value);
3939 gc->set(gc, gpio_chip_hwgpio(desc), value);
3943 * set multiple outputs on the same chip;
3944 * use the chip's set_multiple function if available;
3945 * otherwise set the outputs sequentially;
3946 * @chip: the GPIO chip we operate on
3947 * @mask: bit mask array; one bit per output; BITS_PER_LONG bits per word
3948 * defines which outputs are to be changed
3949 * @bits: bit value array; one bit per output; BITS_PER_LONG bits per word
3950 * defines the values the outputs specified by mask are to be set to
3952 static void gpio_chip_set_multiple(struct gpio_chip *gc,
3953 unsigned long *mask, unsigned long *bits)
3955 if (gc->set_multiple) {
3956 gc->set_multiple(gc, mask, bits);
3960 /* set outputs if the corresponding mask bit is set */
3961 for_each_set_bit(i, mask, gc->ngpio)
3962 gc->set(gc, i, test_bit(i, bits));
3966 int gpiod_set_array_value_complex(bool raw, bool can_sleep,
3967 unsigned int array_size,
3968 struct gpio_desc **desc_array,
3969 struct gpio_array *array_info,
3970 unsigned long *value_bitmap)
3975 * Validate array_info against desc_array and its size.
3976 * It should immediately follow desc_array if both
3977 * have been obtained from the same gpiod_get_array() call.
3979 if (array_info && array_info->desc == desc_array &&
3980 array_size <= array_info->size &&
3981 (void *)array_info == desc_array + array_info->size) {
3983 WARN_ON(array_info->chip->can_sleep);
3985 if (!raw && !bitmap_empty(array_info->invert_mask, array_size))
3986 bitmap_xor(value_bitmap, value_bitmap,
3987 array_info->invert_mask, array_size);
3989 gpio_chip_set_multiple(array_info->chip, array_info->set_mask,
3992 if (bitmap_full(array_info->set_mask, array_size))
3995 i = find_first_zero_bit(array_info->set_mask, array_size);
4000 while (i < array_size) {
4001 struct gpio_chip *gc = desc_array[i]->gdev->chip;
4002 unsigned long fastpath[2 * BITS_TO_LONGS(FASTPATH_NGPIO)];
4003 unsigned long *mask, *bits;
4006 if (likely(gc->ngpio <= FASTPATH_NGPIO)) {
4009 mask = kmalloc_array(2 * BITS_TO_LONGS(gc->ngpio),
4011 can_sleep ? GFP_KERNEL : GFP_ATOMIC);
4016 bits = mask + BITS_TO_LONGS(gc->ngpio);
4017 bitmap_zero(mask, gc->ngpio);
4020 WARN_ON(gc->can_sleep);
4023 struct gpio_desc *desc = desc_array[i];
4024 int hwgpio = gpio_chip_hwgpio(desc);
4025 int value = test_bit(i, value_bitmap);
4028 * Pins applicable for fast input but not for
4029 * fast output processing may have been already
4030 * inverted inside the fast path, skip them.
4032 if (!raw && !(array_info &&
4033 test_bit(i, array_info->invert_mask)) &&
4034 test_bit(FLAG_ACTIVE_LOW, &desc->flags))
4036 trace_gpio_value(desc_to_gpio(desc), 0, value);
4038 * collect all normal outputs belonging to the same chip
4039 * open drain and open source outputs are set individually
4041 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags) && !raw) {
4042 gpio_set_open_drain_value_commit(desc, value);
4043 } else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags) && !raw) {
4044 gpio_set_open_source_value_commit(desc, value);
4046 __set_bit(hwgpio, mask);
4047 __assign_bit(hwgpio, bits, value);
4053 i = find_next_zero_bit(array_info->set_mask,
4055 } while ((i < array_size) &&
4056 (desc_array[i]->gdev->chip == gc));
4057 /* push collected bits to outputs */
4059 gpio_chip_set_multiple(gc, mask, bits);
4061 if (mask != fastpath)
4068 * gpiod_set_raw_value() - assign a gpio's raw value
4069 * @desc: gpio whose value will be assigned
4070 * @value: value to assign
4072 * Set the raw value of the GPIO, i.e. the value of its physical line without
4073 * regard for its ACTIVE_LOW status.
4075 * This function can be called from contexts where we cannot sleep, and will
4076 * complain if the GPIO chip functions potentially sleep.
4078 void gpiod_set_raw_value(struct gpio_desc *desc, int value)
4080 VALIDATE_DESC_VOID(desc);
4081 /* Should be using gpiod_set_raw_value_cansleep() */
4082 WARN_ON(desc->gdev->chip->can_sleep);
4083 gpiod_set_raw_value_commit(desc, value);
4085 EXPORT_SYMBOL_GPL(gpiod_set_raw_value);
4088 * gpiod_set_value_nocheck() - set a GPIO line value without checking
4089 * @desc: the descriptor to set the value on
4090 * @value: value to set
4092 * This sets the value of a GPIO line backing a descriptor, applying
4093 * different semantic quirks like active low and open drain/source
4096 static void gpiod_set_value_nocheck(struct gpio_desc *desc, int value)
4098 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
4100 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
4101 gpio_set_open_drain_value_commit(desc, value);
4102 else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
4103 gpio_set_open_source_value_commit(desc, value);
4105 gpiod_set_raw_value_commit(desc, value);
4109 * gpiod_set_value() - assign a gpio's value
4110 * @desc: gpio whose value will be assigned
4111 * @value: value to assign
4113 * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW,
4114 * OPEN_DRAIN and OPEN_SOURCE flags into account.
4116 * This function can be called from contexts where we cannot sleep, and will
4117 * complain if the GPIO chip functions potentially sleep.
4119 void gpiod_set_value(struct gpio_desc *desc, int value)
4121 VALIDATE_DESC_VOID(desc);
4122 /* Should be using gpiod_set_value_cansleep() */
4123 WARN_ON(desc->gdev->chip->can_sleep);
4124 gpiod_set_value_nocheck(desc, value);
4126 EXPORT_SYMBOL_GPL(gpiod_set_value);
4129 * gpiod_set_raw_array_value() - assign values to an array of GPIOs
4130 * @array_size: number of elements in the descriptor array / value bitmap
4131 * @desc_array: array of GPIO descriptors whose values will be assigned
4132 * @array_info: information on applicability of fast bitmap processing path
4133 * @value_bitmap: bitmap of values to assign
4135 * Set the raw values of the GPIOs, i.e. the values of the physical lines
4136 * without regard for their ACTIVE_LOW status.
4138 * This function can be called from contexts where we cannot sleep, and will
4139 * complain if the GPIO chip functions potentially sleep.
4141 int gpiod_set_raw_array_value(unsigned int array_size,
4142 struct gpio_desc **desc_array,
4143 struct gpio_array *array_info,
4144 unsigned long *value_bitmap)
4148 return gpiod_set_array_value_complex(true, false, array_size,
4149 desc_array, array_info, value_bitmap);
4151 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value);
4154 * gpiod_set_array_value() - assign values to an array of GPIOs
4155 * @array_size: number of elements in the descriptor array / value bitmap
4156 * @desc_array: array of GPIO descriptors whose values will be assigned
4157 * @array_info: information on applicability of fast bitmap processing path
4158 * @value_bitmap: bitmap of values to assign
4160 * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
4163 * This function can be called from contexts where we cannot sleep, and will
4164 * complain if the GPIO chip functions potentially sleep.
4166 int gpiod_set_array_value(unsigned int array_size,
4167 struct gpio_desc **desc_array,
4168 struct gpio_array *array_info,
4169 unsigned long *value_bitmap)
4173 return gpiod_set_array_value_complex(false, false, array_size,
4174 desc_array, array_info,
4177 EXPORT_SYMBOL_GPL(gpiod_set_array_value);
4180 * gpiod_cansleep() - report whether gpio value access may sleep
4181 * @desc: gpio to check
4184 int gpiod_cansleep(const struct gpio_desc *desc)
4186 VALIDATE_DESC(desc);
4187 return desc->gdev->chip->can_sleep;
4189 EXPORT_SYMBOL_GPL(gpiod_cansleep);
4192 * gpiod_set_consumer_name() - set the consumer name for the descriptor
4193 * @desc: gpio to set the consumer name on
4194 * @name: the new consumer name
4196 int gpiod_set_consumer_name(struct gpio_desc *desc, const char *name)
4198 VALIDATE_DESC(desc);
4200 name = kstrdup_const(name, GFP_KERNEL);
4205 kfree_const(desc->label);
4206 desc_set_label(desc, name);
4210 EXPORT_SYMBOL_GPL(gpiod_set_consumer_name);
4213 * gpiod_to_irq() - return the IRQ corresponding to a GPIO
4214 * @desc: gpio whose IRQ will be returned (already requested)
4216 * Return the IRQ corresponding to the passed GPIO, or an error code in case of
4219 int gpiod_to_irq(const struct gpio_desc *desc)
4221 struct gpio_chip *gc;
4225 * Cannot VALIDATE_DESC() here as gpiod_to_irq() consumer semantics
4226 * requires this function to not return zero on an invalid descriptor
4227 * but rather a negative error number.
4229 if (!desc || IS_ERR(desc) || !desc->gdev || !desc->gdev->chip)
4232 gc = desc->gdev->chip;
4233 offset = gpio_chip_hwgpio(desc);
4235 int retirq = gc->to_irq(gc, offset);
4237 /* Zero means NO_IRQ */
4245 EXPORT_SYMBOL_GPL(gpiod_to_irq);
4248 * gpiochip_lock_as_irq() - lock a GPIO to be used as IRQ
4249 * @gc: the chip the GPIO to lock belongs to
4250 * @offset: the offset of the GPIO to lock as IRQ
4252 * This is used directly by GPIO drivers that want to lock down
4253 * a certain GPIO line to be used for IRQs.
4255 int gpiochip_lock_as_irq(struct gpio_chip *gc, unsigned int offset)
4257 struct gpio_desc *desc;
4259 desc = gpiochip_get_desc(gc, offset);
4261 return PTR_ERR(desc);
4264 * If it's fast: flush the direction setting if something changed
4267 if (!gc->can_sleep && gc->get_direction) {
4268 int dir = gpiod_get_direction(desc);
4271 chip_err(gc, "%s: cannot get GPIO direction\n",
4277 /* To be valid for IRQ the line needs to be input or open drain */
4278 if (test_bit(FLAG_IS_OUT, &desc->flags) &&
4279 !test_bit(FLAG_OPEN_DRAIN, &desc->flags)) {
4281 "%s: tried to flag a GPIO set as output for IRQ\n",
4286 set_bit(FLAG_USED_AS_IRQ, &desc->flags);
4287 set_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
4290 * If the consumer has not set up a label (such as when the
4291 * IRQ is referenced from .to_irq()) we set up a label here
4292 * so it is clear this is used as an interrupt.
4295 desc_set_label(desc, "interrupt");
4299 EXPORT_SYMBOL_GPL(gpiochip_lock_as_irq);
4302 * gpiochip_unlock_as_irq() - unlock a GPIO used as IRQ
4303 * @gc: the chip the GPIO to lock belongs to
4304 * @offset: the offset of the GPIO to lock as IRQ
4306 * This is used directly by GPIO drivers that want to indicate
4307 * that a certain GPIO is no longer used exclusively for IRQ.
4309 void gpiochip_unlock_as_irq(struct gpio_chip *gc, unsigned int offset)
4311 struct gpio_desc *desc;
4313 desc = gpiochip_get_desc(gc, offset);
4317 clear_bit(FLAG_USED_AS_IRQ, &desc->flags);
4318 clear_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
4320 /* If we only had this marking, erase it */
4321 if (desc->label && !strcmp(desc->label, "interrupt"))
4322 desc_set_label(desc, NULL);
4324 EXPORT_SYMBOL_GPL(gpiochip_unlock_as_irq);
4326 void gpiochip_disable_irq(struct gpio_chip *gc, unsigned int offset)
4328 struct gpio_desc *desc = gpiochip_get_desc(gc, offset);
4330 if (!IS_ERR(desc) &&
4331 !WARN_ON(!test_bit(FLAG_USED_AS_IRQ, &desc->flags)))
4332 clear_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
4334 EXPORT_SYMBOL_GPL(gpiochip_disable_irq);
4336 void gpiochip_enable_irq(struct gpio_chip *gc, unsigned int offset)
4338 struct gpio_desc *desc = gpiochip_get_desc(gc, offset);
4340 if (!IS_ERR(desc) &&
4341 !WARN_ON(!test_bit(FLAG_USED_AS_IRQ, &desc->flags))) {
4343 * We must not be output when using IRQ UNLESS we are
4346 WARN_ON(test_bit(FLAG_IS_OUT, &desc->flags) &&
4347 !test_bit(FLAG_OPEN_DRAIN, &desc->flags));
4348 set_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
4351 EXPORT_SYMBOL_GPL(gpiochip_enable_irq);
4353 bool gpiochip_line_is_irq(struct gpio_chip *gc, unsigned int offset)
4355 if (offset >= gc->ngpio)
4358 return test_bit(FLAG_USED_AS_IRQ, &gc->gpiodev->descs[offset].flags);
4360 EXPORT_SYMBOL_GPL(gpiochip_line_is_irq);
4362 int gpiochip_reqres_irq(struct gpio_chip *gc, unsigned int offset)
4366 if (!try_module_get(gc->gpiodev->owner))
4369 ret = gpiochip_lock_as_irq(gc, offset);
4371 chip_err(gc, "unable to lock HW IRQ %u for IRQ\n", offset);
4372 module_put(gc->gpiodev->owner);
4377 EXPORT_SYMBOL_GPL(gpiochip_reqres_irq);
4379 void gpiochip_relres_irq(struct gpio_chip *gc, unsigned int offset)
4381 gpiochip_unlock_as_irq(gc, offset);
4382 module_put(gc->gpiodev->owner);
4384 EXPORT_SYMBOL_GPL(gpiochip_relres_irq);
4386 bool gpiochip_line_is_open_drain(struct gpio_chip *gc, unsigned int offset)
4388 if (offset >= gc->ngpio)
4391 return test_bit(FLAG_OPEN_DRAIN, &gc->gpiodev->descs[offset].flags);
4393 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_drain);
4395 bool gpiochip_line_is_open_source(struct gpio_chip *gc, unsigned int offset)
4397 if (offset >= gc->ngpio)
4400 return test_bit(FLAG_OPEN_SOURCE, &gc->gpiodev->descs[offset].flags);
4402 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_source);
4404 bool gpiochip_line_is_persistent(struct gpio_chip *gc, unsigned int offset)
4406 if (offset >= gc->ngpio)
4409 return !test_bit(FLAG_TRANSITORY, &gc->gpiodev->descs[offset].flags);
4411 EXPORT_SYMBOL_GPL(gpiochip_line_is_persistent);
4414 * gpiod_get_raw_value_cansleep() - return a gpio's raw value
4415 * @desc: gpio whose value will be returned
4417 * Return the GPIO's raw value, i.e. the value of the physical line disregarding
4418 * its ACTIVE_LOW status, or negative errno on failure.
4420 * This function is to be called from contexts that can sleep.
4422 int gpiod_get_raw_value_cansleep(const struct gpio_desc *desc)
4424 might_sleep_if(extra_checks);
4425 VALIDATE_DESC(desc);
4426 return gpiod_get_raw_value_commit(desc);
4428 EXPORT_SYMBOL_GPL(gpiod_get_raw_value_cansleep);
4431 * gpiod_get_value_cansleep() - return a gpio's value
4432 * @desc: gpio whose value will be returned
4434 * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
4435 * account, or negative errno on failure.
4437 * This function is to be called from contexts that can sleep.
4439 int gpiod_get_value_cansleep(const struct gpio_desc *desc)
4443 might_sleep_if(extra_checks);
4444 VALIDATE_DESC(desc);
4445 value = gpiod_get_raw_value_commit(desc);
4449 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
4454 EXPORT_SYMBOL_GPL(gpiod_get_value_cansleep);
4457 * gpiod_get_raw_array_value_cansleep() - read raw values from an array of GPIOs
4458 * @array_size: number of elements in the descriptor array / value bitmap
4459 * @desc_array: array of GPIO descriptors whose values will be read
4460 * @array_info: information on applicability of fast bitmap processing path
4461 * @value_bitmap: bitmap to store the read values
4463 * Read the raw values of the GPIOs, i.e. the values of the physical lines
4464 * without regard for their ACTIVE_LOW status. Return 0 in case of success,
4465 * else an error code.
4467 * This function is to be called from contexts that can sleep.
4469 int gpiod_get_raw_array_value_cansleep(unsigned int array_size,
4470 struct gpio_desc **desc_array,
4471 struct gpio_array *array_info,
4472 unsigned long *value_bitmap)
4474 might_sleep_if(extra_checks);
4477 return gpiod_get_array_value_complex(true, true, array_size,
4478 desc_array, array_info,
4481 EXPORT_SYMBOL_GPL(gpiod_get_raw_array_value_cansleep);
4484 * gpiod_get_array_value_cansleep() - read values from an array of GPIOs
4485 * @array_size: number of elements in the descriptor array / value bitmap
4486 * @desc_array: array of GPIO descriptors whose values will be read
4487 * @array_info: information on applicability of fast bitmap processing path
4488 * @value_bitmap: bitmap to store the read values
4490 * Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
4491 * into account. Return 0 in case of success, else an error code.
4493 * This function is to be called from contexts that can sleep.
4495 int gpiod_get_array_value_cansleep(unsigned int array_size,
4496 struct gpio_desc **desc_array,
4497 struct gpio_array *array_info,
4498 unsigned long *value_bitmap)
4500 might_sleep_if(extra_checks);
4503 return gpiod_get_array_value_complex(false, true, array_size,
4504 desc_array, array_info,
4507 EXPORT_SYMBOL_GPL(gpiod_get_array_value_cansleep);
4510 * gpiod_set_raw_value_cansleep() - assign a gpio's raw value
4511 * @desc: gpio whose value will be assigned
4512 * @value: value to assign
4514 * Set the raw value of the GPIO, i.e. the value of its physical line without
4515 * regard for its ACTIVE_LOW status.
4517 * This function is to be called from contexts that can sleep.
4519 void gpiod_set_raw_value_cansleep(struct gpio_desc *desc, int value)
4521 might_sleep_if(extra_checks);
4522 VALIDATE_DESC_VOID(desc);
4523 gpiod_set_raw_value_commit(desc, value);
4525 EXPORT_SYMBOL_GPL(gpiod_set_raw_value_cansleep);
4528 * gpiod_set_value_cansleep() - assign a gpio's value
4529 * @desc: gpio whose value will be assigned
4530 * @value: value to assign
4532 * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
4535 * This function is to be called from contexts that can sleep.
4537 void gpiod_set_value_cansleep(struct gpio_desc *desc, int value)
4539 might_sleep_if(extra_checks);
4540 VALIDATE_DESC_VOID(desc);
4541 gpiod_set_value_nocheck(desc, value);
4543 EXPORT_SYMBOL_GPL(gpiod_set_value_cansleep);
4546 * gpiod_set_raw_array_value_cansleep() - assign values to an array of GPIOs
4547 * @array_size: number of elements in the descriptor array / value bitmap
4548 * @desc_array: array of GPIO descriptors whose values will be assigned
4549 * @array_info: information on applicability of fast bitmap processing path
4550 * @value_bitmap: bitmap of values to assign
4552 * Set the raw values of the GPIOs, i.e. the values of the physical lines
4553 * without regard for their ACTIVE_LOW status.
4555 * This function is to be called from contexts that can sleep.
4557 int gpiod_set_raw_array_value_cansleep(unsigned int array_size,
4558 struct gpio_desc **desc_array,
4559 struct gpio_array *array_info,
4560 unsigned long *value_bitmap)
4562 might_sleep_if(extra_checks);
4565 return gpiod_set_array_value_complex(true, true, array_size, desc_array,
4566 array_info, value_bitmap);
4568 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value_cansleep);
4571 * gpiod_add_lookup_tables() - register GPIO device consumers
4572 * @tables: list of tables of consumers to register
4573 * @n: number of tables in the list
4575 void gpiod_add_lookup_tables(struct gpiod_lookup_table **tables, size_t n)
4579 mutex_lock(&gpio_lookup_lock);
4581 for (i = 0; i < n; i++)
4582 list_add_tail(&tables[i]->list, &gpio_lookup_list);
4584 mutex_unlock(&gpio_lookup_lock);
4588 * gpiod_set_array_value_cansleep() - assign values to an array of GPIOs
4589 * @array_size: number of elements in the descriptor array / value bitmap
4590 * @desc_array: array of GPIO descriptors whose values will be assigned
4591 * @array_info: information on applicability of fast bitmap processing path
4592 * @value_bitmap: bitmap of values to assign
4594 * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
4597 * This function is to be called from contexts that can sleep.
4599 int gpiod_set_array_value_cansleep(unsigned int array_size,
4600 struct gpio_desc **desc_array,
4601 struct gpio_array *array_info,
4602 unsigned long *value_bitmap)
4604 might_sleep_if(extra_checks);
4607 return gpiod_set_array_value_complex(false, true, array_size,
4608 desc_array, array_info,
4611 EXPORT_SYMBOL_GPL(gpiod_set_array_value_cansleep);
4614 * gpiod_add_lookup_table() - register GPIO device consumers
4615 * @table: table of consumers to register
4617 void gpiod_add_lookup_table(struct gpiod_lookup_table *table)
4619 mutex_lock(&gpio_lookup_lock);
4621 list_add_tail(&table->list, &gpio_lookup_list);
4623 mutex_unlock(&gpio_lookup_lock);
4625 EXPORT_SYMBOL_GPL(gpiod_add_lookup_table);
4628 * gpiod_remove_lookup_table() - unregister GPIO device consumers
4629 * @table: table of consumers to unregister
4631 void gpiod_remove_lookup_table(struct gpiod_lookup_table *table)
4633 mutex_lock(&gpio_lookup_lock);
4635 list_del(&table->list);
4637 mutex_unlock(&gpio_lookup_lock);
4639 EXPORT_SYMBOL_GPL(gpiod_remove_lookup_table);
4642 * gpiod_add_hogs() - register a set of GPIO hogs from machine code
4643 * @hogs: table of gpio hog entries with a zeroed sentinel at the end
4645 void gpiod_add_hogs(struct gpiod_hog *hogs)
4647 struct gpio_chip *gc;
4648 struct gpiod_hog *hog;
4650 mutex_lock(&gpio_machine_hogs_mutex);
4652 for (hog = &hogs[0]; hog->chip_label; hog++) {
4653 list_add_tail(&hog->list, &gpio_machine_hogs);
4656 * The chip may have been registered earlier, so check if it
4657 * exists and, if so, try to hog the line now.
4659 gc = find_chip_by_name(hog->chip_label);
4661 gpiochip_machine_hog(gc, hog);
4664 mutex_unlock(&gpio_machine_hogs_mutex);
4666 EXPORT_SYMBOL_GPL(gpiod_add_hogs);
4668 static struct gpiod_lookup_table *gpiod_find_lookup_table(struct device *dev)
4670 const char *dev_id = dev ? dev_name(dev) : NULL;
4671 struct gpiod_lookup_table *table;
4673 mutex_lock(&gpio_lookup_lock);
4675 list_for_each_entry(table, &gpio_lookup_list, list) {
4676 if (table->dev_id && dev_id) {
4678 * Valid strings on both ends, must be identical to have
4681 if (!strcmp(table->dev_id, dev_id))
4685 * One of the pointers is NULL, so both must be to have
4688 if (dev_id == table->dev_id)
4695 mutex_unlock(&gpio_lookup_lock);
4699 static struct gpio_desc *gpiod_find(struct device *dev, const char *con_id,
4700 unsigned int idx, unsigned long *flags)
4702 struct gpio_desc *desc = ERR_PTR(-ENOENT);
4703 struct gpiod_lookup_table *table;
4704 struct gpiod_lookup *p;
4706 table = gpiod_find_lookup_table(dev);
4710 for (p = &table->table[0]; p->key; p++) {
4711 struct gpio_chip *gc;
4713 /* idx must always match exactly */
4717 /* If the lookup entry has a con_id, require exact match */
4718 if (p->con_id && (!con_id || strcmp(p->con_id, con_id)))
4721 if (p->chip_hwnum == U16_MAX) {
4722 desc = gpio_name_to_desc(p->key);
4728 dev_warn(dev, "cannot find GPIO line %s, deferring\n",
4730 return ERR_PTR(-EPROBE_DEFER);
4733 gc = find_chip_by_name(p->key);
4737 * As the lookup table indicates a chip with
4738 * p->key should exist, assume it may
4739 * still appear later and let the interested
4740 * consumer be probed again or let the Deferred
4741 * Probe infrastructure handle the error.
4743 dev_warn(dev, "cannot find GPIO chip %s, deferring\n",
4745 return ERR_PTR(-EPROBE_DEFER);
4748 if (gc->ngpio <= p->chip_hwnum) {
4750 "requested GPIO %u (%u) is out of range [0..%u] for chip %s\n",
4751 idx, p->chip_hwnum, gc->ngpio - 1,
4753 return ERR_PTR(-EINVAL);
4756 desc = gpiochip_get_desc(gc, p->chip_hwnum);
4765 static int platform_gpio_count(struct device *dev, const char *con_id)
4767 struct gpiod_lookup_table *table;
4768 struct gpiod_lookup *p;
4769 unsigned int count = 0;
4771 table = gpiod_find_lookup_table(dev);
4775 for (p = &table->table[0]; p->key; p++) {
4776 if ((con_id && p->con_id && !strcmp(con_id, p->con_id)) ||
4777 (!con_id && !p->con_id))
4787 * fwnode_gpiod_get_index - obtain a GPIO from firmware node
4788 * @fwnode: handle of the firmware node
4789 * @con_id: function within the GPIO consumer
4790 * @index: index of the GPIO to obtain for the consumer
4791 * @flags: GPIO initialization flags
4792 * @label: label to attach to the requested GPIO
4794 * This function can be used for drivers that get their configuration
4795 * from opaque firmware.
4797 * The function properly finds the corresponding GPIO using whatever is the
4798 * underlying firmware interface and then makes sure that the GPIO
4799 * descriptor is requested before it is returned to the caller.
4802 * On successful request the GPIO pin is configured in accordance with
4805 * In case of error an ERR_PTR() is returned.
4807 struct gpio_desc *fwnode_gpiod_get_index(struct fwnode_handle *fwnode,
4808 const char *con_id, int index,
4809 enum gpiod_flags flags,
4812 struct gpio_desc *desc;
4813 char prop_name[32]; /* 32 is max size of property name */
4816 for (i = 0; i < ARRAY_SIZE(gpio_suffixes); i++) {
4818 snprintf(prop_name, sizeof(prop_name), "%s-%s",
4819 con_id, gpio_suffixes[i]);
4821 snprintf(prop_name, sizeof(prop_name), "%s",
4824 desc = fwnode_get_named_gpiod(fwnode, prop_name, index, flags,
4826 if (!IS_ERR(desc) || (PTR_ERR(desc) != -ENOENT))
4832 EXPORT_SYMBOL_GPL(fwnode_gpiod_get_index);
4835 * gpiod_count - return the number of GPIOs associated with a device / function
4836 * or -ENOENT if no GPIO has been assigned to the requested function
4837 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4838 * @con_id: function within the GPIO consumer
4840 int gpiod_count(struct device *dev, const char *con_id)
4842 int count = -ENOENT;
4844 if (IS_ENABLED(CONFIG_OF) && dev && dev->of_node)
4845 count = of_gpio_get_count(dev, con_id);
4846 else if (IS_ENABLED(CONFIG_ACPI) && dev && ACPI_HANDLE(dev))
4847 count = acpi_gpio_count(dev, con_id);
4850 count = platform_gpio_count(dev, con_id);
4854 EXPORT_SYMBOL_GPL(gpiod_count);
4857 * gpiod_get - obtain a GPIO for a given GPIO function
4858 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4859 * @con_id: function within the GPIO consumer
4860 * @flags: optional GPIO initialization flags
4862 * Return the GPIO descriptor corresponding to the function con_id of device
4863 * dev, -ENOENT if no GPIO has been assigned to the requested function, or
4864 * another IS_ERR() code if an error occurred while trying to acquire the GPIO.
4866 struct gpio_desc *__must_check gpiod_get(struct device *dev, const char *con_id,
4867 enum gpiod_flags flags)
4869 return gpiod_get_index(dev, con_id, 0, flags);
4871 EXPORT_SYMBOL_GPL(gpiod_get);
4874 * gpiod_get_optional - obtain an optional GPIO for a given GPIO function
4875 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4876 * @con_id: function within the GPIO consumer
4877 * @flags: optional GPIO initialization flags
4879 * This is equivalent to gpiod_get(), except that when no GPIO was assigned to
4880 * the requested function it will return NULL. This is convenient for drivers
4881 * that need to handle optional GPIOs.
4883 struct gpio_desc *__must_check gpiod_get_optional(struct device *dev,
4885 enum gpiod_flags flags)
4887 return gpiod_get_index_optional(dev, con_id, 0, flags);
4889 EXPORT_SYMBOL_GPL(gpiod_get_optional);
4893 * gpiod_configure_flags - helper function to configure a given GPIO
4894 * @desc: gpio whose value will be assigned
4895 * @con_id: function within the GPIO consumer
4896 * @lflags: bitmask of gpio_lookup_flags GPIO_* values - returned from
4897 * of_find_gpio() or of_get_gpio_hog()
4898 * @dflags: gpiod_flags - optional GPIO initialization flags
4900 * Return 0 on success, -ENOENT if no GPIO has been assigned to the
4901 * requested function and/or index, or another IS_ERR() code if an error
4902 * occurred while trying to acquire the GPIO.
4904 int gpiod_configure_flags(struct gpio_desc *desc, const char *con_id,
4905 unsigned long lflags, enum gpiod_flags dflags)
4909 if (lflags & GPIO_ACTIVE_LOW)
4910 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
4912 if (lflags & GPIO_OPEN_DRAIN)
4913 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
4914 else if (dflags & GPIOD_FLAGS_BIT_OPEN_DRAIN) {
4916 * This enforces open drain mode from the consumer side.
4917 * This is necessary for some busses like I2C, but the lookup
4918 * should *REALLY* have specified them as open drain in the
4919 * first place, so print a little warning here.
4921 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
4923 "enforced open drain please flag it properly in DT/ACPI DSDT/board file\n");
4926 if (lflags & GPIO_OPEN_SOURCE)
4927 set_bit(FLAG_OPEN_SOURCE, &desc->flags);
4929 if ((lflags & GPIO_PULL_UP) && (lflags & GPIO_PULL_DOWN)) {
4931 "both pull-up and pull-down enabled, invalid configuration\n");
4935 if (lflags & GPIO_PULL_UP)
4936 set_bit(FLAG_PULL_UP, &desc->flags);
4937 else if (lflags & GPIO_PULL_DOWN)
4938 set_bit(FLAG_PULL_DOWN, &desc->flags);
4940 ret = gpiod_set_transitory(desc, (lflags & GPIO_TRANSITORY));
4944 /* No particular flag request, return here... */
4945 if (!(dflags & GPIOD_FLAGS_BIT_DIR_SET)) {
4946 gpiod_dbg(desc, "no flags found for %s\n", con_id);
4951 if (dflags & GPIOD_FLAGS_BIT_DIR_OUT)
4952 ret = gpiod_direction_output(desc,
4953 !!(dflags & GPIOD_FLAGS_BIT_DIR_VAL));
4955 ret = gpiod_direction_input(desc);
4961 * gpiod_get_index - obtain a GPIO from a multi-index GPIO function
4962 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4963 * @con_id: function within the GPIO consumer
4964 * @idx: index of the GPIO to obtain in the consumer
4965 * @flags: optional GPIO initialization flags
4967 * This variant of gpiod_get() allows to access GPIOs other than the first
4968 * defined one for functions that define several GPIOs.
4970 * Return a valid GPIO descriptor, -ENOENT if no GPIO has been assigned to the
4971 * requested function and/or index, or another IS_ERR() code if an error
4972 * occurred while trying to acquire the GPIO.
4974 struct gpio_desc *__must_check gpiod_get_index(struct device *dev,
4977 enum gpiod_flags flags)
4979 unsigned long lookupflags = GPIO_LOOKUP_FLAGS_DEFAULT;
4980 struct gpio_desc *desc = NULL;
4982 /* Maybe we have a device name, maybe not */
4983 const char *devname = dev ? dev_name(dev) : "?";
4985 dev_dbg(dev, "GPIO lookup for consumer %s\n", con_id);
4988 /* Using device tree? */
4989 if (IS_ENABLED(CONFIG_OF) && dev->of_node) {
4990 dev_dbg(dev, "using device tree for GPIO lookup\n");
4991 desc = of_find_gpio(dev, con_id, idx, &lookupflags);
4992 } else if (ACPI_COMPANION(dev)) {
4993 dev_dbg(dev, "using ACPI for GPIO lookup\n");
4994 desc = acpi_find_gpio(dev, con_id, idx, &flags, &lookupflags);
4999 * Either we are not using DT or ACPI, or their lookup did not return
5000 * a result. In that case, use platform lookup as a fallback.
5002 if (!desc || desc == ERR_PTR(-ENOENT)) {
5003 dev_dbg(dev, "using lookup tables for GPIO lookup\n");
5004 desc = gpiod_find(dev, con_id, idx, &lookupflags);
5008 dev_dbg(dev, "No GPIO consumer %s found\n", con_id);
5013 * If a connection label was passed use that, else attempt to use
5014 * the device name as label
5016 ret = gpiod_request(desc, con_id ? con_id : devname);
5018 if (ret == -EBUSY && flags & GPIOD_FLAGS_BIT_NONEXCLUSIVE) {
5020 * This happens when there are several consumers for
5021 * the same GPIO line: we just return here without
5022 * further initialization. It is a bit if a hack.
5023 * This is necessary to support fixed regulators.
5025 * FIXME: Make this more sane and safe.
5027 dev_info(dev, "nonexclusive access to GPIO for %s\n",
5028 con_id ? con_id : devname);
5031 return ERR_PTR(ret);
5035 ret = gpiod_configure_flags(desc, con_id, lookupflags, flags);
5037 dev_dbg(dev, "setup of GPIO %s failed\n", con_id);
5039 return ERR_PTR(ret);
5042 atomic_notifier_call_chain(&desc->gdev->notifier,
5043 GPIOLINE_CHANGED_REQUESTED, desc);
5047 EXPORT_SYMBOL_GPL(gpiod_get_index);
5050 * fwnode_get_named_gpiod - obtain a GPIO from firmware node
5051 * @fwnode: handle of the firmware node
5052 * @propname: name of the firmware property representing the GPIO
5053 * @index: index of the GPIO to obtain for the consumer
5054 * @dflags: GPIO initialization flags
5055 * @label: label to attach to the requested GPIO
5057 * This function can be used for drivers that get their configuration
5058 * from opaque firmware.
5060 * The function properly finds the corresponding GPIO using whatever is the
5061 * underlying firmware interface and then makes sure that the GPIO
5062 * descriptor is requested before it is returned to the caller.
5065 * On successful request the GPIO pin is configured in accordance with
5068 * In case of error an ERR_PTR() is returned.
5070 struct gpio_desc *fwnode_get_named_gpiod(struct fwnode_handle *fwnode,
5071 const char *propname, int index,
5072 enum gpiod_flags dflags,
5075 unsigned long lflags = GPIO_LOOKUP_FLAGS_DEFAULT;
5076 struct gpio_desc *desc = ERR_PTR(-ENODEV);
5080 return ERR_PTR(-EINVAL);
5082 if (is_of_node(fwnode)) {
5083 desc = gpiod_get_from_of_node(to_of_node(fwnode),
5088 } else if (is_acpi_node(fwnode)) {
5089 struct acpi_gpio_info info;
5091 desc = acpi_node_get_gpiod(fwnode, propname, index, &info);
5095 acpi_gpio_update_gpiod_flags(&dflags, &info);
5096 acpi_gpio_update_gpiod_lookup_flags(&lflags, &info);
5099 /* Currently only ACPI takes this path */
5100 ret = gpiod_request(desc, label);
5102 return ERR_PTR(ret);
5104 ret = gpiod_configure_flags(desc, propname, lflags, dflags);
5107 return ERR_PTR(ret);
5110 atomic_notifier_call_chain(&desc->gdev->notifier,
5111 GPIOLINE_CHANGED_REQUESTED, desc);
5115 EXPORT_SYMBOL_GPL(fwnode_get_named_gpiod);
5118 * gpiod_get_index_optional - obtain an optional GPIO from a multi-index GPIO
5120 * @dev: GPIO consumer, can be NULL for system-global GPIOs
5121 * @con_id: function within the GPIO consumer
5122 * @index: index of the GPIO to obtain in the consumer
5123 * @flags: optional GPIO initialization flags
5125 * This is equivalent to gpiod_get_index(), except that when no GPIO with the
5126 * specified index was assigned to the requested function it will return NULL.
5127 * This is convenient for drivers that need to handle optional GPIOs.
5129 struct gpio_desc *__must_check gpiod_get_index_optional(struct device *dev,
5132 enum gpiod_flags flags)
5134 struct gpio_desc *desc;
5136 desc = gpiod_get_index(dev, con_id, index, flags);
5138 if (PTR_ERR(desc) == -ENOENT)
5144 EXPORT_SYMBOL_GPL(gpiod_get_index_optional);
5147 * gpiod_hog - Hog the specified GPIO desc given the provided flags
5148 * @desc: gpio whose value will be assigned
5149 * @name: gpio line name
5150 * @lflags: bitmask of gpio_lookup_flags GPIO_* values - returned from
5151 * of_find_gpio() or of_get_gpio_hog()
5152 * @dflags: gpiod_flags - optional GPIO initialization flags
5154 int gpiod_hog(struct gpio_desc *desc, const char *name,
5155 unsigned long lflags, enum gpiod_flags dflags)
5157 struct gpio_chip *gc;
5158 struct gpio_desc *local_desc;
5162 gc = gpiod_to_chip(desc);
5163 hwnum = gpio_chip_hwgpio(desc);
5165 local_desc = gpiochip_request_own_desc(gc, hwnum, name,
5167 if (IS_ERR(local_desc)) {
5168 ret = PTR_ERR(local_desc);
5169 pr_err("requesting hog GPIO %s (chip %s, offset %d) failed, %d\n",
5170 name, gc->label, hwnum, ret);
5174 /* Mark GPIO as hogged so it can be identified and removed later */
5175 set_bit(FLAG_IS_HOGGED, &desc->flags);
5177 gpiod_info(desc, "hogged as %s%s\n",
5178 (dflags & GPIOD_FLAGS_BIT_DIR_OUT) ? "output" : "input",
5179 (dflags & GPIOD_FLAGS_BIT_DIR_OUT) ?
5180 (dflags & GPIOD_FLAGS_BIT_DIR_VAL) ? "/high" : "/low" : "");
5186 * gpiochip_free_hogs - Scan gpio-controller chip and release GPIO hog
5187 * @gc: gpio chip to act on
5189 static void gpiochip_free_hogs(struct gpio_chip *gc)
5193 for (id = 0; id < gc->ngpio; id++) {
5194 if (test_bit(FLAG_IS_HOGGED, &gc->gpiodev->descs[id].flags))
5195 gpiochip_free_own_desc(&gc->gpiodev->descs[id]);
5200 * gpiod_get_array - obtain multiple GPIOs from a multi-index GPIO function
5201 * @dev: GPIO consumer, can be NULL for system-global GPIOs
5202 * @con_id: function within the GPIO consumer
5203 * @flags: optional GPIO initialization flags
5205 * This function acquires all the GPIOs defined under a given function.
5207 * Return a struct gpio_descs containing an array of descriptors, -ENOENT if
5208 * no GPIO has been assigned to the requested function, or another IS_ERR()
5209 * code if an error occurred while trying to acquire the GPIOs.
5211 struct gpio_descs *__must_check gpiod_get_array(struct device *dev,
5213 enum gpiod_flags flags)
5215 struct gpio_desc *desc;
5216 struct gpio_descs *descs;
5217 struct gpio_array *array_info = NULL;
5218 struct gpio_chip *gc;
5219 int count, bitmap_size;
5221 count = gpiod_count(dev, con_id);
5223 return ERR_PTR(count);
5225 descs = kzalloc(struct_size(descs, desc, count), GFP_KERNEL);
5227 return ERR_PTR(-ENOMEM);
5229 for (descs->ndescs = 0; descs->ndescs < count; ) {
5230 desc = gpiod_get_index(dev, con_id, descs->ndescs, flags);
5232 gpiod_put_array(descs);
5233 return ERR_CAST(desc);
5236 descs->desc[descs->ndescs] = desc;
5238 gc = gpiod_to_chip(desc);
5240 * If pin hardware number of array member 0 is also 0, select
5241 * its chip as a candidate for fast bitmap processing path.
5243 if (descs->ndescs == 0 && gpio_chip_hwgpio(desc) == 0) {
5244 struct gpio_descs *array;
5246 bitmap_size = BITS_TO_LONGS(gc->ngpio > count ?
5249 array = kzalloc(struct_size(descs, desc, count) +
5250 struct_size(array_info, invert_mask,
5251 3 * bitmap_size), GFP_KERNEL);
5253 gpiod_put_array(descs);
5254 return ERR_PTR(-ENOMEM);
5257 memcpy(array, descs,
5258 struct_size(descs, desc, descs->ndescs + 1));
5262 array_info = (void *)(descs->desc + count);
5263 array_info->get_mask = array_info->invert_mask +
5265 array_info->set_mask = array_info->get_mask +
5268 array_info->desc = descs->desc;
5269 array_info->size = count;
5270 array_info->chip = gc;
5271 bitmap_set(array_info->get_mask, descs->ndescs,
5272 count - descs->ndescs);
5273 bitmap_set(array_info->set_mask, descs->ndescs,
5274 count - descs->ndescs);
5275 descs->info = array_info;
5277 /* Unmark array members which don't belong to the 'fast' chip */
5278 if (array_info && array_info->chip != gc) {
5279 __clear_bit(descs->ndescs, array_info->get_mask);
5280 __clear_bit(descs->ndescs, array_info->set_mask);
5283 * Detect array members which belong to the 'fast' chip
5284 * but their pins are not in hardware order.
5286 else if (array_info &&
5287 gpio_chip_hwgpio(desc) != descs->ndescs) {
5289 * Don't use fast path if all array members processed so
5290 * far belong to the same chip as this one but its pin
5291 * hardware number is different from its array index.
5293 if (bitmap_full(array_info->get_mask, descs->ndescs)) {
5296 __clear_bit(descs->ndescs,
5297 array_info->get_mask);
5298 __clear_bit(descs->ndescs,
5299 array_info->set_mask);
5301 } else if (array_info) {
5302 /* Exclude open drain or open source from fast output */
5303 if (gpiochip_line_is_open_drain(gc, descs->ndescs) ||
5304 gpiochip_line_is_open_source(gc, descs->ndescs))
5305 __clear_bit(descs->ndescs,
5306 array_info->set_mask);
5307 /* Identify 'fast' pins which require invertion */
5308 if (gpiod_is_active_low(desc))
5309 __set_bit(descs->ndescs,
5310 array_info->invert_mask);
5317 "GPIO array info: chip=%s, size=%d, get_mask=%lx, set_mask=%lx, invert_mask=%lx\n",
5318 array_info->chip->label, array_info->size,
5319 *array_info->get_mask, *array_info->set_mask,
5320 *array_info->invert_mask);
5323 EXPORT_SYMBOL_GPL(gpiod_get_array);
5326 * gpiod_get_array_optional - obtain multiple GPIOs from a multi-index GPIO
5328 * @dev: GPIO consumer, can be NULL for system-global GPIOs
5329 * @con_id: function within the GPIO consumer
5330 * @flags: optional GPIO initialization flags
5332 * This is equivalent to gpiod_get_array(), except that when no GPIO was
5333 * assigned to the requested function it will return NULL.
5335 struct gpio_descs *__must_check gpiod_get_array_optional(struct device *dev,
5337 enum gpiod_flags flags)
5339 struct gpio_descs *descs;
5341 descs = gpiod_get_array(dev, con_id, flags);
5342 if (PTR_ERR(descs) == -ENOENT)
5347 EXPORT_SYMBOL_GPL(gpiod_get_array_optional);
5350 * gpiod_put - dispose of a GPIO descriptor
5351 * @desc: GPIO descriptor to dispose of
5353 * No descriptor can be used after gpiod_put() has been called on it.
5355 void gpiod_put(struct gpio_desc *desc)
5360 EXPORT_SYMBOL_GPL(gpiod_put);
5363 * gpiod_put_array - dispose of multiple GPIO descriptors
5364 * @descs: struct gpio_descs containing an array of descriptors
5366 void gpiod_put_array(struct gpio_descs *descs)
5370 for (i = 0; i < descs->ndescs; i++)
5371 gpiod_put(descs->desc[i]);
5375 EXPORT_SYMBOL_GPL(gpiod_put_array);
5377 static int __init gpiolib_dev_init(void)
5381 /* Register GPIO sysfs bus */
5382 ret = bus_register(&gpio_bus_type);
5384 pr_err("gpiolib: could not register GPIO bus type\n");
5388 ret = alloc_chrdev_region(&gpio_devt, 0, GPIO_DEV_MAX, GPIOCHIP_NAME);
5390 pr_err("gpiolib: failed to allocate char dev region\n");
5391 bus_unregister(&gpio_bus_type);
5395 gpiolib_initialized = true;
5396 gpiochip_setup_devs();
5398 #if IS_ENABLED(CONFIG_OF_DYNAMIC) && IS_ENABLED(CONFIG_OF_GPIO)
5399 WARN_ON(of_reconfig_notifier_register(&gpio_of_notifier));
5400 #endif /* CONFIG_OF_DYNAMIC && CONFIG_OF_GPIO */
5404 core_initcall(gpiolib_dev_init);
5406 #ifdef CONFIG_DEBUG_FS
5408 static void gpiolib_dbg_show(struct seq_file *s, struct gpio_device *gdev)
5411 struct gpio_chip *gc = gdev->chip;
5412 unsigned gpio = gdev->base;
5413 struct gpio_desc *gdesc = &gdev->descs[0];
5418 for (i = 0; i < gdev->ngpio; i++, gpio++, gdesc++) {
5419 if (!test_bit(FLAG_REQUESTED, &gdesc->flags)) {
5421 seq_printf(s, " gpio-%-3d (%-20.20s)\n",
5427 gpiod_get_direction(gdesc);
5428 is_out = test_bit(FLAG_IS_OUT, &gdesc->flags);
5429 is_irq = test_bit(FLAG_USED_AS_IRQ, &gdesc->flags);
5430 active_low = test_bit(FLAG_ACTIVE_LOW, &gdesc->flags);
5431 seq_printf(s, " gpio-%-3d (%-20.20s|%-20.20s) %s %s %s%s",
5432 gpio, gdesc->name ? gdesc->name : "", gdesc->label,
5433 is_out ? "out" : "in ",
5434 gc->get ? (gc->get(gc, i) ? "hi" : "lo") : "? ",
5435 is_irq ? "IRQ " : "",
5436 active_low ? "ACTIVE LOW" : "");
5437 seq_printf(s, "\n");
5441 static void *gpiolib_seq_start(struct seq_file *s, loff_t *pos)
5443 unsigned long flags;
5444 struct gpio_device *gdev = NULL;
5445 loff_t index = *pos;
5449 spin_lock_irqsave(&gpio_lock, flags);
5450 list_for_each_entry(gdev, &gpio_devices, list)
5452 spin_unlock_irqrestore(&gpio_lock, flags);
5455 spin_unlock_irqrestore(&gpio_lock, flags);
5460 static void *gpiolib_seq_next(struct seq_file *s, void *v, loff_t *pos)
5462 unsigned long flags;
5463 struct gpio_device *gdev = v;
5466 spin_lock_irqsave(&gpio_lock, flags);
5467 if (list_is_last(&gdev->list, &gpio_devices))
5470 ret = list_entry(gdev->list.next, struct gpio_device, list);
5471 spin_unlock_irqrestore(&gpio_lock, flags);
5479 static void gpiolib_seq_stop(struct seq_file *s, void *v)
5483 static int gpiolib_seq_show(struct seq_file *s, void *v)
5485 struct gpio_device *gdev = v;
5486 struct gpio_chip *gc = gdev->chip;
5487 struct device *parent;
5490 seq_printf(s, "%s%s: (dangling chip)", (char *)s->private,
5491 dev_name(&gdev->dev));
5495 seq_printf(s, "%s%s: GPIOs %d-%d", (char *)s->private,
5496 dev_name(&gdev->dev),
5497 gdev->base, gdev->base + gdev->ngpio - 1);
5498 parent = gc->parent;
5500 seq_printf(s, ", parent: %s/%s",
5501 parent->bus ? parent->bus->name : "no-bus",
5504 seq_printf(s, ", %s", gc->label);
5506 seq_printf(s, ", can sleep");
5507 seq_printf(s, ":\n");
5510 gc->dbg_show(s, gc);
5512 gpiolib_dbg_show(s, gdev);
5517 static const struct seq_operations gpiolib_seq_ops = {
5518 .start = gpiolib_seq_start,
5519 .next = gpiolib_seq_next,
5520 .stop = gpiolib_seq_stop,
5521 .show = gpiolib_seq_show,
5524 static int gpiolib_open(struct inode *inode, struct file *file)
5526 return seq_open(file, &gpiolib_seq_ops);
5529 static const struct file_operations gpiolib_operations = {
5530 .owner = THIS_MODULE,
5531 .open = gpiolib_open,
5533 .llseek = seq_lseek,
5534 .release = seq_release,
5537 static int __init gpiolib_debugfs_init(void)
5539 /* /sys/kernel/debug/gpio */
5540 debugfs_create_file("gpio", S_IFREG | S_IRUGO, NULL, NULL,
5541 &gpiolib_operations);
5544 subsys_initcall(gpiolib_debugfs_init);
5546 #endif /* DEBUG_FS */