1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/bitmap.h>
3 #include <linux/kernel.h>
4 #include <linux/module.h>
5 #include <linux/interrupt.h>
7 #include <linux/spinlock.h>
8 #include <linux/list.h>
9 #include <linux/device.h>
10 #include <linux/err.h>
11 #include <linux/debugfs.h>
12 #include <linux/seq_file.h>
13 #include <linux/gpio.h>
14 #include <linux/idr.h>
15 #include <linux/slab.h>
16 #include <linux/acpi.h>
17 #include <linux/gpio/driver.h>
18 #include <linux/gpio/machine.h>
19 #include <linux/pinctrl/consumer.h>
20 #include <linux/cdev.h>
22 #include <linux/uaccess.h>
23 #include <linux/compat.h>
24 #include <linux/anon_inodes.h>
25 #include <linux/file.h>
26 #include <linux/kfifo.h>
27 #include <linux/poll.h>
28 #include <linux/timekeeping.h>
29 #include <uapi/linux/gpio.h>
32 #include "gpiolib-of.h"
33 #include "gpiolib-acpi.h"
35 #define CREATE_TRACE_POINTS
36 #include <trace/events/gpio.h>
38 /* Implementation infrastructure for GPIO interfaces.
40 * The GPIO programming interface allows for inlining speed-critical
41 * get/set operations for common cases, so that access to SOC-integrated
42 * GPIOs can sometimes cost only an instruction or two per bit.
46 /* When debugging, extend minimal trust to callers and platform code.
47 * Also emit diagnostic messages that may help initial bringup, when
48 * board setup or driver bugs are most common.
50 * Otherwise, minimize overhead in what may be bitbanging codepaths.
53 #define extra_checks 1
55 #define extra_checks 0
58 /* Device and char device-related information */
59 static DEFINE_IDA(gpio_ida);
60 static dev_t gpio_devt;
61 #define GPIO_DEV_MAX 256 /* 256 GPIO chip devices supported */
62 static struct bus_type gpio_bus_type = {
67 * Number of GPIOs to use for the fast path in set array
69 #define FASTPATH_NGPIO CONFIG_GPIOLIB_FASTPATH_LIMIT
71 /* gpio_lock prevents conflicts during gpio_desc[] table updates.
72 * While any GPIO is requested, its gpio_chip is not removable;
73 * each GPIO's "requested" flag serves as a lock and refcount.
75 DEFINE_SPINLOCK(gpio_lock);
77 static DEFINE_MUTEX(gpio_lookup_lock);
78 static LIST_HEAD(gpio_lookup_list);
79 LIST_HEAD(gpio_devices);
81 static DEFINE_MUTEX(gpio_machine_hogs_mutex);
82 static LIST_HEAD(gpio_machine_hogs);
84 static void gpiochip_free_hogs(struct gpio_chip *chip);
85 static int gpiochip_add_irqchip(struct gpio_chip *gpiochip,
86 struct lock_class_key *lock_key,
87 struct lock_class_key *request_key);
88 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip);
89 static int gpiochip_irqchip_init_hw(struct gpio_chip *gpiochip);
90 static int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gpiochip);
91 static void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gpiochip);
93 static bool gpiolib_initialized;
95 static inline void desc_set_label(struct gpio_desc *d, const char *label)
101 * gpio_to_desc - Convert a GPIO number to its descriptor
102 * @gpio: global GPIO number
105 * The GPIO descriptor associated with the given GPIO, or %NULL if no GPIO
106 * with the given number exists in the system.
108 struct gpio_desc *gpio_to_desc(unsigned gpio)
110 struct gpio_device *gdev;
113 spin_lock_irqsave(&gpio_lock, flags);
115 list_for_each_entry(gdev, &gpio_devices, list) {
116 if (gdev->base <= gpio &&
117 gdev->base + gdev->ngpio > gpio) {
118 spin_unlock_irqrestore(&gpio_lock, flags);
119 return &gdev->descs[gpio - gdev->base];
123 spin_unlock_irqrestore(&gpio_lock, flags);
125 if (!gpio_is_valid(gpio))
126 WARN(1, "invalid GPIO %d\n", gpio);
130 EXPORT_SYMBOL_GPL(gpio_to_desc);
133 * gpiochip_get_desc - get the GPIO descriptor corresponding to the given
134 * hardware number for this chip
136 * @hwnum: hardware number of the GPIO for this chip
139 * A pointer to the GPIO descriptor or %ERR_PTR(-EINVAL) if no GPIO exists
140 * in the given chip for the specified hardware number.
142 struct gpio_desc *gpiochip_get_desc(struct gpio_chip *chip,
145 struct gpio_device *gdev = chip->gpiodev;
147 if (hwnum >= gdev->ngpio)
148 return ERR_PTR(-EINVAL);
150 return &gdev->descs[hwnum];
154 * desc_to_gpio - convert a GPIO descriptor to the integer namespace
155 * @desc: GPIO descriptor
157 * This should disappear in the future but is needed since we still
158 * use GPIO numbers for error messages and sysfs nodes.
161 * The global GPIO number for the GPIO specified by its descriptor.
163 int desc_to_gpio(const struct gpio_desc *desc)
165 return desc->gdev->base + (desc - &desc->gdev->descs[0]);
167 EXPORT_SYMBOL_GPL(desc_to_gpio);
171 * gpiod_to_chip - Return the GPIO chip to which a GPIO descriptor belongs
172 * @desc: descriptor to return the chip of
174 struct gpio_chip *gpiod_to_chip(const struct gpio_desc *desc)
176 if (!desc || !desc->gdev)
178 return desc->gdev->chip;
180 EXPORT_SYMBOL_GPL(gpiod_to_chip);
182 /* dynamic allocation of GPIOs, e.g. on a hotplugged device */
183 static int gpiochip_find_base(int ngpio)
185 struct gpio_device *gdev;
186 int base = ARCH_NR_GPIOS - ngpio;
188 list_for_each_entry_reverse(gdev, &gpio_devices, list) {
189 /* found a free space? */
190 if (gdev->base + gdev->ngpio <= base)
193 /* nope, check the space right before the chip */
194 base = gdev->base - ngpio;
197 if (gpio_is_valid(base)) {
198 pr_debug("%s: found new base at %d\n", __func__, base);
201 pr_err("%s: cannot find free range\n", __func__);
207 * gpiod_get_direction - return the current direction of a GPIO
208 * @desc: GPIO to get the direction of
210 * Returns 0 for output, 1 for input, or an error code in case of error.
212 * This function may sleep if gpiod_cansleep() is true.
214 int gpiod_get_direction(struct gpio_desc *desc)
216 struct gpio_chip *chip;
220 chip = gpiod_to_chip(desc);
221 offset = gpio_chip_hwgpio(desc);
224 * Open drain emulation using input mode may incorrectly report
225 * input here, fix that up.
227 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags) &&
228 test_bit(FLAG_IS_OUT, &desc->flags))
231 if (!chip->get_direction)
234 ret = chip->get_direction(chip, offset);
238 /* GPIOF_DIR_IN or other positive, otherwise GPIOF_DIR_OUT */
242 assign_bit(FLAG_IS_OUT, &desc->flags, !ret);
246 EXPORT_SYMBOL_GPL(gpiod_get_direction);
249 * Add a new chip to the global chips list, keeping the list of chips sorted
250 * by range(means [base, base + ngpio - 1]) order.
252 * Return -EBUSY if the new chip overlaps with some other chip's integer
255 static int gpiodev_add_to_list(struct gpio_device *gdev)
257 struct gpio_device *prev, *next;
259 if (list_empty(&gpio_devices)) {
260 /* initial entry in list */
261 list_add_tail(&gdev->list, &gpio_devices);
265 next = list_entry(gpio_devices.next, struct gpio_device, list);
266 if (gdev->base + gdev->ngpio <= next->base) {
267 /* add before first entry */
268 list_add(&gdev->list, &gpio_devices);
272 prev = list_entry(gpio_devices.prev, struct gpio_device, list);
273 if (prev->base + prev->ngpio <= gdev->base) {
274 /* add behind last entry */
275 list_add_tail(&gdev->list, &gpio_devices);
279 list_for_each_entry_safe(prev, next, &gpio_devices, list) {
280 /* at the end of the list */
281 if (&next->list == &gpio_devices)
284 /* add between prev and next */
285 if (prev->base + prev->ngpio <= gdev->base
286 && gdev->base + gdev->ngpio <= next->base) {
287 list_add(&gdev->list, &prev->list);
292 dev_err(&gdev->dev, "GPIO integer space overlap, cannot add chip\n");
297 * Convert a GPIO name to its descriptor
299 static struct gpio_desc *gpio_name_to_desc(const char * const name)
301 struct gpio_device *gdev;
304 spin_lock_irqsave(&gpio_lock, flags);
306 list_for_each_entry(gdev, &gpio_devices, list) {
309 for (i = 0; i != gdev->ngpio; ++i) {
310 struct gpio_desc *desc = &gdev->descs[i];
312 if (!desc->name || !name)
315 if (!strcmp(desc->name, name)) {
316 spin_unlock_irqrestore(&gpio_lock, flags);
322 spin_unlock_irqrestore(&gpio_lock, flags);
328 * Takes the names from gc->names and checks if they are all unique. If they
329 * are, they are assigned to their gpio descriptors.
331 * Warning if one of the names is already used for a different GPIO.
333 static int gpiochip_set_desc_names(struct gpio_chip *gc)
335 struct gpio_device *gdev = gc->gpiodev;
341 /* First check all names if they are unique */
342 for (i = 0; i != gc->ngpio; ++i) {
343 struct gpio_desc *gpio;
345 gpio = gpio_name_to_desc(gc->names[i]);
348 "Detected name collision for GPIO name '%s'\n",
352 /* Then add all names to the GPIO descriptors */
353 for (i = 0; i != gc->ngpio; ++i)
354 gdev->descs[i].name = gc->names[i];
359 static unsigned long *gpiochip_allocate_mask(struct gpio_chip *chip)
363 p = bitmap_alloc(chip->ngpio, GFP_KERNEL);
367 /* Assume by default all GPIOs are valid */
368 bitmap_fill(p, chip->ngpio);
373 static int gpiochip_alloc_valid_mask(struct gpio_chip *gc)
375 if (!(of_gpio_need_valid_mask(gc) || gc->init_valid_mask))
378 gc->valid_mask = gpiochip_allocate_mask(gc);
385 static int gpiochip_init_valid_mask(struct gpio_chip *gc)
387 if (gc->init_valid_mask)
388 return gc->init_valid_mask(gc,
395 static void gpiochip_free_valid_mask(struct gpio_chip *gpiochip)
397 bitmap_free(gpiochip->valid_mask);
398 gpiochip->valid_mask = NULL;
401 static int gpiochip_add_pin_ranges(struct gpio_chip *gc)
403 if (gc->add_pin_ranges)
404 return gc->add_pin_ranges(gc);
409 bool gpiochip_line_is_valid(const struct gpio_chip *gpiochip,
412 /* No mask means all valid */
413 if (likely(!gpiochip->valid_mask))
415 return test_bit(offset, gpiochip->valid_mask);
417 EXPORT_SYMBOL_GPL(gpiochip_line_is_valid);
420 * GPIO line handle management
424 * struct linehandle_state - contains the state of a userspace handle
425 * @gdev: the GPIO device the handle pertains to
426 * @label: consumer label used to tag descriptors
427 * @descs: the GPIO descriptors held by this handle
428 * @numdescs: the number of descriptors held in the descs array
430 struct linehandle_state {
431 struct gpio_device *gdev;
433 struct gpio_desc *descs[GPIOHANDLES_MAX];
437 #define GPIOHANDLE_REQUEST_VALID_FLAGS \
438 (GPIOHANDLE_REQUEST_INPUT | \
439 GPIOHANDLE_REQUEST_OUTPUT | \
440 GPIOHANDLE_REQUEST_ACTIVE_LOW | \
441 GPIOHANDLE_REQUEST_BIAS_PULL_UP | \
442 GPIOHANDLE_REQUEST_BIAS_PULL_DOWN | \
443 GPIOHANDLE_REQUEST_BIAS_DISABLE | \
444 GPIOHANDLE_REQUEST_OPEN_DRAIN | \
445 GPIOHANDLE_REQUEST_OPEN_SOURCE)
447 static int linehandle_validate_flags(u32 flags)
449 /* Return an error if an unknown flag is set */
450 if (flags & ~GPIOHANDLE_REQUEST_VALID_FLAGS)
454 * Do not allow both INPUT & OUTPUT flags to be set as they are
457 if ((flags & GPIOHANDLE_REQUEST_INPUT) &&
458 (flags & GPIOHANDLE_REQUEST_OUTPUT))
462 * Do not allow OPEN_SOURCE & OPEN_DRAIN flags in a single request. If
463 * the hardware actually supports enabling both at the same time the
464 * electrical result would be disastrous.
466 if ((flags & GPIOHANDLE_REQUEST_OPEN_DRAIN) &&
467 (flags & GPIOHANDLE_REQUEST_OPEN_SOURCE))
470 /* OPEN_DRAIN and OPEN_SOURCE flags only make sense for output mode. */
471 if (!(flags & GPIOHANDLE_REQUEST_OUTPUT) &&
472 ((flags & GPIOHANDLE_REQUEST_OPEN_DRAIN) ||
473 (flags & GPIOHANDLE_REQUEST_OPEN_SOURCE)))
476 /* Bias flags only allowed for input or output mode. */
477 if (!((flags & GPIOHANDLE_REQUEST_INPUT) ||
478 (flags & GPIOHANDLE_REQUEST_OUTPUT)) &&
479 ((flags & GPIOHANDLE_REQUEST_BIAS_DISABLE) ||
480 (flags & GPIOHANDLE_REQUEST_BIAS_PULL_UP) ||
481 (flags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN)))
484 /* Only one bias flag can be set. */
485 if (((flags & GPIOHANDLE_REQUEST_BIAS_DISABLE) &&
486 (flags & (GPIOHANDLE_REQUEST_BIAS_PULL_DOWN |
487 GPIOHANDLE_REQUEST_BIAS_PULL_UP))) ||
488 ((flags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN) &&
489 (flags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)))
495 static long linehandle_set_config(struct linehandle_state *lh,
498 struct gpiohandle_config gcnf;
499 struct gpio_desc *desc;
502 unsigned long *flagsp;
504 if (copy_from_user(&gcnf, ip, sizeof(gcnf)))
508 ret = linehandle_validate_flags(lflags);
512 for (i = 0; i < lh->numdescs; i++) {
514 flagsp = &desc->flags;
516 assign_bit(FLAG_ACTIVE_LOW, flagsp,
517 lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW);
519 assign_bit(FLAG_OPEN_DRAIN, flagsp,
520 lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN);
522 assign_bit(FLAG_OPEN_SOURCE, flagsp,
523 lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE);
525 assign_bit(FLAG_PULL_UP, flagsp,
526 lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP);
528 assign_bit(FLAG_PULL_DOWN, flagsp,
529 lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN);
531 assign_bit(FLAG_BIAS_DISABLE, flagsp,
532 lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE);
535 * Lines have to be requested explicitly for input
536 * or output, else the line will be treated "as is".
538 if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
539 int val = !!gcnf.default_values[i];
541 ret = gpiod_direction_output(desc, val);
544 } else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
545 ret = gpiod_direction_input(desc);
550 atomic_notifier_call_chain(&desc->gdev->notifier,
551 GPIOLINE_CHANGED_CONFIG, desc);
556 static long linehandle_ioctl(struct file *filep, unsigned int cmd,
559 struct linehandle_state *lh = filep->private_data;
560 void __user *ip = (void __user *)arg;
561 struct gpiohandle_data ghd;
562 DECLARE_BITMAP(vals, GPIOHANDLES_MAX);
565 if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
566 /* NOTE: It's ok to read values of output lines. */
567 int ret = gpiod_get_array_value_complex(false,
576 memset(&ghd, 0, sizeof(ghd));
577 for (i = 0; i < lh->numdescs; i++)
578 ghd.values[i] = test_bit(i, vals);
580 if (copy_to_user(ip, &ghd, sizeof(ghd)))
584 } else if (cmd == GPIOHANDLE_SET_LINE_VALUES_IOCTL) {
586 * All line descriptors were created at once with the same
587 * flags so just check if the first one is really output.
589 if (!test_bit(FLAG_IS_OUT, &lh->descs[0]->flags))
592 if (copy_from_user(&ghd, ip, sizeof(ghd)))
595 /* Clamp all values to [0,1] */
596 for (i = 0; i < lh->numdescs; i++)
597 __assign_bit(i, vals, ghd.values[i]);
599 /* Reuse the array setting function */
600 return gpiod_set_array_value_complex(false,
606 } else if (cmd == GPIOHANDLE_SET_CONFIG_IOCTL) {
607 return linehandle_set_config(lh, ip);
613 static long linehandle_ioctl_compat(struct file *filep, unsigned int cmd,
616 return linehandle_ioctl(filep, cmd, (unsigned long)compat_ptr(arg));
620 static int linehandle_release(struct inode *inode, struct file *filep)
622 struct linehandle_state *lh = filep->private_data;
623 struct gpio_device *gdev = lh->gdev;
626 for (i = 0; i < lh->numdescs; i++)
627 gpiod_free(lh->descs[i]);
630 put_device(&gdev->dev);
634 static const struct file_operations linehandle_fileops = {
635 .release = linehandle_release,
636 .owner = THIS_MODULE,
637 .llseek = noop_llseek,
638 .unlocked_ioctl = linehandle_ioctl,
640 .compat_ioctl = linehandle_ioctl_compat,
644 static int linehandle_create(struct gpio_device *gdev, void __user *ip)
646 struct gpiohandle_request handlereq;
647 struct linehandle_state *lh;
649 int fd, i, count = 0, ret;
652 if (copy_from_user(&handlereq, ip, sizeof(handlereq)))
654 if ((handlereq.lines == 0) || (handlereq.lines > GPIOHANDLES_MAX))
657 lflags = handlereq.flags;
659 ret = linehandle_validate_flags(lflags);
663 lh = kzalloc(sizeof(*lh), GFP_KERNEL);
667 get_device(&gdev->dev);
669 /* Make sure this is terminated */
670 handlereq.consumer_label[sizeof(handlereq.consumer_label)-1] = '\0';
671 if (strlen(handlereq.consumer_label)) {
672 lh->label = kstrdup(handlereq.consumer_label,
680 /* Request each GPIO */
681 for (i = 0; i < handlereq.lines; i++) {
682 u32 offset = handlereq.lineoffsets[i];
683 struct gpio_desc *desc = gpiochip_get_desc(gdev->chip, offset);
690 ret = gpiod_request(desc, lh->label);
696 if (lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW)
697 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
698 if (lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN)
699 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
700 if (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE)
701 set_bit(FLAG_OPEN_SOURCE, &desc->flags);
702 if (lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE)
703 set_bit(FLAG_BIAS_DISABLE, &desc->flags);
704 if (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN)
705 set_bit(FLAG_PULL_DOWN, &desc->flags);
706 if (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)
707 set_bit(FLAG_PULL_UP, &desc->flags);
709 ret = gpiod_set_transitory(desc, false);
714 * Lines have to be requested explicitly for input
715 * or output, else the line will be treated "as is".
717 if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
718 int val = !!handlereq.default_values[i];
720 ret = gpiod_direction_output(desc, val);
723 } else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
724 ret = gpiod_direction_input(desc);
728 dev_dbg(&gdev->dev, "registered chardev handle for line %d\n",
731 /* Let i point at the last handle */
733 lh->numdescs = handlereq.lines;
735 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
741 file = anon_inode_getfile("gpio-linehandle",
744 O_RDONLY | O_CLOEXEC);
747 goto out_put_unused_fd;
751 if (copy_to_user(ip, &handlereq, sizeof(handlereq))) {
753 * fput() will trigger the release() callback, so do not go onto
754 * the regular error cleanup path here.
761 fd_install(fd, file);
763 dev_dbg(&gdev->dev, "registered chardev handle for %d lines\n",
771 for (i = 0; i < count; i++)
772 gpiod_free(lh->descs[i]);
776 put_device(&gdev->dev);
781 * GPIO line event management
785 * struct lineevent_state - contains the state of a userspace event
786 * @gdev: the GPIO device the event pertains to
787 * @label: consumer label used to tag descriptors
788 * @desc: the GPIO descriptor held by this event
789 * @eflags: the event flags this line was requested with
790 * @irq: the interrupt that trigger in response to events on this GPIO
791 * @wait: wait queue that handles blocking reads of events
792 * @events: KFIFO for the GPIO events
793 * @timestamp: cache for the timestamp storing it between hardirq
794 * and IRQ thread, used to bring the timestamp close to the actual
797 struct lineevent_state {
798 struct gpio_device *gdev;
800 struct gpio_desc *desc;
803 wait_queue_head_t wait;
804 DECLARE_KFIFO(events, struct gpioevent_data, 16);
808 #define GPIOEVENT_REQUEST_VALID_FLAGS \
809 (GPIOEVENT_REQUEST_RISING_EDGE | \
810 GPIOEVENT_REQUEST_FALLING_EDGE)
812 static __poll_t lineevent_poll(struct file *filep,
813 struct poll_table_struct *wait)
815 struct lineevent_state *le = filep->private_data;
818 poll_wait(filep, &le->wait, wait);
820 if (!kfifo_is_empty_spinlocked_noirqsave(&le->events, &le->wait.lock))
821 events = EPOLLIN | EPOLLRDNORM;
827 static ssize_t lineevent_read(struct file *filep,
832 struct lineevent_state *le = filep->private_data;
833 struct gpioevent_data event;
834 ssize_t bytes_read = 0;
837 if (count < sizeof(event))
841 spin_lock(&le->wait.lock);
842 if (kfifo_is_empty(&le->events)) {
844 spin_unlock(&le->wait.lock);
848 if (filep->f_flags & O_NONBLOCK) {
849 spin_unlock(&le->wait.lock);
853 ret = wait_event_interruptible_locked(le->wait,
854 !kfifo_is_empty(&le->events));
856 spin_unlock(&le->wait.lock);
861 ret = kfifo_out(&le->events, &event, 1);
862 spin_unlock(&le->wait.lock);
865 * This should never happen - we were holding the lock
866 * from the moment we learned the fifo is no longer
873 if (copy_to_user(buf + bytes_read, &event, sizeof(event)))
875 bytes_read += sizeof(event);
876 } while (count >= bytes_read + sizeof(event));
881 static int lineevent_release(struct inode *inode, struct file *filep)
883 struct lineevent_state *le = filep->private_data;
884 struct gpio_device *gdev = le->gdev;
886 free_irq(le->irq, le);
887 gpiod_free(le->desc);
890 put_device(&gdev->dev);
894 static long lineevent_ioctl(struct file *filep, unsigned int cmd,
897 struct lineevent_state *le = filep->private_data;
898 void __user *ip = (void __user *)arg;
899 struct gpiohandle_data ghd;
902 * We can get the value for an event line but not set it,
903 * because it is input by definition.
905 if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
908 memset(&ghd, 0, sizeof(ghd));
910 val = gpiod_get_value_cansleep(le->desc);
915 if (copy_to_user(ip, &ghd, sizeof(ghd)))
924 static long lineevent_ioctl_compat(struct file *filep, unsigned int cmd,
927 return lineevent_ioctl(filep, cmd, (unsigned long)compat_ptr(arg));
931 static const struct file_operations lineevent_fileops = {
932 .release = lineevent_release,
933 .read = lineevent_read,
934 .poll = lineevent_poll,
935 .owner = THIS_MODULE,
936 .llseek = noop_llseek,
937 .unlocked_ioctl = lineevent_ioctl,
939 .compat_ioctl = lineevent_ioctl_compat,
943 static irqreturn_t lineevent_irq_thread(int irq, void *p)
945 struct lineevent_state *le = p;
946 struct gpioevent_data ge;
949 /* Do not leak kernel stack to userspace */
950 memset(&ge, 0, sizeof(ge));
953 * We may be running from a nested threaded interrupt in which case
954 * we didn't get the timestamp from lineevent_irq_handler().
957 ge.timestamp = ktime_get_ns();
959 ge.timestamp = le->timestamp;
961 if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE
962 && le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
963 int level = gpiod_get_value_cansleep(le->desc);
965 /* Emit low-to-high event */
966 ge.id = GPIOEVENT_EVENT_RISING_EDGE;
968 /* Emit high-to-low event */
969 ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
970 } else if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE) {
971 /* Emit low-to-high event */
972 ge.id = GPIOEVENT_EVENT_RISING_EDGE;
973 } else if (le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
974 /* Emit high-to-low event */
975 ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
980 ret = kfifo_in_spinlocked_noirqsave(&le->events, &ge,
983 wake_up_poll(&le->wait, EPOLLIN);
985 pr_debug_ratelimited("event FIFO is full - event dropped\n");
990 static irqreturn_t lineevent_irq_handler(int irq, void *p)
992 struct lineevent_state *le = p;
995 * Just store the timestamp in hardirq context so we get it as
996 * close in time as possible to the actual event.
998 le->timestamp = ktime_get_ns();
1000 return IRQ_WAKE_THREAD;
1003 static int lineevent_create(struct gpio_device *gdev, void __user *ip)
1005 struct gpioevent_request eventreq;
1006 struct lineevent_state *le;
1007 struct gpio_desc *desc;
1016 if (copy_from_user(&eventreq, ip, sizeof(eventreq)))
1019 offset = eventreq.lineoffset;
1020 lflags = eventreq.handleflags;
1021 eflags = eventreq.eventflags;
1023 desc = gpiochip_get_desc(gdev->chip, offset);
1025 return PTR_ERR(desc);
1027 /* Return an error if a unknown flag is set */
1028 if ((lflags & ~GPIOHANDLE_REQUEST_VALID_FLAGS) ||
1029 (eflags & ~GPIOEVENT_REQUEST_VALID_FLAGS))
1032 /* This is just wrong: we don't look for events on output lines */
1033 if ((lflags & GPIOHANDLE_REQUEST_OUTPUT) ||
1034 (lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN) ||
1035 (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE))
1038 /* Only one bias flag can be set. */
1039 if (((lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE) &&
1040 (lflags & (GPIOHANDLE_REQUEST_BIAS_PULL_DOWN |
1041 GPIOHANDLE_REQUEST_BIAS_PULL_UP))) ||
1042 ((lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN) &&
1043 (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)))
1046 le = kzalloc(sizeof(*le), GFP_KERNEL);
1050 get_device(&gdev->dev);
1052 /* Make sure this is terminated */
1053 eventreq.consumer_label[sizeof(eventreq.consumer_label)-1] = '\0';
1054 if (strlen(eventreq.consumer_label)) {
1055 le->label = kstrdup(eventreq.consumer_label,
1063 ret = gpiod_request(desc, le->label);
1065 goto out_free_label;
1067 le->eflags = eflags;
1069 if (lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW)
1070 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
1071 if (lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE)
1072 set_bit(FLAG_BIAS_DISABLE, &desc->flags);
1073 if (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN)
1074 set_bit(FLAG_PULL_DOWN, &desc->flags);
1075 if (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)
1076 set_bit(FLAG_PULL_UP, &desc->flags);
1078 ret = gpiod_direction_input(desc);
1082 le->irq = gpiod_to_irq(desc);
1088 if (eflags & GPIOEVENT_REQUEST_RISING_EDGE)
1089 irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
1090 IRQF_TRIGGER_FALLING : IRQF_TRIGGER_RISING;
1091 if (eflags & GPIOEVENT_REQUEST_FALLING_EDGE)
1092 irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
1093 IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING;
1094 irqflags |= IRQF_ONESHOT;
1096 INIT_KFIFO(le->events);
1097 init_waitqueue_head(&le->wait);
1099 /* Request a thread to read the events */
1100 ret = request_threaded_irq(le->irq,
1101 lineevent_irq_handler,
1102 lineevent_irq_thread,
1109 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
1115 file = anon_inode_getfile("gpio-event",
1118 O_RDONLY | O_CLOEXEC);
1120 ret = PTR_ERR(file);
1121 goto out_put_unused_fd;
1125 if (copy_to_user(ip, &eventreq, sizeof(eventreq))) {
1127 * fput() will trigger the release() callback, so do not go onto
1128 * the regular error cleanup path here.
1135 fd_install(fd, file);
1142 free_irq(le->irq, le);
1144 gpiod_free(le->desc);
1149 put_device(&gdev->dev);
1153 static void gpio_desc_to_lineinfo(struct gpio_desc *desc,
1154 struct gpioline_info *info)
1156 struct gpio_chip *chip = desc->gdev->chip;
1157 unsigned long flags;
1159 spin_lock_irqsave(&gpio_lock, flags);
1162 strncpy(info->name, desc->name, sizeof(info->name));
1163 info->name[sizeof(info->name) - 1] = '\0';
1165 info->name[0] = '\0';
1169 strncpy(info->consumer, desc->label, sizeof(info->consumer));
1170 info->consumer[sizeof(info->consumer) - 1] = '\0';
1172 info->consumer[0] = '\0';
1176 * Userspace only need to know that the kernel is using this GPIO so
1180 if (test_bit(FLAG_REQUESTED, &desc->flags) ||
1181 test_bit(FLAG_IS_HOGGED, &desc->flags) ||
1182 test_bit(FLAG_USED_AS_IRQ, &desc->flags) ||
1183 test_bit(FLAG_EXPORT, &desc->flags) ||
1184 test_bit(FLAG_SYSFS, &desc->flags) ||
1185 !pinctrl_gpio_can_use_line(chip->base + info->line_offset))
1186 info->flags |= GPIOLINE_FLAG_KERNEL;
1187 if (test_bit(FLAG_IS_OUT, &desc->flags))
1188 info->flags |= GPIOLINE_FLAG_IS_OUT;
1189 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
1190 info->flags |= GPIOLINE_FLAG_ACTIVE_LOW;
1191 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
1192 info->flags |= (GPIOLINE_FLAG_OPEN_DRAIN |
1193 GPIOLINE_FLAG_IS_OUT);
1194 if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
1195 info->flags |= (GPIOLINE_FLAG_OPEN_SOURCE |
1196 GPIOLINE_FLAG_IS_OUT);
1197 if (test_bit(FLAG_BIAS_DISABLE, &desc->flags))
1198 info->flags |= GPIOLINE_FLAG_BIAS_DISABLE;
1199 if (test_bit(FLAG_PULL_DOWN, &desc->flags))
1200 info->flags |= GPIOLINE_FLAG_BIAS_PULL_DOWN;
1201 if (test_bit(FLAG_PULL_UP, &desc->flags))
1202 info->flags |= GPIOLINE_FLAG_BIAS_PULL_UP;
1204 spin_unlock_irqrestore(&gpio_lock, flags);
1207 struct gpio_chardev_data {
1208 struct gpio_device *gdev;
1209 wait_queue_head_t wait;
1210 DECLARE_KFIFO(events, struct gpioline_info_changed, 32);
1211 struct notifier_block lineinfo_changed_nb;
1212 unsigned long *watched_lines;
1216 * gpio_ioctl() - ioctl handler for the GPIO chardev
1218 static long gpio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1220 struct gpio_chardev_data *priv = filp->private_data;
1221 struct gpio_device *gdev = priv->gdev;
1222 struct gpio_chip *chip = gdev->chip;
1223 void __user *ip = (void __user *)arg;
1224 struct gpio_desc *desc;
1227 /* We fail any subsequent ioctl():s when the chip is gone */
1231 /* Fill in the struct and pass to userspace */
1232 if (cmd == GPIO_GET_CHIPINFO_IOCTL) {
1233 struct gpiochip_info chipinfo;
1235 memset(&chipinfo, 0, sizeof(chipinfo));
1237 strncpy(chipinfo.name, dev_name(&gdev->dev),
1238 sizeof(chipinfo.name));
1239 chipinfo.name[sizeof(chipinfo.name)-1] = '\0';
1240 strncpy(chipinfo.label, gdev->label,
1241 sizeof(chipinfo.label));
1242 chipinfo.label[sizeof(chipinfo.label)-1] = '\0';
1243 chipinfo.lines = gdev->ngpio;
1244 if (copy_to_user(ip, &chipinfo, sizeof(chipinfo)))
1247 } else if (cmd == GPIO_GET_LINEINFO_IOCTL ||
1248 cmd == GPIO_GET_LINEINFO_WATCH_IOCTL) {
1249 struct gpioline_info lineinfo;
1251 if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
1254 desc = gpiochip_get_desc(chip, lineinfo.line_offset);
1256 return PTR_ERR(desc);
1258 gpio_desc_to_lineinfo(desc, &lineinfo);
1260 if (copy_to_user(ip, &lineinfo, sizeof(lineinfo)))
1263 if (cmd == GPIO_GET_LINEINFO_WATCH_IOCTL)
1264 set_bit(desc_to_gpio(desc), priv->watched_lines);
1267 } else if (cmd == GPIO_GET_LINEHANDLE_IOCTL) {
1268 return linehandle_create(gdev, ip);
1269 } else if (cmd == GPIO_GET_LINEEVENT_IOCTL) {
1270 return lineevent_create(gdev, ip);
1271 } else if (cmd == GPIO_GET_LINEINFO_UNWATCH_IOCTL) {
1272 if (copy_from_user(&offset, ip, sizeof(offset)))
1275 desc = gpiochip_get_desc(chip, offset);
1277 return PTR_ERR(desc);
1279 clear_bit(desc_to_gpio(desc), &desc->flags);
1285 #ifdef CONFIG_COMPAT
1286 static long gpio_ioctl_compat(struct file *filp, unsigned int cmd,
1289 return gpio_ioctl(filp, cmd, (unsigned long)compat_ptr(arg));
1293 static struct gpio_chardev_data *
1294 to_gpio_chardev_data(struct notifier_block *nb)
1296 return container_of(nb, struct gpio_chardev_data, lineinfo_changed_nb);
1299 static int lineinfo_changed_notify(struct notifier_block *nb,
1300 unsigned long action, void *data)
1302 struct gpio_chardev_data *priv = to_gpio_chardev_data(nb);
1303 struct gpioline_info_changed chg;
1304 struct gpio_desc *desc = data;
1307 if (!test_bit(desc_to_gpio(desc), priv->watched_lines))
1310 memset(&chg, 0, sizeof(chg));
1311 chg.info.line_offset = gpio_chip_hwgpio(desc);
1312 chg.event_type = action;
1313 chg.timestamp = ktime_get_ns();
1314 gpio_desc_to_lineinfo(desc, &chg.info);
1316 ret = kfifo_in_spinlocked(&priv->events, &chg, 1, &priv->wait.lock);
1318 wake_up_poll(&priv->wait, EPOLLIN);
1320 pr_debug_ratelimited("lineinfo event FIFO is full - event dropped\n");
1325 static __poll_t lineinfo_watch_poll(struct file *filep,
1326 struct poll_table_struct *pollt)
1328 struct gpio_chardev_data *priv = filep->private_data;
1329 __poll_t events = 0;
1331 poll_wait(filep, &priv->wait, pollt);
1333 if (!kfifo_is_empty_spinlocked_noirqsave(&priv->events,
1335 events = EPOLLIN | EPOLLRDNORM;
1340 static ssize_t lineinfo_watch_read(struct file *filep, char __user *buf,
1341 size_t count, loff_t *off)
1343 struct gpio_chardev_data *priv = filep->private_data;
1344 struct gpioline_info_changed event;
1345 ssize_t bytes_read = 0;
1348 if (count < sizeof(event))
1352 spin_lock(&priv->wait.lock);
1353 if (kfifo_is_empty(&priv->events)) {
1355 spin_unlock(&priv->wait.lock);
1359 if (filep->f_flags & O_NONBLOCK) {
1360 spin_unlock(&priv->wait.lock);
1364 ret = wait_event_interruptible_locked(priv->wait,
1365 !kfifo_is_empty(&priv->events));
1367 spin_unlock(&priv->wait.lock);
1372 ret = kfifo_out(&priv->events, &event, 1);
1373 spin_unlock(&priv->wait.lock);
1377 /* We should never get here. See lineevent_read(). */
1380 if (copy_to_user(buf + bytes_read, &event, sizeof(event)))
1382 bytes_read += sizeof(event);
1383 } while (count >= bytes_read + sizeof(event));
1389 * gpio_chrdev_open() - open the chardev for ioctl operations
1390 * @inode: inode for this chardev
1391 * @filp: file struct for storing private data
1392 * Returns 0 on success
1394 static int gpio_chrdev_open(struct inode *inode, struct file *filp)
1396 struct gpio_device *gdev = container_of(inode->i_cdev,
1397 struct gpio_device, chrdev);
1398 struct gpio_chardev_data *priv;
1401 /* Fail on open if the backing gpiochip is gone */
1405 priv = kzalloc(sizeof(*priv), GFP_KERNEL);
1409 priv->watched_lines = bitmap_zalloc(gdev->chip->ngpio, GFP_KERNEL);
1410 if (!priv->watched_lines)
1413 init_waitqueue_head(&priv->wait);
1414 INIT_KFIFO(priv->events);
1417 priv->lineinfo_changed_nb.notifier_call = lineinfo_changed_notify;
1418 ret = atomic_notifier_chain_register(&gdev->notifier,
1419 &priv->lineinfo_changed_nb);
1421 goto out_free_bitmap;
1423 get_device(&gdev->dev);
1424 filp->private_data = priv;
1426 ret = nonseekable_open(inode, filp);
1428 goto out_unregister_notifier;
1432 out_unregister_notifier:
1433 atomic_notifier_chain_unregister(&gdev->notifier,
1434 &priv->lineinfo_changed_nb);
1436 bitmap_free(priv->watched_lines);
1443 * gpio_chrdev_release() - close chardev after ioctl operations
1444 * @inode: inode for this chardev
1445 * @filp: file struct for storing private data
1446 * Returns 0 on success
1448 static int gpio_chrdev_release(struct inode *inode, struct file *filp)
1450 struct gpio_chardev_data *priv = filp->private_data;
1451 struct gpio_device *gdev = priv->gdev;
1453 bitmap_free(priv->watched_lines);
1454 atomic_notifier_chain_unregister(&gdev->notifier,
1455 &priv->lineinfo_changed_nb);
1456 put_device(&gdev->dev);
1462 static const struct file_operations gpio_fileops = {
1463 .release = gpio_chrdev_release,
1464 .open = gpio_chrdev_open,
1465 .poll = lineinfo_watch_poll,
1466 .read = lineinfo_watch_read,
1467 .owner = THIS_MODULE,
1468 .llseek = no_llseek,
1469 .unlocked_ioctl = gpio_ioctl,
1470 #ifdef CONFIG_COMPAT
1471 .compat_ioctl = gpio_ioctl_compat,
1475 static void gpiodevice_release(struct device *dev)
1477 struct gpio_device *gdev = dev_get_drvdata(dev);
1479 list_del(&gdev->list);
1480 ida_simple_remove(&gpio_ida, gdev->id);
1481 kfree_const(gdev->label);
1486 static int gpiochip_setup_dev(struct gpio_device *gdev)
1490 cdev_init(&gdev->chrdev, &gpio_fileops);
1491 gdev->chrdev.owner = THIS_MODULE;
1492 gdev->dev.devt = MKDEV(MAJOR(gpio_devt), gdev->id);
1494 ret = cdev_device_add(&gdev->chrdev, &gdev->dev);
1498 chip_dbg(gdev->chip, "added GPIO chardev (%d:%d)\n",
1499 MAJOR(gpio_devt), gdev->id);
1501 ret = gpiochip_sysfs_register(gdev);
1503 goto err_remove_device;
1505 /* From this point, the .release() function cleans up gpio_device */
1506 gdev->dev.release = gpiodevice_release;
1507 pr_debug("%s: registered GPIOs %d to %d on device: %s (%s)\n",
1508 __func__, gdev->base, gdev->base + gdev->ngpio - 1,
1509 dev_name(&gdev->dev), gdev->chip->label ? : "generic");
1514 cdev_device_del(&gdev->chrdev, &gdev->dev);
1518 static void gpiochip_machine_hog(struct gpio_chip *chip, struct gpiod_hog *hog)
1520 struct gpio_desc *desc;
1523 desc = gpiochip_get_desc(chip, hog->chip_hwnum);
1525 pr_err("%s: unable to get GPIO desc: %ld\n",
1526 __func__, PTR_ERR(desc));
1530 if (test_bit(FLAG_IS_HOGGED, &desc->flags))
1533 rv = gpiod_hog(desc, hog->line_name, hog->lflags, hog->dflags);
1535 pr_err("%s: unable to hog GPIO line (%s:%u): %d\n",
1536 __func__, chip->label, hog->chip_hwnum, rv);
1539 static void machine_gpiochip_add(struct gpio_chip *chip)
1541 struct gpiod_hog *hog;
1543 mutex_lock(&gpio_machine_hogs_mutex);
1545 list_for_each_entry(hog, &gpio_machine_hogs, list) {
1546 if (!strcmp(chip->label, hog->chip_label))
1547 gpiochip_machine_hog(chip, hog);
1550 mutex_unlock(&gpio_machine_hogs_mutex);
1553 static void gpiochip_setup_devs(void)
1555 struct gpio_device *gdev;
1558 list_for_each_entry(gdev, &gpio_devices, list) {
1559 ret = gpiochip_setup_dev(gdev);
1561 pr_err("%s: Failed to initialize gpio device (%d)\n",
1562 dev_name(&gdev->dev), ret);
1566 int gpiochip_add_data_with_key(struct gpio_chip *chip, void *data,
1567 struct lock_class_key *lock_key,
1568 struct lock_class_key *request_key)
1570 unsigned long flags;
1573 int base = chip->base;
1574 struct gpio_device *gdev;
1577 * First: allocate and populate the internal stat container, and
1578 * set up the struct device.
1580 gdev = kzalloc(sizeof(*gdev), GFP_KERNEL);
1583 gdev->dev.bus = &gpio_bus_type;
1585 chip->gpiodev = gdev;
1587 gdev->dev.parent = chip->parent;
1588 gdev->dev.of_node = chip->parent->of_node;
1591 #ifdef CONFIG_OF_GPIO
1592 /* If the gpiochip has an assigned OF node this takes precedence */
1594 gdev->dev.of_node = chip->of_node;
1596 chip->of_node = gdev->dev.of_node;
1599 gdev->id = ida_simple_get(&gpio_ida, 0, 0, GFP_KERNEL);
1604 dev_set_name(&gdev->dev, GPIOCHIP_NAME "%d", gdev->id);
1605 device_initialize(&gdev->dev);
1606 dev_set_drvdata(&gdev->dev, gdev);
1607 if (chip->parent && chip->parent->driver)
1608 gdev->owner = chip->parent->driver->owner;
1609 else if (chip->owner)
1610 /* TODO: remove chip->owner */
1611 gdev->owner = chip->owner;
1613 gdev->owner = THIS_MODULE;
1615 gdev->descs = kcalloc(chip->ngpio, sizeof(gdev->descs[0]), GFP_KERNEL);
1621 if (chip->ngpio == 0) {
1622 chip_err(chip, "tried to insert a GPIO chip with zero lines\n");
1624 goto err_free_descs;
1627 if (chip->ngpio > FASTPATH_NGPIO)
1628 chip_warn(chip, "line cnt %u is greater than fast path cnt %u\n",
1629 chip->ngpio, FASTPATH_NGPIO);
1631 gdev->label = kstrdup_const(chip->label ?: "unknown", GFP_KERNEL);
1634 goto err_free_descs;
1637 gdev->ngpio = chip->ngpio;
1640 spin_lock_irqsave(&gpio_lock, flags);
1643 * TODO: this allocates a Linux GPIO number base in the global
1644 * GPIO numberspace for this chip. In the long run we want to
1645 * get *rid* of this numberspace and use only descriptors, but
1646 * it may be a pipe dream. It will not happen before we get rid
1647 * of the sysfs interface anyways.
1650 base = gpiochip_find_base(chip->ngpio);
1653 spin_unlock_irqrestore(&gpio_lock, flags);
1654 goto err_free_label;
1657 * TODO: it should not be necessary to reflect the assigned
1658 * base outside of the GPIO subsystem. Go over drivers and
1659 * see if anyone makes use of this, else drop this and assign
1666 ret = gpiodev_add_to_list(gdev);
1668 spin_unlock_irqrestore(&gpio_lock, flags);
1669 goto err_free_label;
1672 for (i = 0; i < chip->ngpio; i++)
1673 gdev->descs[i].gdev = gdev;
1675 spin_unlock_irqrestore(&gpio_lock, flags);
1677 ATOMIC_INIT_NOTIFIER_HEAD(&gdev->notifier);
1679 #ifdef CONFIG_PINCTRL
1680 INIT_LIST_HEAD(&gdev->pin_ranges);
1683 ret = gpiochip_set_desc_names(chip);
1685 goto err_remove_from_list;
1687 ret = gpiochip_alloc_valid_mask(chip);
1689 goto err_remove_from_list;
1691 ret = of_gpiochip_add(chip);
1693 goto err_free_gpiochip_mask;
1695 ret = gpiochip_init_valid_mask(chip);
1697 goto err_remove_of_chip;
1699 for (i = 0; i < chip->ngpio; i++) {
1700 struct gpio_desc *desc = &gdev->descs[i];
1702 if (chip->get_direction && gpiochip_line_is_valid(chip, i)) {
1703 assign_bit(FLAG_IS_OUT,
1704 &desc->flags, !chip->get_direction(chip, i));
1706 assign_bit(FLAG_IS_OUT,
1707 &desc->flags, !chip->direction_input);
1711 ret = gpiochip_add_pin_ranges(chip);
1713 goto err_remove_of_chip;
1715 acpi_gpiochip_add(chip);
1717 machine_gpiochip_add(chip);
1719 ret = gpiochip_irqchip_init_valid_mask(chip);
1721 goto err_remove_acpi_chip;
1723 ret = gpiochip_irqchip_init_hw(chip);
1725 goto err_remove_acpi_chip;
1727 ret = gpiochip_add_irqchip(chip, lock_key, request_key);
1729 goto err_remove_irqchip_mask;
1732 * By first adding the chardev, and then adding the device,
1733 * we get a device node entry in sysfs under
1734 * /sys/bus/gpio/devices/gpiochipN/dev that can be used for
1735 * coldplug of device nodes and other udev business.
1736 * We can do this only if gpiolib has been initialized.
1737 * Otherwise, defer until later.
1739 if (gpiolib_initialized) {
1740 ret = gpiochip_setup_dev(gdev);
1742 goto err_remove_irqchip;
1747 gpiochip_irqchip_remove(chip);
1748 err_remove_irqchip_mask:
1749 gpiochip_irqchip_free_valid_mask(chip);
1750 err_remove_acpi_chip:
1751 acpi_gpiochip_remove(chip);
1753 gpiochip_free_hogs(chip);
1754 of_gpiochip_remove(chip);
1755 err_free_gpiochip_mask:
1756 gpiochip_remove_pin_ranges(chip);
1757 gpiochip_free_valid_mask(chip);
1758 err_remove_from_list:
1759 spin_lock_irqsave(&gpio_lock, flags);
1760 list_del(&gdev->list);
1761 spin_unlock_irqrestore(&gpio_lock, flags);
1763 kfree_const(gdev->label);
1767 ida_simple_remove(&gpio_ida, gdev->id);
1769 /* failures here can mean systems won't boot... */
1770 pr_err("%s: GPIOs %d..%d (%s) failed to register, %d\n", __func__,
1771 gdev->base, gdev->base + gdev->ngpio - 1,
1772 chip->label ? : "generic", ret);
1776 EXPORT_SYMBOL_GPL(gpiochip_add_data_with_key);
1779 * gpiochip_get_data() - get per-subdriver data for the chip
1783 * The per-subdriver data for the chip.
1785 void *gpiochip_get_data(struct gpio_chip *chip)
1787 return chip->gpiodev->data;
1789 EXPORT_SYMBOL_GPL(gpiochip_get_data);
1792 * gpiochip_remove() - unregister a gpio_chip
1793 * @chip: the chip to unregister
1795 * A gpio_chip with any GPIOs still requested may not be removed.
1797 void gpiochip_remove(struct gpio_chip *chip)
1799 struct gpio_device *gdev = chip->gpiodev;
1800 struct gpio_desc *desc;
1801 unsigned long flags;
1803 bool requested = false;
1805 /* FIXME: should the legacy sysfs handling be moved to gpio_device? */
1806 gpiochip_sysfs_unregister(gdev);
1807 gpiochip_free_hogs(chip);
1808 /* Numb the device, cancelling all outstanding operations */
1810 gpiochip_irqchip_remove(chip);
1811 acpi_gpiochip_remove(chip);
1812 of_gpiochip_remove(chip);
1813 gpiochip_remove_pin_ranges(chip);
1814 gpiochip_free_valid_mask(chip);
1816 * We accept no more calls into the driver from this point, so
1817 * NULL the driver data pointer
1821 spin_lock_irqsave(&gpio_lock, flags);
1822 for (i = 0; i < gdev->ngpio; i++) {
1823 desc = &gdev->descs[i];
1824 if (test_bit(FLAG_REQUESTED, &desc->flags))
1827 spin_unlock_irqrestore(&gpio_lock, flags);
1830 dev_crit(&gdev->dev,
1831 "REMOVING GPIOCHIP WITH GPIOS STILL REQUESTED\n");
1834 * The gpiochip side puts its use of the device to rest here:
1835 * if there are no userspace clients, the chardev and device will
1836 * be removed, else it will be dangling until the last user is
1839 cdev_device_del(&gdev->chrdev, &gdev->dev);
1840 put_device(&gdev->dev);
1842 EXPORT_SYMBOL_GPL(gpiochip_remove);
1844 static void devm_gpio_chip_release(struct device *dev, void *res)
1846 struct gpio_chip *chip = *(struct gpio_chip **)res;
1848 gpiochip_remove(chip);
1852 * devm_gpiochip_add_data() - Resource managed gpiochip_add_data()
1853 * @dev: pointer to the device that gpio_chip belongs to.
1854 * @chip: the chip to register, with chip->base initialized
1855 * @data: driver-private data associated with this chip
1857 * Context: potentially before irqs will work
1859 * The gpio chip automatically be released when the device is unbound.
1862 * A negative errno if the chip can't be registered, such as because the
1863 * chip->base is invalid or already associated with a different chip.
1864 * Otherwise it returns zero as a success code.
1866 int devm_gpiochip_add_data(struct device *dev, struct gpio_chip *chip,
1869 struct gpio_chip **ptr;
1872 ptr = devres_alloc(devm_gpio_chip_release, sizeof(*ptr),
1877 ret = gpiochip_add_data(chip, data);
1884 devres_add(dev, ptr);
1888 EXPORT_SYMBOL_GPL(devm_gpiochip_add_data);
1891 * gpiochip_find() - iterator for locating a specific gpio_chip
1892 * @data: data to pass to match function
1893 * @match: Callback function to check gpio_chip
1895 * Similar to bus_find_device. It returns a reference to a gpio_chip as
1896 * determined by a user supplied @match callback. The callback should return
1897 * 0 if the device doesn't match and non-zero if it does. If the callback is
1898 * non-zero, this function will return to the caller and not iterate over any
1901 struct gpio_chip *gpiochip_find(void *data,
1902 int (*match)(struct gpio_chip *chip,
1905 struct gpio_device *gdev;
1906 struct gpio_chip *chip = NULL;
1907 unsigned long flags;
1909 spin_lock_irqsave(&gpio_lock, flags);
1910 list_for_each_entry(gdev, &gpio_devices, list)
1911 if (gdev->chip && match(gdev->chip, data)) {
1916 spin_unlock_irqrestore(&gpio_lock, flags);
1920 EXPORT_SYMBOL_GPL(gpiochip_find);
1922 static int gpiochip_match_name(struct gpio_chip *chip, void *data)
1924 const char *name = data;
1926 return !strcmp(chip->label, name);
1929 static struct gpio_chip *find_chip_by_name(const char *name)
1931 return gpiochip_find((void *)name, gpiochip_match_name);
1934 #ifdef CONFIG_GPIOLIB_IRQCHIP
1937 * The following is irqchip helper code for gpiochips.
1940 static int gpiochip_irqchip_init_hw(struct gpio_chip *gc)
1942 struct gpio_irq_chip *girq = &gc->irq;
1947 return girq->init_hw(gc);
1950 static int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gc)
1952 struct gpio_irq_chip *girq = &gc->irq;
1954 if (!girq->init_valid_mask)
1957 girq->valid_mask = gpiochip_allocate_mask(gc);
1958 if (!girq->valid_mask)
1961 girq->init_valid_mask(gc, girq->valid_mask, gc->ngpio);
1966 static void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gpiochip)
1968 bitmap_free(gpiochip->irq.valid_mask);
1969 gpiochip->irq.valid_mask = NULL;
1972 bool gpiochip_irqchip_irq_valid(const struct gpio_chip *gpiochip,
1973 unsigned int offset)
1975 if (!gpiochip_line_is_valid(gpiochip, offset))
1977 /* No mask means all valid */
1978 if (likely(!gpiochip->irq.valid_mask))
1980 return test_bit(offset, gpiochip->irq.valid_mask);
1982 EXPORT_SYMBOL_GPL(gpiochip_irqchip_irq_valid);
1985 * gpiochip_set_cascaded_irqchip() - connects a cascaded irqchip to a gpiochip
1986 * @gc: the gpiochip to set the irqchip chain to
1987 * @parent_irq: the irq number corresponding to the parent IRQ for this
1989 * @parent_handler: the parent interrupt handler for the accumulated IRQ
1990 * coming out of the gpiochip. If the interrupt is nested rather than
1991 * cascaded, pass NULL in this handler argument
1993 static void gpiochip_set_cascaded_irqchip(struct gpio_chip *gc,
1994 unsigned int parent_irq,
1995 irq_flow_handler_t parent_handler)
1997 struct gpio_irq_chip *girq = &gc->irq;
1998 struct device *dev = &gc->gpiodev->dev;
2000 if (!girq->domain) {
2001 chip_err(gc, "called %s before setting up irqchip\n",
2006 if (parent_handler) {
2007 if (gc->can_sleep) {
2009 "you cannot have chained interrupts on a chip that may sleep\n");
2012 girq->parents = devm_kcalloc(dev, 1,
2013 sizeof(*girq->parents),
2015 if (!girq->parents) {
2016 chip_err(gc, "out of memory allocating parent IRQ\n");
2019 girq->parents[0] = parent_irq;
2020 girq->num_parents = 1;
2022 * The parent irqchip is already using the chip_data for this
2023 * irqchip, so our callbacks simply use the handler_data.
2025 irq_set_chained_handler_and_data(parent_irq, parent_handler,
2031 * gpiochip_set_nested_irqchip() - connects a nested irqchip to a gpiochip
2032 * @gpiochip: the gpiochip to set the irqchip nested handler to
2033 * @irqchip: the irqchip to nest to the gpiochip
2034 * @parent_irq: the irq number corresponding to the parent IRQ for this
2037 void gpiochip_set_nested_irqchip(struct gpio_chip *gpiochip,
2038 struct irq_chip *irqchip,
2039 unsigned int parent_irq)
2041 gpiochip_set_cascaded_irqchip(gpiochip, parent_irq, NULL);
2043 EXPORT_SYMBOL_GPL(gpiochip_set_nested_irqchip);
2045 #ifdef CONFIG_IRQ_DOMAIN_HIERARCHY
2048 * gpiochip_set_hierarchical_irqchip() - connects a hierarchical irqchip
2050 * @gc: the gpiochip to set the irqchip hierarchical handler to
2051 * @irqchip: the irqchip to handle this level of the hierarchy, the interrupt
2052 * will then percolate up to the parent
2054 static void gpiochip_set_hierarchical_irqchip(struct gpio_chip *gc,
2055 struct irq_chip *irqchip)
2057 /* DT will deal with mapping each IRQ as we go along */
2058 if (is_of_node(gc->irq.fwnode))
2062 * This is for legacy and boardfile "irqchip" fwnodes: allocate
2063 * irqs upfront instead of dynamically since we don't have the
2064 * dynamic type of allocation that hardware description languages
2065 * provide. Once all GPIO drivers using board files are gone from
2066 * the kernel we can delete this code, but for a transitional period
2067 * it is necessary to keep this around.
2069 if (is_fwnode_irqchip(gc->irq.fwnode)) {
2073 for (i = 0; i < gc->ngpio; i++) {
2074 struct irq_fwspec fwspec;
2075 unsigned int parent_hwirq;
2076 unsigned int parent_type;
2077 struct gpio_irq_chip *girq = &gc->irq;
2080 * We call the child to parent translation function
2081 * only to check if the child IRQ is valid or not.
2082 * Just pick the rising edge type here as that is what
2083 * we likely need to support.
2085 ret = girq->child_to_parent_hwirq(gc, i,
2086 IRQ_TYPE_EDGE_RISING,
2090 chip_err(gc, "skip set-up on hwirq %d\n",
2095 fwspec.fwnode = gc->irq.fwnode;
2096 /* This is the hwirq for the GPIO line side of things */
2097 fwspec.param[0] = girq->child_offset_to_irq(gc, i);
2098 /* Just pick something */
2099 fwspec.param[1] = IRQ_TYPE_EDGE_RISING;
2100 fwspec.param_count = 2;
2101 ret = __irq_domain_alloc_irqs(gc->irq.domain,
2102 /* just pick something */
2111 "can not allocate irq for GPIO line %d parent hwirq %d in hierarchy domain: %d\n",
2118 chip_err(gc, "%s unknown fwnode type proceed anyway\n", __func__);
2123 static int gpiochip_hierarchy_irq_domain_translate(struct irq_domain *d,
2124 struct irq_fwspec *fwspec,
2125 unsigned long *hwirq,
2128 /* We support standard DT translation */
2129 if (is_of_node(fwspec->fwnode) && fwspec->param_count == 2) {
2130 return irq_domain_translate_twocell(d, fwspec, hwirq, type);
2133 /* This is for board files and others not using DT */
2134 if (is_fwnode_irqchip(fwspec->fwnode)) {
2137 ret = irq_domain_translate_twocell(d, fwspec, hwirq, type);
2140 WARN_ON(*type == IRQ_TYPE_NONE);
2146 static int gpiochip_hierarchy_irq_domain_alloc(struct irq_domain *d,
2148 unsigned int nr_irqs,
2151 struct gpio_chip *gc = d->host_data;
2152 irq_hw_number_t hwirq;
2153 unsigned int type = IRQ_TYPE_NONE;
2154 struct irq_fwspec *fwspec = data;
2156 unsigned int parent_hwirq;
2157 unsigned int parent_type;
2158 struct gpio_irq_chip *girq = &gc->irq;
2162 * The nr_irqs parameter is always one except for PCI multi-MSI
2163 * so this should not happen.
2165 WARN_ON(nr_irqs != 1);
2167 ret = gc->irq.child_irq_domain_ops.translate(d, fwspec, &hwirq, &type);
2171 chip_dbg(gc, "allocate IRQ %d, hwirq %lu\n", irq, hwirq);
2173 ret = girq->child_to_parent_hwirq(gc, hwirq, type,
2174 &parent_hwirq, &parent_type);
2176 chip_err(gc, "can't look up hwirq %lu\n", hwirq);
2179 chip_dbg(gc, "found parent hwirq %u\n", parent_hwirq);
2182 * We set handle_bad_irq because the .set_type() should
2183 * always be invoked and set the right type of handler.
2185 irq_domain_set_info(d,
2194 /* This parent only handles asserted level IRQs */
2195 parent_arg = girq->populate_parent_alloc_arg(gc, parent_hwirq, parent_type);
2199 chip_dbg(gc, "alloc_irqs_parent for %d parent hwirq %d\n",
2201 irq_set_lockdep_class(irq, gc->irq.lock_key, gc->irq.request_key);
2202 ret = irq_domain_alloc_irqs_parent(d, irq, 1, parent_arg);
2204 * If the parent irqdomain is msi, the interrupts have already
2205 * been allocated, so the EEXIST is good.
2207 if (irq_domain_is_msi(d->parent) && (ret == -EEXIST))
2211 "failed to allocate parent hwirq %d for hwirq %lu\n",
2212 parent_hwirq, hwirq);
2218 static unsigned int gpiochip_child_offset_to_irq_noop(struct gpio_chip *chip,
2219 unsigned int offset)
2224 static void gpiochip_hierarchy_setup_domain_ops(struct irq_domain_ops *ops)
2226 ops->activate = gpiochip_irq_domain_activate;
2227 ops->deactivate = gpiochip_irq_domain_deactivate;
2228 ops->alloc = gpiochip_hierarchy_irq_domain_alloc;
2229 ops->free = irq_domain_free_irqs_common;
2232 * We only allow overriding the translate() function for
2233 * hierarchical chips, and this should only be done if the user
2234 * really need something other than 1:1 translation.
2236 if (!ops->translate)
2237 ops->translate = gpiochip_hierarchy_irq_domain_translate;
2240 static int gpiochip_hierarchy_add_domain(struct gpio_chip *gc)
2242 if (!gc->irq.child_to_parent_hwirq ||
2244 chip_err(gc, "missing irqdomain vital data\n");
2248 if (!gc->irq.child_offset_to_irq)
2249 gc->irq.child_offset_to_irq = gpiochip_child_offset_to_irq_noop;
2251 if (!gc->irq.populate_parent_alloc_arg)
2252 gc->irq.populate_parent_alloc_arg =
2253 gpiochip_populate_parent_fwspec_twocell;
2255 gpiochip_hierarchy_setup_domain_ops(&gc->irq.child_irq_domain_ops);
2257 gc->irq.domain = irq_domain_create_hierarchy(
2258 gc->irq.parent_domain,
2262 &gc->irq.child_irq_domain_ops,
2265 if (!gc->irq.domain)
2268 gpiochip_set_hierarchical_irqchip(gc, gc->irq.chip);
2273 static bool gpiochip_hierarchy_is_hierarchical(struct gpio_chip *gc)
2275 return !!gc->irq.parent_domain;
2278 void *gpiochip_populate_parent_fwspec_twocell(struct gpio_chip *chip,
2279 unsigned int parent_hwirq,
2280 unsigned int parent_type)
2282 struct irq_fwspec *fwspec;
2284 fwspec = kmalloc(sizeof(*fwspec), GFP_KERNEL);
2288 fwspec->fwnode = chip->irq.parent_domain->fwnode;
2289 fwspec->param_count = 2;
2290 fwspec->param[0] = parent_hwirq;
2291 fwspec->param[1] = parent_type;
2295 EXPORT_SYMBOL_GPL(gpiochip_populate_parent_fwspec_twocell);
2297 void *gpiochip_populate_parent_fwspec_fourcell(struct gpio_chip *chip,
2298 unsigned int parent_hwirq,
2299 unsigned int parent_type)
2301 struct irq_fwspec *fwspec;
2303 fwspec = kmalloc(sizeof(*fwspec), GFP_KERNEL);
2307 fwspec->fwnode = chip->irq.parent_domain->fwnode;
2308 fwspec->param_count = 4;
2309 fwspec->param[0] = 0;
2310 fwspec->param[1] = parent_hwirq;
2311 fwspec->param[2] = 0;
2312 fwspec->param[3] = parent_type;
2316 EXPORT_SYMBOL_GPL(gpiochip_populate_parent_fwspec_fourcell);
2320 static int gpiochip_hierarchy_add_domain(struct gpio_chip *gc)
2325 static bool gpiochip_hierarchy_is_hierarchical(struct gpio_chip *gc)
2330 #endif /* CONFIG_IRQ_DOMAIN_HIERARCHY */
2333 * gpiochip_irq_map() - maps an IRQ into a GPIO irqchip
2334 * @d: the irqdomain used by this irqchip
2335 * @irq: the global irq number used by this GPIO irqchip irq
2336 * @hwirq: the local IRQ/GPIO line offset on this gpiochip
2338 * This function will set up the mapping for a certain IRQ line on a
2339 * gpiochip by assigning the gpiochip as chip data, and using the irqchip
2340 * stored inside the gpiochip.
2342 int gpiochip_irq_map(struct irq_domain *d, unsigned int irq,
2343 irq_hw_number_t hwirq)
2345 struct gpio_chip *chip = d->host_data;
2348 if (!gpiochip_irqchip_irq_valid(chip, hwirq))
2351 irq_set_chip_data(irq, chip);
2353 * This lock class tells lockdep that GPIO irqs are in a different
2354 * category than their parents, so it won't report false recursion.
2356 irq_set_lockdep_class(irq, chip->irq.lock_key, chip->irq.request_key);
2357 irq_set_chip_and_handler(irq, chip->irq.chip, chip->irq.handler);
2358 /* Chips that use nested thread handlers have them marked */
2359 if (chip->irq.threaded)
2360 irq_set_nested_thread(irq, 1);
2361 irq_set_noprobe(irq);
2363 if (chip->irq.num_parents == 1)
2364 ret = irq_set_parent(irq, chip->irq.parents[0]);
2365 else if (chip->irq.map)
2366 ret = irq_set_parent(irq, chip->irq.map[hwirq]);
2372 * No set-up of the hardware will happen if IRQ_TYPE_NONE
2373 * is passed as default type.
2375 if (chip->irq.default_type != IRQ_TYPE_NONE)
2376 irq_set_irq_type(irq, chip->irq.default_type);
2380 EXPORT_SYMBOL_GPL(gpiochip_irq_map);
2382 void gpiochip_irq_unmap(struct irq_domain *d, unsigned int irq)
2384 struct gpio_chip *chip = d->host_data;
2386 if (chip->irq.threaded)
2387 irq_set_nested_thread(irq, 0);
2388 irq_set_chip_and_handler(irq, NULL, NULL);
2389 irq_set_chip_data(irq, NULL);
2391 EXPORT_SYMBOL_GPL(gpiochip_irq_unmap);
2393 static const struct irq_domain_ops gpiochip_domain_ops = {
2394 .map = gpiochip_irq_map,
2395 .unmap = gpiochip_irq_unmap,
2396 /* Virtually all GPIO irqchips are twocell:ed */
2397 .xlate = irq_domain_xlate_twocell,
2401 * TODO: move these activate/deactivate in under the hierarchicial
2402 * irqchip implementation as static once SPMI and SSBI (all external
2403 * users) are phased over.
2406 * gpiochip_irq_domain_activate() - Lock a GPIO to be used as an IRQ
2407 * @domain: The IRQ domain used by this IRQ chip
2408 * @data: Outermost irq_data associated with the IRQ
2409 * @reserve: If set, only reserve an interrupt vector instead of assigning one
2411 * This function is a wrapper that calls gpiochip_lock_as_irq() and is to be
2412 * used as the activate function for the &struct irq_domain_ops. The host_data
2413 * for the IRQ domain must be the &struct gpio_chip.
2415 int gpiochip_irq_domain_activate(struct irq_domain *domain,
2416 struct irq_data *data, bool reserve)
2418 struct gpio_chip *chip = domain->host_data;
2420 return gpiochip_lock_as_irq(chip, data->hwirq);
2422 EXPORT_SYMBOL_GPL(gpiochip_irq_domain_activate);
2425 * gpiochip_irq_domain_deactivate() - Unlock a GPIO used as an IRQ
2426 * @domain: The IRQ domain used by this IRQ chip
2427 * @data: Outermost irq_data associated with the IRQ
2429 * This function is a wrapper that will call gpiochip_unlock_as_irq() and is to
2430 * be used as the deactivate function for the &struct irq_domain_ops. The
2431 * host_data for the IRQ domain must be the &struct gpio_chip.
2433 void gpiochip_irq_domain_deactivate(struct irq_domain *domain,
2434 struct irq_data *data)
2436 struct gpio_chip *chip = domain->host_data;
2438 return gpiochip_unlock_as_irq(chip, data->hwirq);
2440 EXPORT_SYMBOL_GPL(gpiochip_irq_domain_deactivate);
2442 static int gpiochip_to_irq(struct gpio_chip *chip, unsigned offset)
2444 struct irq_domain *domain = chip->irq.domain;
2446 if (!gpiochip_irqchip_irq_valid(chip, offset))
2449 #ifdef CONFIG_IRQ_DOMAIN_HIERARCHY
2450 if (irq_domain_is_hierarchy(domain)) {
2451 struct irq_fwspec spec;
2453 spec.fwnode = domain->fwnode;
2454 spec.param_count = 2;
2455 spec.param[0] = chip->irq.child_offset_to_irq(chip, offset);
2456 spec.param[1] = IRQ_TYPE_NONE;
2458 return irq_create_fwspec_mapping(&spec);
2462 return irq_create_mapping(domain, offset);
2465 static int gpiochip_irq_reqres(struct irq_data *d)
2467 struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
2469 return gpiochip_reqres_irq(chip, d->hwirq);
2472 static void gpiochip_irq_relres(struct irq_data *d)
2474 struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
2476 gpiochip_relres_irq(chip, d->hwirq);
2479 static void gpiochip_irq_enable(struct irq_data *d)
2481 struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
2483 gpiochip_enable_irq(chip, d->hwirq);
2484 if (chip->irq.irq_enable)
2485 chip->irq.irq_enable(d);
2487 chip->irq.chip->irq_unmask(d);
2490 static void gpiochip_irq_disable(struct irq_data *d)
2492 struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
2494 if (chip->irq.irq_disable)
2495 chip->irq.irq_disable(d);
2497 chip->irq.chip->irq_mask(d);
2498 gpiochip_disable_irq(chip, d->hwirq);
2501 static void gpiochip_set_irq_hooks(struct gpio_chip *gpiochip)
2503 struct irq_chip *irqchip = gpiochip->irq.chip;
2505 if (!irqchip->irq_request_resources &&
2506 !irqchip->irq_release_resources) {
2507 irqchip->irq_request_resources = gpiochip_irq_reqres;
2508 irqchip->irq_release_resources = gpiochip_irq_relres;
2510 if (WARN_ON(gpiochip->irq.irq_enable))
2512 /* Check if the irqchip already has this hook... */
2513 if (irqchip->irq_enable == gpiochip_irq_enable) {
2515 * ...and if so, give a gentle warning that this is bad
2519 "detected irqchip that is shared with multiple gpiochips: please fix the driver.\n");
2522 gpiochip->irq.irq_enable = irqchip->irq_enable;
2523 gpiochip->irq.irq_disable = irqchip->irq_disable;
2524 irqchip->irq_enable = gpiochip_irq_enable;
2525 irqchip->irq_disable = gpiochip_irq_disable;
2529 * gpiochip_add_irqchip() - adds an IRQ chip to a GPIO chip
2530 * @gpiochip: the GPIO chip to add the IRQ chip to
2531 * @lock_key: lockdep class for IRQ lock
2532 * @request_key: lockdep class for IRQ request
2534 static int gpiochip_add_irqchip(struct gpio_chip *gpiochip,
2535 struct lock_class_key *lock_key,
2536 struct lock_class_key *request_key)
2538 struct irq_chip *irqchip = gpiochip->irq.chip;
2539 const struct irq_domain_ops *ops = NULL;
2540 struct device_node *np;
2547 if (gpiochip->irq.parent_handler && gpiochip->can_sleep) {
2548 chip_err(gpiochip, "you cannot have chained interrupts on a chip that may sleep\n");
2552 np = gpiochip->gpiodev->dev.of_node;
2553 type = gpiochip->irq.default_type;
2556 * Specifying a default trigger is a terrible idea if DT or ACPI is
2557 * used to configure the interrupts, as you may end up with
2558 * conflicting triggers. Tell the user, and reset to NONE.
2560 if (WARN(np && type != IRQ_TYPE_NONE,
2561 "%s: Ignoring %u default trigger\n", np->full_name, type))
2562 type = IRQ_TYPE_NONE;
2564 if (has_acpi_companion(gpiochip->parent) && type != IRQ_TYPE_NONE) {
2565 acpi_handle_warn(ACPI_HANDLE(gpiochip->parent),
2566 "Ignoring %u default trigger\n", type);
2567 type = IRQ_TYPE_NONE;
2570 gpiochip->to_irq = gpiochip_to_irq;
2571 gpiochip->irq.default_type = type;
2572 gpiochip->irq.lock_key = lock_key;
2573 gpiochip->irq.request_key = request_key;
2575 /* If a parent irqdomain is provided, let's build a hierarchy */
2576 if (gpiochip_hierarchy_is_hierarchical(gpiochip)) {
2577 int ret = gpiochip_hierarchy_add_domain(gpiochip);
2581 /* Some drivers provide custom irqdomain ops */
2582 if (gpiochip->irq.domain_ops)
2583 ops = gpiochip->irq.domain_ops;
2586 ops = &gpiochip_domain_ops;
2587 gpiochip->irq.domain = irq_domain_add_simple(np,
2589 gpiochip->irq.first,
2591 if (!gpiochip->irq.domain)
2595 if (gpiochip->irq.parent_handler) {
2596 void *data = gpiochip->irq.parent_handler_data ?: gpiochip;
2598 for (i = 0; i < gpiochip->irq.num_parents; i++) {
2600 * The parent IRQ chip is already using the chip_data
2601 * for this IRQ chip, so our callbacks simply use the
2604 irq_set_chained_handler_and_data(gpiochip->irq.parents[i],
2605 gpiochip->irq.parent_handler,
2610 gpiochip_set_irq_hooks(gpiochip);
2612 acpi_gpiochip_request_interrupts(gpiochip);
2618 * gpiochip_irqchip_remove() - removes an irqchip added to a gpiochip
2619 * @gpiochip: the gpiochip to remove the irqchip from
2621 * This is called only from gpiochip_remove()
2623 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip)
2625 struct irq_chip *irqchip = gpiochip->irq.chip;
2626 unsigned int offset;
2628 acpi_gpiochip_free_interrupts(gpiochip);
2630 if (irqchip && gpiochip->irq.parent_handler) {
2631 struct gpio_irq_chip *irq = &gpiochip->irq;
2634 for (i = 0; i < irq->num_parents; i++)
2635 irq_set_chained_handler_and_data(irq->parents[i],
2639 /* Remove all IRQ mappings and delete the domain */
2640 if (gpiochip->irq.domain) {
2643 for (offset = 0; offset < gpiochip->ngpio; offset++) {
2644 if (!gpiochip_irqchip_irq_valid(gpiochip, offset))
2647 irq = irq_find_mapping(gpiochip->irq.domain, offset);
2648 irq_dispose_mapping(irq);
2651 irq_domain_remove(gpiochip->irq.domain);
2655 if (irqchip->irq_request_resources == gpiochip_irq_reqres) {
2656 irqchip->irq_request_resources = NULL;
2657 irqchip->irq_release_resources = NULL;
2659 if (irqchip->irq_enable == gpiochip_irq_enable) {
2660 irqchip->irq_enable = gpiochip->irq.irq_enable;
2661 irqchip->irq_disable = gpiochip->irq.irq_disable;
2664 gpiochip->irq.irq_enable = NULL;
2665 gpiochip->irq.irq_disable = NULL;
2666 gpiochip->irq.chip = NULL;
2668 gpiochip_irqchip_free_valid_mask(gpiochip);
2672 * gpiochip_irqchip_add_key() - adds an irqchip to a gpiochip
2673 * @gpiochip: the gpiochip to add the irqchip to
2674 * @irqchip: the irqchip to add to the gpiochip
2675 * @first_irq: if not dynamically assigned, the base (first) IRQ to
2676 * allocate gpiochip irqs from
2677 * @handler: the irq handler to use (often a predefined irq core function)
2678 * @type: the default type for IRQs on this irqchip, pass IRQ_TYPE_NONE
2679 * to have the core avoid setting up any default type in the hardware.
2680 * @threaded: whether this irqchip uses a nested thread handler
2681 * @lock_key: lockdep class for IRQ lock
2682 * @request_key: lockdep class for IRQ request
2684 * This function closely associates a certain irqchip with a certain
2685 * gpiochip, providing an irq domain to translate the local IRQs to
2686 * global irqs in the gpiolib core, and making sure that the gpiochip
2687 * is passed as chip data to all related functions. Driver callbacks
2688 * need to use gpiochip_get_data() to get their local state containers back
2689 * from the gpiochip passed as chip data. An irqdomain will be stored
2690 * in the gpiochip that shall be used by the driver to handle IRQ number
2691 * translation. The gpiochip will need to be initialized and registered
2692 * before calling this function.
2694 * This function will handle two cell:ed simple IRQs and assumes all
2695 * the pins on the gpiochip can generate a unique IRQ. Everything else
2696 * need to be open coded.
2698 int gpiochip_irqchip_add_key(struct gpio_chip *gpiochip,
2699 struct irq_chip *irqchip,
2700 unsigned int first_irq,
2701 irq_flow_handler_t handler,
2704 struct lock_class_key *lock_key,
2705 struct lock_class_key *request_key)
2707 struct device_node *of_node;
2709 if (!gpiochip || !irqchip)
2712 if (!gpiochip->parent) {
2713 pr_err("missing gpiochip .dev parent pointer\n");
2716 gpiochip->irq.threaded = threaded;
2717 of_node = gpiochip->parent->of_node;
2718 #ifdef CONFIG_OF_GPIO
2720 * If the gpiochip has an assigned OF node this takes precedence
2721 * FIXME: get rid of this and use gpiochip->parent->of_node
2724 if (gpiochip->of_node)
2725 of_node = gpiochip->of_node;
2728 * Specifying a default trigger is a terrible idea if DT or ACPI is
2729 * used to configure the interrupts, as you may end-up with
2730 * conflicting triggers. Tell the user, and reset to NONE.
2732 if (WARN(of_node && type != IRQ_TYPE_NONE,
2733 "%pOF: Ignoring %d default trigger\n", of_node, type))
2734 type = IRQ_TYPE_NONE;
2735 if (has_acpi_companion(gpiochip->parent) && type != IRQ_TYPE_NONE) {
2736 acpi_handle_warn(ACPI_HANDLE(gpiochip->parent),
2737 "Ignoring %d default trigger\n", type);
2738 type = IRQ_TYPE_NONE;
2741 gpiochip->irq.chip = irqchip;
2742 gpiochip->irq.handler = handler;
2743 gpiochip->irq.default_type = type;
2744 gpiochip->to_irq = gpiochip_to_irq;
2745 gpiochip->irq.lock_key = lock_key;
2746 gpiochip->irq.request_key = request_key;
2747 gpiochip->irq.domain = irq_domain_add_simple(of_node,
2748 gpiochip->ngpio, first_irq,
2749 &gpiochip_domain_ops, gpiochip);
2750 if (!gpiochip->irq.domain) {
2751 gpiochip->irq.chip = NULL;
2755 gpiochip_set_irq_hooks(gpiochip);
2757 acpi_gpiochip_request_interrupts(gpiochip);
2761 EXPORT_SYMBOL_GPL(gpiochip_irqchip_add_key);
2763 #else /* CONFIG_GPIOLIB_IRQCHIP */
2765 static inline int gpiochip_add_irqchip(struct gpio_chip *gpiochip,
2766 struct lock_class_key *lock_key,
2767 struct lock_class_key *request_key)
2771 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip) {}
2773 static inline int gpiochip_irqchip_init_hw(struct gpio_chip *gpiochip)
2778 static inline int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gpiochip)
2782 static inline void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gpiochip)
2785 #endif /* CONFIG_GPIOLIB_IRQCHIP */
2788 * gpiochip_generic_request() - request the gpio function for a pin
2789 * @chip: the gpiochip owning the GPIO
2790 * @offset: the offset of the GPIO to request for GPIO function
2792 int gpiochip_generic_request(struct gpio_chip *chip, unsigned offset)
2794 return pinctrl_gpio_request(chip->gpiodev->base + offset);
2796 EXPORT_SYMBOL_GPL(gpiochip_generic_request);
2799 * gpiochip_generic_free() - free the gpio function from a pin
2800 * @chip: the gpiochip to request the gpio function for
2801 * @offset: the offset of the GPIO to free from GPIO function
2803 void gpiochip_generic_free(struct gpio_chip *chip, unsigned offset)
2805 pinctrl_gpio_free(chip->gpiodev->base + offset);
2807 EXPORT_SYMBOL_GPL(gpiochip_generic_free);
2810 * gpiochip_generic_config() - apply configuration for a pin
2811 * @chip: the gpiochip owning the GPIO
2812 * @offset: the offset of the GPIO to apply the configuration
2813 * @config: the configuration to be applied
2815 int gpiochip_generic_config(struct gpio_chip *chip, unsigned offset,
2816 unsigned long config)
2818 return pinctrl_gpio_set_config(chip->gpiodev->base + offset, config);
2820 EXPORT_SYMBOL_GPL(gpiochip_generic_config);
2822 #ifdef CONFIG_PINCTRL
2825 * gpiochip_add_pingroup_range() - add a range for GPIO <-> pin mapping
2826 * @chip: the gpiochip to add the range for
2827 * @pctldev: the pin controller to map to
2828 * @gpio_offset: the start offset in the current gpio_chip number space
2829 * @pin_group: name of the pin group inside the pin controller
2831 * Calling this function directly from a DeviceTree-supported
2832 * pinctrl driver is DEPRECATED. Please see Section 2.1 of
2833 * Documentation/devicetree/bindings/gpio/gpio.txt on how to
2834 * bind pinctrl and gpio drivers via the "gpio-ranges" property.
2836 int gpiochip_add_pingroup_range(struct gpio_chip *chip,
2837 struct pinctrl_dev *pctldev,
2838 unsigned int gpio_offset, const char *pin_group)
2840 struct gpio_pin_range *pin_range;
2841 struct gpio_device *gdev = chip->gpiodev;
2844 pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
2846 chip_err(chip, "failed to allocate pin ranges\n");
2850 /* Use local offset as range ID */
2851 pin_range->range.id = gpio_offset;
2852 pin_range->range.gc = chip;
2853 pin_range->range.name = chip->label;
2854 pin_range->range.base = gdev->base + gpio_offset;
2855 pin_range->pctldev = pctldev;
2857 ret = pinctrl_get_group_pins(pctldev, pin_group,
2858 &pin_range->range.pins,
2859 &pin_range->range.npins);
2865 pinctrl_add_gpio_range(pctldev, &pin_range->range);
2867 chip_dbg(chip, "created GPIO range %d->%d ==> %s PINGRP %s\n",
2868 gpio_offset, gpio_offset + pin_range->range.npins - 1,
2869 pinctrl_dev_get_devname(pctldev), pin_group);
2871 list_add_tail(&pin_range->node, &gdev->pin_ranges);
2875 EXPORT_SYMBOL_GPL(gpiochip_add_pingroup_range);
2878 * gpiochip_add_pin_range() - add a range for GPIO <-> pin mapping
2879 * @chip: the gpiochip to add the range for
2880 * @pinctl_name: the dev_name() of the pin controller to map to
2881 * @gpio_offset: the start offset in the current gpio_chip number space
2882 * @pin_offset: the start offset in the pin controller number space
2883 * @npins: the number of pins from the offset of each pin space (GPIO and
2884 * pin controller) to accumulate in this range
2887 * 0 on success, or a negative error-code on failure.
2889 * Calling this function directly from a DeviceTree-supported
2890 * pinctrl driver is DEPRECATED. Please see Section 2.1 of
2891 * Documentation/devicetree/bindings/gpio/gpio.txt on how to
2892 * bind pinctrl and gpio drivers via the "gpio-ranges" property.
2894 int gpiochip_add_pin_range(struct gpio_chip *chip, const char *pinctl_name,
2895 unsigned int gpio_offset, unsigned int pin_offset,
2898 struct gpio_pin_range *pin_range;
2899 struct gpio_device *gdev = chip->gpiodev;
2902 pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
2904 chip_err(chip, "failed to allocate pin ranges\n");
2908 /* Use local offset as range ID */
2909 pin_range->range.id = gpio_offset;
2910 pin_range->range.gc = chip;
2911 pin_range->range.name = chip->label;
2912 pin_range->range.base = gdev->base + gpio_offset;
2913 pin_range->range.pin_base = pin_offset;
2914 pin_range->range.npins = npins;
2915 pin_range->pctldev = pinctrl_find_and_add_gpio_range(pinctl_name,
2917 if (IS_ERR(pin_range->pctldev)) {
2918 ret = PTR_ERR(pin_range->pctldev);
2919 chip_err(chip, "could not create pin range\n");
2923 chip_dbg(chip, "created GPIO range %d->%d ==> %s PIN %d->%d\n",
2924 gpio_offset, gpio_offset + npins - 1,
2926 pin_offset, pin_offset + npins - 1);
2928 list_add_tail(&pin_range->node, &gdev->pin_ranges);
2932 EXPORT_SYMBOL_GPL(gpiochip_add_pin_range);
2935 * gpiochip_remove_pin_ranges() - remove all the GPIO <-> pin mappings
2936 * @chip: the chip to remove all the mappings for
2938 void gpiochip_remove_pin_ranges(struct gpio_chip *chip)
2940 struct gpio_pin_range *pin_range, *tmp;
2941 struct gpio_device *gdev = chip->gpiodev;
2943 list_for_each_entry_safe(pin_range, tmp, &gdev->pin_ranges, node) {
2944 list_del(&pin_range->node);
2945 pinctrl_remove_gpio_range(pin_range->pctldev,
2950 EXPORT_SYMBOL_GPL(gpiochip_remove_pin_ranges);
2952 #endif /* CONFIG_PINCTRL */
2954 /* These "optional" allocation calls help prevent drivers from stomping
2955 * on each other, and help provide better diagnostics in debugfs.
2956 * They're called even less than the "set direction" calls.
2958 static int gpiod_request_commit(struct gpio_desc *desc, const char *label)
2960 struct gpio_chip *chip = desc->gdev->chip;
2962 unsigned long flags;
2966 label = kstrdup_const(label, GFP_KERNEL);
2971 spin_lock_irqsave(&gpio_lock, flags);
2973 /* NOTE: gpio_request() can be called in early boot,
2974 * before IRQs are enabled, for non-sleeping (SOC) GPIOs.
2977 if (test_and_set_bit(FLAG_REQUESTED, &desc->flags) == 0) {
2978 desc_set_label(desc, label ? : "?");
2986 if (chip->request) {
2987 /* chip->request may sleep */
2988 spin_unlock_irqrestore(&gpio_lock, flags);
2989 offset = gpio_chip_hwgpio(desc);
2990 if (gpiochip_line_is_valid(chip, offset))
2991 ret = chip->request(chip, offset);
2994 spin_lock_irqsave(&gpio_lock, flags);
2997 desc_set_label(desc, NULL);
2999 clear_bit(FLAG_REQUESTED, &desc->flags);
3003 if (chip->get_direction) {
3004 /* chip->get_direction may sleep */
3005 spin_unlock_irqrestore(&gpio_lock, flags);
3006 gpiod_get_direction(desc);
3007 spin_lock_irqsave(&gpio_lock, flags);
3010 spin_unlock_irqrestore(&gpio_lock, flags);
3011 atomic_notifier_call_chain(&desc->gdev->notifier,
3012 GPIOLINE_CHANGED_REQUESTED, desc);
3017 * This descriptor validation needs to be inserted verbatim into each
3018 * function taking a descriptor, so we need to use a preprocessor
3019 * macro to avoid endless duplication. If the desc is NULL it is an
3020 * optional GPIO and calls should just bail out.
3022 static int validate_desc(const struct gpio_desc *desc, const char *func)
3027 pr_warn("%s: invalid GPIO (errorpointer)\n", func);
3028 return PTR_ERR(desc);
3031 pr_warn("%s: invalid GPIO (no device)\n", func);
3034 if (!desc->gdev->chip) {
3035 dev_warn(&desc->gdev->dev,
3036 "%s: backing chip is gone\n", func);
3042 #define VALIDATE_DESC(desc) do { \
3043 int __valid = validate_desc(desc, __func__); \
3048 #define VALIDATE_DESC_VOID(desc) do { \
3049 int __valid = validate_desc(desc, __func__); \
3054 int gpiod_request(struct gpio_desc *desc, const char *label)
3056 int ret = -EPROBE_DEFER;
3057 struct gpio_device *gdev;
3059 VALIDATE_DESC(desc);
3062 if (try_module_get(gdev->owner)) {
3063 ret = gpiod_request_commit(desc, label);
3065 module_put(gdev->owner);
3067 get_device(&gdev->dev);
3071 gpiod_dbg(desc, "%s: status %d\n", __func__, ret);
3076 static bool gpiod_free_commit(struct gpio_desc *desc)
3079 unsigned long flags;
3080 struct gpio_chip *chip;
3084 gpiod_unexport(desc);
3086 spin_lock_irqsave(&gpio_lock, flags);
3088 chip = desc->gdev->chip;
3089 if (chip && test_bit(FLAG_REQUESTED, &desc->flags)) {
3091 spin_unlock_irqrestore(&gpio_lock, flags);
3092 might_sleep_if(chip->can_sleep);
3093 chip->free(chip, gpio_chip_hwgpio(desc));
3094 spin_lock_irqsave(&gpio_lock, flags);
3096 kfree_const(desc->label);
3097 desc_set_label(desc, NULL);
3098 clear_bit(FLAG_ACTIVE_LOW, &desc->flags);
3099 clear_bit(FLAG_REQUESTED, &desc->flags);
3100 clear_bit(FLAG_OPEN_DRAIN, &desc->flags);
3101 clear_bit(FLAG_OPEN_SOURCE, &desc->flags);
3102 clear_bit(FLAG_PULL_UP, &desc->flags);
3103 clear_bit(FLAG_PULL_DOWN, &desc->flags);
3104 clear_bit(FLAG_BIAS_DISABLE, &desc->flags);
3105 clear_bit(FLAG_IS_HOGGED, &desc->flags);
3106 #ifdef CONFIG_OF_DYNAMIC
3112 spin_unlock_irqrestore(&gpio_lock, flags);
3113 atomic_notifier_call_chain(&desc->gdev->notifier,
3114 GPIOLINE_CHANGED_RELEASED, desc);
3119 void gpiod_free(struct gpio_desc *desc)
3121 if (desc && desc->gdev && gpiod_free_commit(desc)) {
3122 module_put(desc->gdev->owner);
3123 put_device(&desc->gdev->dev);
3125 WARN_ON(extra_checks);
3130 * gpiochip_is_requested - return string iff signal was requested
3131 * @chip: controller managing the signal
3132 * @offset: of signal within controller's 0..(ngpio - 1) range
3134 * Returns NULL if the GPIO is not currently requested, else a string.
3135 * The string returned is the label passed to gpio_request(); if none has been
3136 * passed it is a meaningless, non-NULL constant.
3138 * This function is for use by GPIO controller drivers. The label can
3139 * help with diagnostics, and knowing that the signal is used as a GPIO
3140 * can help avoid accidentally multiplexing it to another controller.
3142 const char *gpiochip_is_requested(struct gpio_chip *chip, unsigned offset)
3144 struct gpio_desc *desc;
3146 if (offset >= chip->ngpio)
3149 desc = gpiochip_get_desc(chip, offset);
3153 if (test_bit(FLAG_REQUESTED, &desc->flags) == 0)
3157 EXPORT_SYMBOL_GPL(gpiochip_is_requested);
3160 * gpiochip_request_own_desc - Allow GPIO chip to request its own descriptor
3162 * @hwnum: hardware number of the GPIO for which to request the descriptor
3163 * @label: label for the GPIO
3164 * @lflags: lookup flags for this GPIO or 0 if default, this can be used to
3165 * specify things like line inversion semantics with the machine flags
3166 * such as GPIO_OUT_LOW
3167 * @dflags: descriptor request flags for this GPIO or 0 if default, this
3168 * can be used to specify consumer semantics such as open drain
3170 * Function allows GPIO chip drivers to request and use their own GPIO
3171 * descriptors via gpiolib API. Difference to gpiod_request() is that this
3172 * function will not increase reference count of the GPIO chip module. This
3173 * allows the GPIO chip module to be unloaded as needed (we assume that the
3174 * GPIO chip driver handles freeing the GPIOs it has requested).
3177 * A pointer to the GPIO descriptor, or an ERR_PTR()-encoded negative error
3180 struct gpio_desc *gpiochip_request_own_desc(struct gpio_chip *chip,
3183 enum gpio_lookup_flags lflags,
3184 enum gpiod_flags dflags)
3186 struct gpio_desc *desc = gpiochip_get_desc(chip, hwnum);
3190 chip_err(chip, "failed to get GPIO descriptor\n");
3194 ret = gpiod_request_commit(desc, label);
3196 return ERR_PTR(ret);
3198 ret = gpiod_configure_flags(desc, label, lflags, dflags);
3200 chip_err(chip, "setup of own GPIO %s failed\n", label);
3201 gpiod_free_commit(desc);
3202 return ERR_PTR(ret);
3207 EXPORT_SYMBOL_GPL(gpiochip_request_own_desc);
3210 * gpiochip_free_own_desc - Free GPIO requested by the chip driver
3211 * @desc: GPIO descriptor to free
3213 * Function frees the given GPIO requested previously with
3214 * gpiochip_request_own_desc().
3216 void gpiochip_free_own_desc(struct gpio_desc *desc)
3219 gpiod_free_commit(desc);
3221 EXPORT_SYMBOL_GPL(gpiochip_free_own_desc);
3224 * Drivers MUST set GPIO direction before making get/set calls. In
3225 * some cases this is done in early boot, before IRQs are enabled.
3227 * As a rule these aren't called more than once (except for drivers
3228 * using the open-drain emulation idiom) so these are natural places
3229 * to accumulate extra debugging checks. Note that we can't (yet)
3230 * rely on gpio_request() having been called beforehand.
3233 static int gpio_set_config(struct gpio_chip *gc, unsigned int offset,
3234 enum pin_config_param mode)
3236 if (!gc->set_config)
3239 return gc->set_config(gc, offset, mode);
3242 static int gpio_set_bias(struct gpio_chip *chip, struct gpio_desc *desc)
3247 if (test_bit(FLAG_BIAS_DISABLE, &desc->flags))
3248 bias = PIN_CONFIG_BIAS_DISABLE;
3249 else if (test_bit(FLAG_PULL_UP, &desc->flags))
3250 bias = PIN_CONFIG_BIAS_PULL_UP;
3251 else if (test_bit(FLAG_PULL_DOWN, &desc->flags))
3252 bias = PIN_CONFIG_BIAS_PULL_DOWN;
3255 ret = gpio_set_config(chip, gpio_chip_hwgpio(desc), bias);
3256 if (ret != -ENOTSUPP)
3263 * gpiod_direction_input - set the GPIO direction to input
3264 * @desc: GPIO to set to input
3266 * Set the direction of the passed GPIO to input, such as gpiod_get_value() can
3267 * be called safely on it.
3269 * Return 0 in case of success, else an error code.
3271 int gpiod_direction_input(struct gpio_desc *desc)
3273 struct gpio_chip *chip;
3276 VALIDATE_DESC(desc);
3277 chip = desc->gdev->chip;
3280 * It is legal to have no .get() and .direction_input() specified if
3281 * the chip is output-only, but you can't specify .direction_input()
3282 * and not support the .get() operation, that doesn't make sense.
3284 if (!chip->get && chip->direction_input) {
3286 "%s: missing get() but have direction_input()\n",
3292 * If we have a .direction_input() callback, things are simple,
3293 * just call it. Else we are some input-only chip so try to check the
3294 * direction (if .get_direction() is supported) else we silently
3295 * assume we are in input mode after this.
3297 if (chip->direction_input) {
3298 ret = chip->direction_input(chip, gpio_chip_hwgpio(desc));
3299 } else if (chip->get_direction &&
3300 (chip->get_direction(chip, gpio_chip_hwgpio(desc)) != 1)) {
3302 "%s: missing direction_input() operation and line is output\n",
3307 clear_bit(FLAG_IS_OUT, &desc->flags);
3308 ret = gpio_set_bias(chip, desc);
3311 trace_gpio_direction(desc_to_gpio(desc), 1, ret);
3315 EXPORT_SYMBOL_GPL(gpiod_direction_input);
3317 static int gpiod_direction_output_raw_commit(struct gpio_desc *desc, int value)
3319 struct gpio_chip *gc = desc->gdev->chip;
3324 * It's OK not to specify .direction_output() if the gpiochip is
3325 * output-only, but if there is then not even a .set() operation it
3326 * is pretty tricky to drive the output line.
3328 if (!gc->set && !gc->direction_output) {
3330 "%s: missing set() and direction_output() operations\n",
3335 if (gc->direction_output) {
3336 ret = gc->direction_output(gc, gpio_chip_hwgpio(desc), val);
3338 /* Check that we are in output mode if we can */
3339 if (gc->get_direction &&
3340 gc->get_direction(gc, gpio_chip_hwgpio(desc))) {
3342 "%s: missing direction_output() operation\n",
3347 * If we can't actively set the direction, we are some
3348 * output-only chip, so just drive the output as desired.
3350 gc->set(gc, gpio_chip_hwgpio(desc), val);
3354 set_bit(FLAG_IS_OUT, &desc->flags);
3355 trace_gpio_value(desc_to_gpio(desc), 0, val);
3356 trace_gpio_direction(desc_to_gpio(desc), 0, ret);
3361 * gpiod_direction_output_raw - set the GPIO direction to output
3362 * @desc: GPIO to set to output
3363 * @value: initial output value of the GPIO
3365 * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
3366 * be called safely on it. The initial value of the output must be specified
3367 * as raw value on the physical line without regard for the ACTIVE_LOW status.
3369 * Return 0 in case of success, else an error code.
3371 int gpiod_direction_output_raw(struct gpio_desc *desc, int value)
3373 VALIDATE_DESC(desc);
3374 return gpiod_direction_output_raw_commit(desc, value);
3376 EXPORT_SYMBOL_GPL(gpiod_direction_output_raw);
3379 * gpiod_direction_output - set the GPIO direction to output
3380 * @desc: GPIO to set to output
3381 * @value: initial output value of the GPIO
3383 * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
3384 * be called safely on it. The initial value of the output must be specified
3385 * as the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
3388 * Return 0 in case of success, else an error code.
3390 int gpiod_direction_output(struct gpio_desc *desc, int value)
3392 struct gpio_chip *gc;
3395 VALIDATE_DESC(desc);
3396 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3401 /* GPIOs used for enabled IRQs shall not be set as output */
3402 if (test_bit(FLAG_USED_AS_IRQ, &desc->flags) &&
3403 test_bit(FLAG_IRQ_IS_ENABLED, &desc->flags)) {
3405 "%s: tried to set a GPIO tied to an IRQ as output\n",
3410 gc = desc->gdev->chip;
3411 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags)) {
3412 /* First see if we can enable open drain in hardware */
3413 ret = gpio_set_config(gc, gpio_chip_hwgpio(desc),
3414 PIN_CONFIG_DRIVE_OPEN_DRAIN);
3416 goto set_output_value;
3417 /* Emulate open drain by not actively driving the line high */
3419 ret = gpiod_direction_input(desc);
3420 goto set_output_flag;
3423 else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags)) {
3424 ret = gpio_set_config(gc, gpio_chip_hwgpio(desc),
3425 PIN_CONFIG_DRIVE_OPEN_SOURCE);
3427 goto set_output_value;
3428 /* Emulate open source by not actively driving the line low */
3430 ret = gpiod_direction_input(desc);
3431 goto set_output_flag;
3434 gpio_set_config(gc, gpio_chip_hwgpio(desc),
3435 PIN_CONFIG_DRIVE_PUSH_PULL);
3439 ret = gpio_set_bias(gc, desc);
3442 return gpiod_direction_output_raw_commit(desc, value);
3446 * When emulating open-source or open-drain functionalities by not
3447 * actively driving the line (setting mode to input) we still need to
3448 * set the IS_OUT flag or otherwise we won't be able to set the line
3452 set_bit(FLAG_IS_OUT, &desc->flags);
3455 EXPORT_SYMBOL_GPL(gpiod_direction_output);
3458 * gpiod_set_debounce - sets @debounce time for a GPIO
3459 * @desc: descriptor of the GPIO for which to set debounce time
3460 * @debounce: debounce time in microseconds
3463 * 0 on success, %-ENOTSUPP if the controller doesn't support setting the
3466 int gpiod_set_debounce(struct gpio_desc *desc, unsigned debounce)
3468 struct gpio_chip *chip;
3469 unsigned long config;
3471 VALIDATE_DESC(desc);
3472 chip = desc->gdev->chip;
3474 config = pinconf_to_config_packed(PIN_CONFIG_INPUT_DEBOUNCE, debounce);
3475 return gpio_set_config(chip, gpio_chip_hwgpio(desc), config);
3477 EXPORT_SYMBOL_GPL(gpiod_set_debounce);
3480 * gpiod_set_transitory - Lose or retain GPIO state on suspend or reset
3481 * @desc: descriptor of the GPIO for which to configure persistence
3482 * @transitory: True to lose state on suspend or reset, false for persistence
3485 * 0 on success, otherwise a negative error code.
3487 int gpiod_set_transitory(struct gpio_desc *desc, bool transitory)
3489 struct gpio_chip *chip;
3490 unsigned long packed;
3494 VALIDATE_DESC(desc);
3496 * Handle FLAG_TRANSITORY first, enabling queries to gpiolib for
3497 * persistence state.
3499 assign_bit(FLAG_TRANSITORY, &desc->flags, transitory);
3501 /* If the driver supports it, set the persistence state now */
3502 chip = desc->gdev->chip;
3503 if (!chip->set_config)
3506 packed = pinconf_to_config_packed(PIN_CONFIG_PERSIST_STATE,
3508 gpio = gpio_chip_hwgpio(desc);
3509 rc = gpio_set_config(chip, gpio, packed);
3510 if (rc == -ENOTSUPP) {
3511 dev_dbg(&desc->gdev->dev, "Persistence not supported for GPIO %d\n",
3518 EXPORT_SYMBOL_GPL(gpiod_set_transitory);
3521 * gpiod_is_active_low - test whether a GPIO is active-low or not
3522 * @desc: the gpio descriptor to test
3524 * Returns 1 if the GPIO is active-low, 0 otherwise.
3526 int gpiod_is_active_low(const struct gpio_desc *desc)
3528 VALIDATE_DESC(desc);
3529 return test_bit(FLAG_ACTIVE_LOW, &desc->flags);
3531 EXPORT_SYMBOL_GPL(gpiod_is_active_low);
3534 * gpiod_toggle_active_low - toggle whether a GPIO is active-low or not
3535 * @desc: the gpio descriptor to change
3537 void gpiod_toggle_active_low(struct gpio_desc *desc)
3539 VALIDATE_DESC_VOID(desc);
3540 change_bit(FLAG_ACTIVE_LOW, &desc->flags);
3542 EXPORT_SYMBOL_GPL(gpiod_toggle_active_low);
3544 /* I/O calls are only valid after configuration completed; the relevant
3545 * "is this a valid GPIO" error checks should already have been done.
3547 * "Get" operations are often inlinable as reading a pin value register,
3548 * and masking the relevant bit in that register.
3550 * When "set" operations are inlinable, they involve writing that mask to
3551 * one register to set a low value, or a different register to set it high.
3552 * Otherwise locking is needed, so there may be little value to inlining.
3554 *------------------------------------------------------------------------
3556 * IMPORTANT!!! The hot paths -- get/set value -- assume that callers
3557 * have requested the GPIO. That can include implicit requesting by
3558 * a direction setting call. Marking a gpio as requested locks its chip
3559 * in memory, guaranteeing that these table lookups need no more locking
3560 * and that gpiochip_remove() will fail.
3562 * REVISIT when debugging, consider adding some instrumentation to ensure
3563 * that the GPIO was actually requested.
3566 static int gpiod_get_raw_value_commit(const struct gpio_desc *desc)
3568 struct gpio_chip *chip;
3572 chip = desc->gdev->chip;
3573 offset = gpio_chip_hwgpio(desc);
3574 value = chip->get ? chip->get(chip, offset) : -EIO;
3575 value = value < 0 ? value : !!value;
3576 trace_gpio_value(desc_to_gpio(desc), 1, value);
3580 static int gpio_chip_get_multiple(struct gpio_chip *chip,
3581 unsigned long *mask, unsigned long *bits)
3583 if (chip->get_multiple) {
3584 return chip->get_multiple(chip, mask, bits);
3585 } else if (chip->get) {
3588 for_each_set_bit(i, mask, chip->ngpio) {
3589 value = chip->get(chip, i);
3592 __assign_bit(i, bits, value);
3599 int gpiod_get_array_value_complex(bool raw, bool can_sleep,
3600 unsigned int array_size,
3601 struct gpio_desc **desc_array,
3602 struct gpio_array *array_info,
3603 unsigned long *value_bitmap)
3608 * Validate array_info against desc_array and its size.
3609 * It should immediately follow desc_array if both
3610 * have been obtained from the same gpiod_get_array() call.
3612 if (array_info && array_info->desc == desc_array &&
3613 array_size <= array_info->size &&
3614 (void *)array_info == desc_array + array_info->size) {
3616 WARN_ON(array_info->chip->can_sleep);
3618 ret = gpio_chip_get_multiple(array_info->chip,
3619 array_info->get_mask,
3624 if (!raw && !bitmap_empty(array_info->invert_mask, array_size))
3625 bitmap_xor(value_bitmap, value_bitmap,
3626 array_info->invert_mask, array_size);
3628 if (bitmap_full(array_info->get_mask, array_size))
3631 i = find_first_zero_bit(array_info->get_mask, array_size);
3636 while (i < array_size) {
3637 struct gpio_chip *chip = desc_array[i]->gdev->chip;
3638 unsigned long fastpath[2 * BITS_TO_LONGS(FASTPATH_NGPIO)];
3639 unsigned long *mask, *bits;
3642 if (likely(chip->ngpio <= FASTPATH_NGPIO)) {
3645 mask = kmalloc_array(2 * BITS_TO_LONGS(chip->ngpio),
3647 can_sleep ? GFP_KERNEL : GFP_ATOMIC);
3652 bits = mask + BITS_TO_LONGS(chip->ngpio);
3653 bitmap_zero(mask, chip->ngpio);
3656 WARN_ON(chip->can_sleep);
3658 /* collect all inputs belonging to the same chip */
3661 const struct gpio_desc *desc = desc_array[i];
3662 int hwgpio = gpio_chip_hwgpio(desc);
3664 __set_bit(hwgpio, mask);
3668 i = find_next_zero_bit(array_info->get_mask,
3670 } while ((i < array_size) &&
3671 (desc_array[i]->gdev->chip == chip));
3673 ret = gpio_chip_get_multiple(chip, mask, bits);
3675 if (mask != fastpath)
3680 for (j = first; j < i; ) {
3681 const struct gpio_desc *desc = desc_array[j];
3682 int hwgpio = gpio_chip_hwgpio(desc);
3683 int value = test_bit(hwgpio, bits);
3685 if (!raw && test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3687 __assign_bit(j, value_bitmap, value);
3688 trace_gpio_value(desc_to_gpio(desc), 1, value);
3692 j = find_next_zero_bit(array_info->get_mask, i,
3696 if (mask != fastpath)
3703 * gpiod_get_raw_value() - return a gpio's raw value
3704 * @desc: gpio whose value will be returned
3706 * Return the GPIO's raw value, i.e. the value of the physical line disregarding
3707 * its ACTIVE_LOW status, or negative errno on failure.
3709 * This function can be called from contexts where we cannot sleep, and will
3710 * complain if the GPIO chip functions potentially sleep.
3712 int gpiod_get_raw_value(const struct gpio_desc *desc)
3714 VALIDATE_DESC(desc);
3715 /* Should be using gpiod_get_raw_value_cansleep() */
3716 WARN_ON(desc->gdev->chip->can_sleep);
3717 return gpiod_get_raw_value_commit(desc);
3719 EXPORT_SYMBOL_GPL(gpiod_get_raw_value);
3722 * gpiod_get_value() - return a gpio's value
3723 * @desc: gpio whose value will be returned
3725 * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
3726 * account, or negative errno on failure.
3728 * This function can be called from contexts where we cannot sleep, and will
3729 * complain if the GPIO chip functions potentially sleep.
3731 int gpiod_get_value(const struct gpio_desc *desc)
3735 VALIDATE_DESC(desc);
3736 /* Should be using gpiod_get_value_cansleep() */
3737 WARN_ON(desc->gdev->chip->can_sleep);
3739 value = gpiod_get_raw_value_commit(desc);
3743 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3748 EXPORT_SYMBOL_GPL(gpiod_get_value);
3751 * gpiod_get_raw_array_value() - read raw values from an array of GPIOs
3752 * @array_size: number of elements in the descriptor array / value bitmap
3753 * @desc_array: array of GPIO descriptors whose values will be read
3754 * @array_info: information on applicability of fast bitmap processing path
3755 * @value_bitmap: bitmap to store the read values
3757 * Read the raw values of the GPIOs, i.e. the values of the physical lines
3758 * without regard for their ACTIVE_LOW status. Return 0 in case of success,
3759 * else an error code.
3761 * This function can be called from contexts where we cannot sleep,
3762 * and it will complain if the GPIO chip functions potentially sleep.
3764 int gpiod_get_raw_array_value(unsigned int array_size,
3765 struct gpio_desc **desc_array,
3766 struct gpio_array *array_info,
3767 unsigned long *value_bitmap)
3771 return gpiod_get_array_value_complex(true, false, array_size,
3772 desc_array, array_info,
3775 EXPORT_SYMBOL_GPL(gpiod_get_raw_array_value);
3778 * gpiod_get_array_value() - read values from an array of GPIOs
3779 * @array_size: number of elements in the descriptor array / value bitmap
3780 * @desc_array: array of GPIO descriptors whose values will be read
3781 * @array_info: information on applicability of fast bitmap processing path
3782 * @value_bitmap: bitmap to store the read values
3784 * Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3785 * into account. Return 0 in case of success, else an error code.
3787 * This function can be called from contexts where we cannot sleep,
3788 * and it will complain if the GPIO chip functions potentially sleep.
3790 int gpiod_get_array_value(unsigned int array_size,
3791 struct gpio_desc **desc_array,
3792 struct gpio_array *array_info,
3793 unsigned long *value_bitmap)
3797 return gpiod_get_array_value_complex(false, false, array_size,
3798 desc_array, array_info,
3801 EXPORT_SYMBOL_GPL(gpiod_get_array_value);
3804 * gpio_set_open_drain_value_commit() - Set the open drain gpio's value.
3805 * @desc: gpio descriptor whose state need to be set.
3806 * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
3808 static void gpio_set_open_drain_value_commit(struct gpio_desc *desc, bool value)
3811 struct gpio_chip *chip = desc->gdev->chip;
3812 int offset = gpio_chip_hwgpio(desc);
3815 ret = chip->direction_input(chip, offset);
3817 ret = chip->direction_output(chip, offset, 0);
3819 set_bit(FLAG_IS_OUT, &desc->flags);
3821 trace_gpio_direction(desc_to_gpio(desc), value, ret);
3824 "%s: Error in set_value for open drain err %d\n",
3829 * _gpio_set_open_source_value() - Set the open source gpio's value.
3830 * @desc: gpio descriptor whose state need to be set.
3831 * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
3833 static void gpio_set_open_source_value_commit(struct gpio_desc *desc, bool value)
3836 struct gpio_chip *chip = desc->gdev->chip;
3837 int offset = gpio_chip_hwgpio(desc);
3840 ret = chip->direction_output(chip, offset, 1);
3842 set_bit(FLAG_IS_OUT, &desc->flags);
3844 ret = chip->direction_input(chip, offset);
3846 trace_gpio_direction(desc_to_gpio(desc), !value, ret);
3849 "%s: Error in set_value for open source err %d\n",
3853 static void gpiod_set_raw_value_commit(struct gpio_desc *desc, bool value)
3855 struct gpio_chip *chip;
3857 chip = desc->gdev->chip;
3858 trace_gpio_value(desc_to_gpio(desc), 0, value);
3859 chip->set(chip, gpio_chip_hwgpio(desc), value);
3863 * set multiple outputs on the same chip;
3864 * use the chip's set_multiple function if available;
3865 * otherwise set the outputs sequentially;
3866 * @mask: bit mask array; one bit per output; BITS_PER_LONG bits per word
3867 * defines which outputs are to be changed
3868 * @bits: bit value array; one bit per output; BITS_PER_LONG bits per word
3869 * defines the values the outputs specified by mask are to be set to
3871 static void gpio_chip_set_multiple(struct gpio_chip *chip,
3872 unsigned long *mask, unsigned long *bits)
3874 if (chip->set_multiple) {
3875 chip->set_multiple(chip, mask, bits);
3879 /* set outputs if the corresponding mask bit is set */
3880 for_each_set_bit(i, mask, chip->ngpio)
3881 chip->set(chip, i, test_bit(i, bits));
3885 int gpiod_set_array_value_complex(bool raw, bool can_sleep,
3886 unsigned int array_size,
3887 struct gpio_desc **desc_array,
3888 struct gpio_array *array_info,
3889 unsigned long *value_bitmap)
3894 * Validate array_info against desc_array and its size.
3895 * It should immediately follow desc_array if both
3896 * have been obtained from the same gpiod_get_array() call.
3898 if (array_info && array_info->desc == desc_array &&
3899 array_size <= array_info->size &&
3900 (void *)array_info == desc_array + array_info->size) {
3902 WARN_ON(array_info->chip->can_sleep);
3904 if (!raw && !bitmap_empty(array_info->invert_mask, array_size))
3905 bitmap_xor(value_bitmap, value_bitmap,
3906 array_info->invert_mask, array_size);
3908 gpio_chip_set_multiple(array_info->chip, array_info->set_mask,
3911 if (bitmap_full(array_info->set_mask, array_size))
3914 i = find_first_zero_bit(array_info->set_mask, array_size);
3919 while (i < array_size) {
3920 struct gpio_chip *chip = desc_array[i]->gdev->chip;
3921 unsigned long fastpath[2 * BITS_TO_LONGS(FASTPATH_NGPIO)];
3922 unsigned long *mask, *bits;
3925 if (likely(chip->ngpio <= FASTPATH_NGPIO)) {
3928 mask = kmalloc_array(2 * BITS_TO_LONGS(chip->ngpio),
3930 can_sleep ? GFP_KERNEL : GFP_ATOMIC);
3935 bits = mask + BITS_TO_LONGS(chip->ngpio);
3936 bitmap_zero(mask, chip->ngpio);
3939 WARN_ON(chip->can_sleep);
3942 struct gpio_desc *desc = desc_array[i];
3943 int hwgpio = gpio_chip_hwgpio(desc);
3944 int value = test_bit(i, value_bitmap);
3947 * Pins applicable for fast input but not for
3948 * fast output processing may have been already
3949 * inverted inside the fast path, skip them.
3951 if (!raw && !(array_info &&
3952 test_bit(i, array_info->invert_mask)) &&
3953 test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3955 trace_gpio_value(desc_to_gpio(desc), 0, value);
3957 * collect all normal outputs belonging to the same chip
3958 * open drain and open source outputs are set individually
3960 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags) && !raw) {
3961 gpio_set_open_drain_value_commit(desc, value);
3962 } else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags) && !raw) {
3963 gpio_set_open_source_value_commit(desc, value);
3965 __set_bit(hwgpio, mask);
3966 __assign_bit(hwgpio, bits, value);
3972 i = find_next_zero_bit(array_info->set_mask,
3974 } while ((i < array_size) &&
3975 (desc_array[i]->gdev->chip == chip));
3976 /* push collected bits to outputs */
3978 gpio_chip_set_multiple(chip, mask, bits);
3980 if (mask != fastpath)
3987 * gpiod_set_raw_value() - assign a gpio's raw value
3988 * @desc: gpio whose value will be assigned
3989 * @value: value to assign
3991 * Set the raw value of the GPIO, i.e. the value of its physical line without
3992 * regard for its ACTIVE_LOW status.
3994 * This function can be called from contexts where we cannot sleep, and will
3995 * complain if the GPIO chip functions potentially sleep.
3997 void gpiod_set_raw_value(struct gpio_desc *desc, int value)
3999 VALIDATE_DESC_VOID(desc);
4000 /* Should be using gpiod_set_raw_value_cansleep() */
4001 WARN_ON(desc->gdev->chip->can_sleep);
4002 gpiod_set_raw_value_commit(desc, value);
4004 EXPORT_SYMBOL_GPL(gpiod_set_raw_value);
4007 * gpiod_set_value_nocheck() - set a GPIO line value without checking
4008 * @desc: the descriptor to set the value on
4009 * @value: value to set
4011 * This sets the value of a GPIO line backing a descriptor, applying
4012 * different semantic quirks like active low and open drain/source
4015 static void gpiod_set_value_nocheck(struct gpio_desc *desc, int value)
4017 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
4019 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
4020 gpio_set_open_drain_value_commit(desc, value);
4021 else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
4022 gpio_set_open_source_value_commit(desc, value);
4024 gpiod_set_raw_value_commit(desc, value);
4028 * gpiod_set_value() - assign a gpio's value
4029 * @desc: gpio whose value will be assigned
4030 * @value: value to assign
4032 * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW,
4033 * OPEN_DRAIN and OPEN_SOURCE flags into account.
4035 * This function can be called from contexts where we cannot sleep, and will
4036 * complain if the GPIO chip functions potentially sleep.
4038 void gpiod_set_value(struct gpio_desc *desc, int value)
4040 VALIDATE_DESC_VOID(desc);
4041 /* Should be using gpiod_set_value_cansleep() */
4042 WARN_ON(desc->gdev->chip->can_sleep);
4043 gpiod_set_value_nocheck(desc, value);
4045 EXPORT_SYMBOL_GPL(gpiod_set_value);
4048 * gpiod_set_raw_array_value() - assign values to an array of GPIOs
4049 * @array_size: number of elements in the descriptor array / value bitmap
4050 * @desc_array: array of GPIO descriptors whose values will be assigned
4051 * @array_info: information on applicability of fast bitmap processing path
4052 * @value_bitmap: bitmap of values to assign
4054 * Set the raw values of the GPIOs, i.e. the values of the physical lines
4055 * without regard for their ACTIVE_LOW status.
4057 * This function can be called from contexts where we cannot sleep, and will
4058 * complain if the GPIO chip functions potentially sleep.
4060 int gpiod_set_raw_array_value(unsigned int array_size,
4061 struct gpio_desc **desc_array,
4062 struct gpio_array *array_info,
4063 unsigned long *value_bitmap)
4067 return gpiod_set_array_value_complex(true, false, array_size,
4068 desc_array, array_info, value_bitmap);
4070 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value);
4073 * gpiod_set_array_value() - assign values to an array of GPIOs
4074 * @array_size: number of elements in the descriptor array / value bitmap
4075 * @desc_array: array of GPIO descriptors whose values will be assigned
4076 * @array_info: information on applicability of fast bitmap processing path
4077 * @value_bitmap: bitmap of values to assign
4079 * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
4082 * This function can be called from contexts where we cannot sleep, and will
4083 * complain if the GPIO chip functions potentially sleep.
4085 int gpiod_set_array_value(unsigned int array_size,
4086 struct gpio_desc **desc_array,
4087 struct gpio_array *array_info,
4088 unsigned long *value_bitmap)
4092 return gpiod_set_array_value_complex(false, false, array_size,
4093 desc_array, array_info,
4096 EXPORT_SYMBOL_GPL(gpiod_set_array_value);
4099 * gpiod_cansleep() - report whether gpio value access may sleep
4100 * @desc: gpio to check
4103 int gpiod_cansleep(const struct gpio_desc *desc)
4105 VALIDATE_DESC(desc);
4106 return desc->gdev->chip->can_sleep;
4108 EXPORT_SYMBOL_GPL(gpiod_cansleep);
4111 * gpiod_set_consumer_name() - set the consumer name for the descriptor
4112 * @desc: gpio to set the consumer name on
4113 * @name: the new consumer name
4115 int gpiod_set_consumer_name(struct gpio_desc *desc, const char *name)
4117 VALIDATE_DESC(desc);
4119 name = kstrdup_const(name, GFP_KERNEL);
4124 kfree_const(desc->label);
4125 desc_set_label(desc, name);
4129 EXPORT_SYMBOL_GPL(gpiod_set_consumer_name);
4132 * gpiod_to_irq() - return the IRQ corresponding to a GPIO
4133 * @desc: gpio whose IRQ will be returned (already requested)
4135 * Return the IRQ corresponding to the passed GPIO, or an error code in case of
4138 int gpiod_to_irq(const struct gpio_desc *desc)
4140 struct gpio_chip *chip;
4144 * Cannot VALIDATE_DESC() here as gpiod_to_irq() consumer semantics
4145 * requires this function to not return zero on an invalid descriptor
4146 * but rather a negative error number.
4148 if (!desc || IS_ERR(desc) || !desc->gdev || !desc->gdev->chip)
4151 chip = desc->gdev->chip;
4152 offset = gpio_chip_hwgpio(desc);
4154 int retirq = chip->to_irq(chip, offset);
4156 /* Zero means NO_IRQ */
4164 EXPORT_SYMBOL_GPL(gpiod_to_irq);
4167 * gpiochip_lock_as_irq() - lock a GPIO to be used as IRQ
4168 * @chip: the chip the GPIO to lock belongs to
4169 * @offset: the offset of the GPIO to lock as IRQ
4171 * This is used directly by GPIO drivers that want to lock down
4172 * a certain GPIO line to be used for IRQs.
4174 int gpiochip_lock_as_irq(struct gpio_chip *chip, unsigned int offset)
4176 struct gpio_desc *desc;
4178 desc = gpiochip_get_desc(chip, offset);
4180 return PTR_ERR(desc);
4183 * If it's fast: flush the direction setting if something changed
4186 if (!chip->can_sleep && chip->get_direction) {
4187 int dir = gpiod_get_direction(desc);
4190 chip_err(chip, "%s: cannot get GPIO direction\n",
4196 if (test_bit(FLAG_IS_OUT, &desc->flags)) {
4198 "%s: tried to flag a GPIO set as output for IRQ\n",
4203 set_bit(FLAG_USED_AS_IRQ, &desc->flags);
4204 set_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
4207 * If the consumer has not set up a label (such as when the
4208 * IRQ is referenced from .to_irq()) we set up a label here
4209 * so it is clear this is used as an interrupt.
4212 desc_set_label(desc, "interrupt");
4216 EXPORT_SYMBOL_GPL(gpiochip_lock_as_irq);
4219 * gpiochip_unlock_as_irq() - unlock a GPIO used as IRQ
4220 * @chip: the chip the GPIO to lock belongs to
4221 * @offset: the offset of the GPIO to lock as IRQ
4223 * This is used directly by GPIO drivers that want to indicate
4224 * that a certain GPIO is no longer used exclusively for IRQ.
4226 void gpiochip_unlock_as_irq(struct gpio_chip *chip, unsigned int offset)
4228 struct gpio_desc *desc;
4230 desc = gpiochip_get_desc(chip, offset);
4234 clear_bit(FLAG_USED_AS_IRQ, &desc->flags);
4235 clear_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
4237 /* If we only had this marking, erase it */
4238 if (desc->label && !strcmp(desc->label, "interrupt"))
4239 desc_set_label(desc, NULL);
4241 EXPORT_SYMBOL_GPL(gpiochip_unlock_as_irq);
4243 void gpiochip_disable_irq(struct gpio_chip *chip, unsigned int offset)
4245 struct gpio_desc *desc = gpiochip_get_desc(chip, offset);
4247 if (!IS_ERR(desc) &&
4248 !WARN_ON(!test_bit(FLAG_USED_AS_IRQ, &desc->flags)))
4249 clear_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
4251 EXPORT_SYMBOL_GPL(gpiochip_disable_irq);
4253 void gpiochip_enable_irq(struct gpio_chip *chip, unsigned int offset)
4255 struct gpio_desc *desc = gpiochip_get_desc(chip, offset);
4257 if (!IS_ERR(desc) &&
4258 !WARN_ON(!test_bit(FLAG_USED_AS_IRQ, &desc->flags))) {
4259 WARN_ON(test_bit(FLAG_IS_OUT, &desc->flags));
4260 set_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
4263 EXPORT_SYMBOL_GPL(gpiochip_enable_irq);
4265 bool gpiochip_line_is_irq(struct gpio_chip *chip, unsigned int offset)
4267 if (offset >= chip->ngpio)
4270 return test_bit(FLAG_USED_AS_IRQ, &chip->gpiodev->descs[offset].flags);
4272 EXPORT_SYMBOL_GPL(gpiochip_line_is_irq);
4274 int gpiochip_reqres_irq(struct gpio_chip *chip, unsigned int offset)
4278 if (!try_module_get(chip->gpiodev->owner))
4281 ret = gpiochip_lock_as_irq(chip, offset);
4283 chip_err(chip, "unable to lock HW IRQ %u for IRQ\n", offset);
4284 module_put(chip->gpiodev->owner);
4289 EXPORT_SYMBOL_GPL(gpiochip_reqres_irq);
4291 void gpiochip_relres_irq(struct gpio_chip *chip, unsigned int offset)
4293 gpiochip_unlock_as_irq(chip, offset);
4294 module_put(chip->gpiodev->owner);
4296 EXPORT_SYMBOL_GPL(gpiochip_relres_irq);
4298 bool gpiochip_line_is_open_drain(struct gpio_chip *chip, unsigned int offset)
4300 if (offset >= chip->ngpio)
4303 return test_bit(FLAG_OPEN_DRAIN, &chip->gpiodev->descs[offset].flags);
4305 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_drain);
4307 bool gpiochip_line_is_open_source(struct gpio_chip *chip, unsigned int offset)
4309 if (offset >= chip->ngpio)
4312 return test_bit(FLAG_OPEN_SOURCE, &chip->gpiodev->descs[offset].flags);
4314 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_source);
4316 bool gpiochip_line_is_persistent(struct gpio_chip *chip, unsigned int offset)
4318 if (offset >= chip->ngpio)
4321 return !test_bit(FLAG_TRANSITORY, &chip->gpiodev->descs[offset].flags);
4323 EXPORT_SYMBOL_GPL(gpiochip_line_is_persistent);
4326 * gpiod_get_raw_value_cansleep() - return a gpio's raw value
4327 * @desc: gpio whose value will be returned
4329 * Return the GPIO's raw value, i.e. the value of the physical line disregarding
4330 * its ACTIVE_LOW status, or negative errno on failure.
4332 * This function is to be called from contexts that can sleep.
4334 int gpiod_get_raw_value_cansleep(const struct gpio_desc *desc)
4336 might_sleep_if(extra_checks);
4337 VALIDATE_DESC(desc);
4338 return gpiod_get_raw_value_commit(desc);
4340 EXPORT_SYMBOL_GPL(gpiod_get_raw_value_cansleep);
4343 * gpiod_get_value_cansleep() - return a gpio's value
4344 * @desc: gpio whose value will be returned
4346 * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
4347 * account, or negative errno on failure.
4349 * This function is to be called from contexts that can sleep.
4351 int gpiod_get_value_cansleep(const struct gpio_desc *desc)
4355 might_sleep_if(extra_checks);
4356 VALIDATE_DESC(desc);
4357 value = gpiod_get_raw_value_commit(desc);
4361 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
4366 EXPORT_SYMBOL_GPL(gpiod_get_value_cansleep);
4369 * gpiod_get_raw_array_value_cansleep() - read raw values from an array of GPIOs
4370 * @array_size: number of elements in the descriptor array / value bitmap
4371 * @desc_array: array of GPIO descriptors whose values will be read
4372 * @array_info: information on applicability of fast bitmap processing path
4373 * @value_bitmap: bitmap to store the read values
4375 * Read the raw values of the GPIOs, i.e. the values of the physical lines
4376 * without regard for their ACTIVE_LOW status. Return 0 in case of success,
4377 * else an error code.
4379 * This function is to be called from contexts that can sleep.
4381 int gpiod_get_raw_array_value_cansleep(unsigned int array_size,
4382 struct gpio_desc **desc_array,
4383 struct gpio_array *array_info,
4384 unsigned long *value_bitmap)
4386 might_sleep_if(extra_checks);
4389 return gpiod_get_array_value_complex(true, true, array_size,
4390 desc_array, array_info,
4393 EXPORT_SYMBOL_GPL(gpiod_get_raw_array_value_cansleep);
4396 * gpiod_get_array_value_cansleep() - read values from an array of GPIOs
4397 * @array_size: number of elements in the descriptor array / value bitmap
4398 * @desc_array: array of GPIO descriptors whose values will be read
4399 * @array_info: information on applicability of fast bitmap processing path
4400 * @value_bitmap: bitmap to store the read values
4402 * Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
4403 * into account. Return 0 in case of success, else an error code.
4405 * This function is to be called from contexts that can sleep.
4407 int gpiod_get_array_value_cansleep(unsigned int array_size,
4408 struct gpio_desc **desc_array,
4409 struct gpio_array *array_info,
4410 unsigned long *value_bitmap)
4412 might_sleep_if(extra_checks);
4415 return gpiod_get_array_value_complex(false, true, array_size,
4416 desc_array, array_info,
4419 EXPORT_SYMBOL_GPL(gpiod_get_array_value_cansleep);
4422 * gpiod_set_raw_value_cansleep() - assign a gpio's raw value
4423 * @desc: gpio whose value will be assigned
4424 * @value: value to assign
4426 * Set the raw value of the GPIO, i.e. the value of its physical line without
4427 * regard for its ACTIVE_LOW status.
4429 * This function is to be called from contexts that can sleep.
4431 void gpiod_set_raw_value_cansleep(struct gpio_desc *desc, int value)
4433 might_sleep_if(extra_checks);
4434 VALIDATE_DESC_VOID(desc);
4435 gpiod_set_raw_value_commit(desc, value);
4437 EXPORT_SYMBOL_GPL(gpiod_set_raw_value_cansleep);
4440 * gpiod_set_value_cansleep() - assign a gpio's value
4441 * @desc: gpio whose value will be assigned
4442 * @value: value to assign
4444 * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
4447 * This function is to be called from contexts that can sleep.
4449 void gpiod_set_value_cansleep(struct gpio_desc *desc, int value)
4451 might_sleep_if(extra_checks);
4452 VALIDATE_DESC_VOID(desc);
4453 gpiod_set_value_nocheck(desc, value);
4455 EXPORT_SYMBOL_GPL(gpiod_set_value_cansleep);
4458 * gpiod_set_raw_array_value_cansleep() - assign values to an array of GPIOs
4459 * @array_size: number of elements in the descriptor array / value bitmap
4460 * @desc_array: array of GPIO descriptors whose values will be assigned
4461 * @array_info: information on applicability of fast bitmap processing path
4462 * @value_bitmap: bitmap of values to assign
4464 * Set the raw values of the GPIOs, i.e. the values of the physical lines
4465 * without regard for their ACTIVE_LOW status.
4467 * This function is to be called from contexts that can sleep.
4469 int gpiod_set_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_set_array_value_complex(true, true, array_size, desc_array,
4478 array_info, value_bitmap);
4480 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value_cansleep);
4483 * gpiod_add_lookup_tables() - register GPIO device consumers
4484 * @tables: list of tables of consumers to register
4485 * @n: number of tables in the list
4487 void gpiod_add_lookup_tables(struct gpiod_lookup_table **tables, size_t n)
4491 mutex_lock(&gpio_lookup_lock);
4493 for (i = 0; i < n; i++)
4494 list_add_tail(&tables[i]->list, &gpio_lookup_list);
4496 mutex_unlock(&gpio_lookup_lock);
4500 * gpiod_set_array_value_cansleep() - assign values to an array of GPIOs
4501 * @array_size: number of elements in the descriptor array / value bitmap
4502 * @desc_array: array of GPIO descriptors whose values will be assigned
4503 * @array_info: information on applicability of fast bitmap processing path
4504 * @value_bitmap: bitmap of values to assign
4506 * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
4509 * This function is to be called from contexts that can sleep.
4511 int gpiod_set_array_value_cansleep(unsigned int array_size,
4512 struct gpio_desc **desc_array,
4513 struct gpio_array *array_info,
4514 unsigned long *value_bitmap)
4516 might_sleep_if(extra_checks);
4519 return gpiod_set_array_value_complex(false, true, array_size,
4520 desc_array, array_info,
4523 EXPORT_SYMBOL_GPL(gpiod_set_array_value_cansleep);
4526 * gpiod_add_lookup_table() - register GPIO device consumers
4527 * @table: table of consumers to register
4529 void gpiod_add_lookup_table(struct gpiod_lookup_table *table)
4531 mutex_lock(&gpio_lookup_lock);
4533 list_add_tail(&table->list, &gpio_lookup_list);
4535 mutex_unlock(&gpio_lookup_lock);
4537 EXPORT_SYMBOL_GPL(gpiod_add_lookup_table);
4540 * gpiod_remove_lookup_table() - unregister GPIO device consumers
4541 * @table: table of consumers to unregister
4543 void gpiod_remove_lookup_table(struct gpiod_lookup_table *table)
4545 mutex_lock(&gpio_lookup_lock);
4547 list_del(&table->list);
4549 mutex_unlock(&gpio_lookup_lock);
4551 EXPORT_SYMBOL_GPL(gpiod_remove_lookup_table);
4554 * gpiod_add_hogs() - register a set of GPIO hogs from machine code
4555 * @hogs: table of gpio hog entries with a zeroed sentinel at the end
4557 void gpiod_add_hogs(struct gpiod_hog *hogs)
4559 struct gpio_chip *chip;
4560 struct gpiod_hog *hog;
4562 mutex_lock(&gpio_machine_hogs_mutex);
4564 for (hog = &hogs[0]; hog->chip_label; hog++) {
4565 list_add_tail(&hog->list, &gpio_machine_hogs);
4568 * The chip may have been registered earlier, so check if it
4569 * exists and, if so, try to hog the line now.
4571 chip = find_chip_by_name(hog->chip_label);
4573 gpiochip_machine_hog(chip, hog);
4576 mutex_unlock(&gpio_machine_hogs_mutex);
4578 EXPORT_SYMBOL_GPL(gpiod_add_hogs);
4580 static struct gpiod_lookup_table *gpiod_find_lookup_table(struct device *dev)
4582 const char *dev_id = dev ? dev_name(dev) : NULL;
4583 struct gpiod_lookup_table *table;
4585 mutex_lock(&gpio_lookup_lock);
4587 list_for_each_entry(table, &gpio_lookup_list, list) {
4588 if (table->dev_id && dev_id) {
4590 * Valid strings on both ends, must be identical to have
4593 if (!strcmp(table->dev_id, dev_id))
4597 * One of the pointers is NULL, so both must be to have
4600 if (dev_id == table->dev_id)
4607 mutex_unlock(&gpio_lookup_lock);
4611 static struct gpio_desc *gpiod_find(struct device *dev, const char *con_id,
4612 unsigned int idx, unsigned long *flags)
4614 struct gpio_desc *desc = ERR_PTR(-ENOENT);
4615 struct gpiod_lookup_table *table;
4616 struct gpiod_lookup *p;
4618 table = gpiod_find_lookup_table(dev);
4622 for (p = &table->table[0]; p->chip_label; p++) {
4623 struct gpio_chip *chip;
4625 /* idx must always match exactly */
4629 /* If the lookup entry has a con_id, require exact match */
4630 if (p->con_id && (!con_id || strcmp(p->con_id, con_id)))
4633 chip = find_chip_by_name(p->chip_label);
4637 * As the lookup table indicates a chip with
4638 * p->chip_label should exist, assume it may
4639 * still appear later and let the interested
4640 * consumer be probed again or let the Deferred
4641 * Probe infrastructure handle the error.
4643 dev_warn(dev, "cannot find GPIO chip %s, deferring\n",
4645 return ERR_PTR(-EPROBE_DEFER);
4648 if (chip->ngpio <= p->chip_hwnum) {
4650 "requested GPIO %u (%u) is out of range [0..%u] for chip %s\n",
4651 idx, p->chip_hwnum, chip->ngpio - 1,
4653 return ERR_PTR(-EINVAL);
4656 desc = gpiochip_get_desc(chip, p->chip_hwnum);
4665 static int platform_gpio_count(struct device *dev, const char *con_id)
4667 struct gpiod_lookup_table *table;
4668 struct gpiod_lookup *p;
4669 unsigned int count = 0;
4671 table = gpiod_find_lookup_table(dev);
4675 for (p = &table->table[0]; p->chip_label; p++) {
4676 if ((con_id && p->con_id && !strcmp(con_id, p->con_id)) ||
4677 (!con_id && !p->con_id))
4687 * fwnode_gpiod_get_index - obtain a GPIO from firmware node
4688 * @fwnode: handle of the firmware node
4689 * @con_id: function within the GPIO consumer
4690 * @index: index of the GPIO to obtain for the consumer
4691 * @flags: GPIO initialization flags
4692 * @label: label to attach to the requested GPIO
4694 * This function can be used for drivers that get their configuration
4695 * from opaque firmware.
4697 * The function properly finds the corresponding GPIO using whatever is the
4698 * underlying firmware interface and then makes sure that the GPIO
4699 * descriptor is requested before it is returned to the caller.
4702 * On successful request the GPIO pin is configured in accordance with
4705 * In case of error an ERR_PTR() is returned.
4707 struct gpio_desc *fwnode_gpiod_get_index(struct fwnode_handle *fwnode,
4708 const char *con_id, int index,
4709 enum gpiod_flags flags,
4712 struct gpio_desc *desc;
4713 char prop_name[32]; /* 32 is max size of property name */
4716 for (i = 0; i < ARRAY_SIZE(gpio_suffixes); i++) {
4718 snprintf(prop_name, sizeof(prop_name), "%s-%s",
4719 con_id, gpio_suffixes[i]);
4721 snprintf(prop_name, sizeof(prop_name), "%s",
4724 desc = fwnode_get_named_gpiod(fwnode, prop_name, index, flags,
4726 if (!IS_ERR(desc) || (PTR_ERR(desc) != -ENOENT))
4732 EXPORT_SYMBOL_GPL(fwnode_gpiod_get_index);
4735 * gpiod_count - return the number of GPIOs associated with a device / function
4736 * or -ENOENT if no GPIO has been assigned to the requested function
4737 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4738 * @con_id: function within the GPIO consumer
4740 int gpiod_count(struct device *dev, const char *con_id)
4742 int count = -ENOENT;
4744 if (IS_ENABLED(CONFIG_OF) && dev && dev->of_node)
4745 count = of_gpio_get_count(dev, con_id);
4746 else if (IS_ENABLED(CONFIG_ACPI) && dev && ACPI_HANDLE(dev))
4747 count = acpi_gpio_count(dev, con_id);
4750 count = platform_gpio_count(dev, con_id);
4754 EXPORT_SYMBOL_GPL(gpiod_count);
4757 * gpiod_get - obtain a GPIO for a given GPIO function
4758 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4759 * @con_id: function within the GPIO consumer
4760 * @flags: optional GPIO initialization flags
4762 * Return the GPIO descriptor corresponding to the function con_id of device
4763 * dev, -ENOENT if no GPIO has been assigned to the requested function, or
4764 * another IS_ERR() code if an error occurred while trying to acquire the GPIO.
4766 struct gpio_desc *__must_check gpiod_get(struct device *dev, const char *con_id,
4767 enum gpiod_flags flags)
4769 return gpiod_get_index(dev, con_id, 0, flags);
4771 EXPORT_SYMBOL_GPL(gpiod_get);
4774 * gpiod_get_optional - obtain an optional GPIO for a given GPIO function
4775 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4776 * @con_id: function within the GPIO consumer
4777 * @flags: optional GPIO initialization flags
4779 * This is equivalent to gpiod_get(), except that when no GPIO was assigned to
4780 * the requested function it will return NULL. This is convenient for drivers
4781 * that need to handle optional GPIOs.
4783 struct gpio_desc *__must_check gpiod_get_optional(struct device *dev,
4785 enum gpiod_flags flags)
4787 return gpiod_get_index_optional(dev, con_id, 0, flags);
4789 EXPORT_SYMBOL_GPL(gpiod_get_optional);
4793 * gpiod_configure_flags - helper function to configure a given GPIO
4794 * @desc: gpio whose value will be assigned
4795 * @con_id: function within the GPIO consumer
4796 * @lflags: bitmask of gpio_lookup_flags GPIO_* values - returned from
4797 * of_find_gpio() or of_get_gpio_hog()
4798 * @dflags: gpiod_flags - optional GPIO initialization flags
4800 * Return 0 on success, -ENOENT if no GPIO has been assigned to the
4801 * requested function and/or index, or another IS_ERR() code if an error
4802 * occurred while trying to acquire the GPIO.
4804 int gpiod_configure_flags(struct gpio_desc *desc, const char *con_id,
4805 unsigned long lflags, enum gpiod_flags dflags)
4809 if (lflags & GPIO_ACTIVE_LOW)
4810 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
4812 if (lflags & GPIO_OPEN_DRAIN)
4813 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
4814 else if (dflags & GPIOD_FLAGS_BIT_OPEN_DRAIN) {
4816 * This enforces open drain mode from the consumer side.
4817 * This is necessary for some busses like I2C, but the lookup
4818 * should *REALLY* have specified them as open drain in the
4819 * first place, so print a little warning here.
4821 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
4823 "enforced open drain please flag it properly in DT/ACPI DSDT/board file\n");
4826 if (lflags & GPIO_OPEN_SOURCE)
4827 set_bit(FLAG_OPEN_SOURCE, &desc->flags);
4829 if ((lflags & GPIO_PULL_UP) && (lflags & GPIO_PULL_DOWN)) {
4831 "both pull-up and pull-down enabled, invalid configuration\n");
4835 if (lflags & GPIO_PULL_UP)
4836 set_bit(FLAG_PULL_UP, &desc->flags);
4837 else if (lflags & GPIO_PULL_DOWN)
4838 set_bit(FLAG_PULL_DOWN, &desc->flags);
4840 ret = gpiod_set_transitory(desc, (lflags & GPIO_TRANSITORY));
4844 /* No particular flag request, return here... */
4845 if (!(dflags & GPIOD_FLAGS_BIT_DIR_SET)) {
4846 pr_debug("no flags found for %s\n", con_id);
4851 if (dflags & GPIOD_FLAGS_BIT_DIR_OUT)
4852 ret = gpiod_direction_output(desc,
4853 !!(dflags & GPIOD_FLAGS_BIT_DIR_VAL));
4855 ret = gpiod_direction_input(desc);
4861 * gpiod_get_index - obtain a GPIO from a multi-index GPIO function
4862 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4863 * @con_id: function within the GPIO consumer
4864 * @idx: index of the GPIO to obtain in the consumer
4865 * @flags: optional GPIO initialization flags
4867 * This variant of gpiod_get() allows to access GPIOs other than the first
4868 * defined one for functions that define several GPIOs.
4870 * Return a valid GPIO descriptor, -ENOENT if no GPIO has been assigned to the
4871 * requested function and/or index, or another IS_ERR() code if an error
4872 * occurred while trying to acquire the GPIO.
4874 struct gpio_desc *__must_check gpiod_get_index(struct device *dev,
4877 enum gpiod_flags flags)
4879 unsigned long lookupflags = GPIO_LOOKUP_FLAGS_DEFAULT;
4880 struct gpio_desc *desc = NULL;
4882 /* Maybe we have a device name, maybe not */
4883 const char *devname = dev ? dev_name(dev) : "?";
4885 dev_dbg(dev, "GPIO lookup for consumer %s\n", con_id);
4888 /* Using device tree? */
4889 if (IS_ENABLED(CONFIG_OF) && dev->of_node) {
4890 dev_dbg(dev, "using device tree for GPIO lookup\n");
4891 desc = of_find_gpio(dev, con_id, idx, &lookupflags);
4892 } else if (ACPI_COMPANION(dev)) {
4893 dev_dbg(dev, "using ACPI for GPIO lookup\n");
4894 desc = acpi_find_gpio(dev, con_id, idx, &flags, &lookupflags);
4899 * Either we are not using DT or ACPI, or their lookup did not return
4900 * a result. In that case, use platform lookup as a fallback.
4902 if (!desc || desc == ERR_PTR(-ENOENT)) {
4903 dev_dbg(dev, "using lookup tables for GPIO lookup\n");
4904 desc = gpiod_find(dev, con_id, idx, &lookupflags);
4908 dev_dbg(dev, "No GPIO consumer %s found\n", con_id);
4913 * If a connection label was passed use that, else attempt to use
4914 * the device name as label
4916 ret = gpiod_request(desc, con_id ? con_id : devname);
4918 if (ret == -EBUSY && flags & GPIOD_FLAGS_BIT_NONEXCLUSIVE) {
4920 * This happens when there are several consumers for
4921 * the same GPIO line: we just return here without
4922 * further initialization. It is a bit if a hack.
4923 * This is necessary to support fixed regulators.
4925 * FIXME: Make this more sane and safe.
4927 dev_info(dev, "nonexclusive access to GPIO for %s\n",
4928 con_id ? con_id : devname);
4931 return ERR_PTR(ret);
4935 ret = gpiod_configure_flags(desc, con_id, lookupflags, flags);
4937 dev_dbg(dev, "setup of GPIO %s failed\n", con_id);
4939 return ERR_PTR(ret);
4944 EXPORT_SYMBOL_GPL(gpiod_get_index);
4947 * fwnode_get_named_gpiod - obtain a GPIO from firmware node
4948 * @fwnode: handle of the firmware node
4949 * @propname: name of the firmware property representing the GPIO
4950 * @index: index of the GPIO to obtain for the consumer
4951 * @dflags: GPIO initialization flags
4952 * @label: label to attach to the requested GPIO
4954 * This function can be used for drivers that get their configuration
4955 * from opaque firmware.
4957 * The function properly finds the corresponding GPIO using whatever is the
4958 * underlying firmware interface and then makes sure that the GPIO
4959 * descriptor is requested before it is returned to the caller.
4962 * On successful request the GPIO pin is configured in accordance with
4965 * In case of error an ERR_PTR() is returned.
4967 struct gpio_desc *fwnode_get_named_gpiod(struct fwnode_handle *fwnode,
4968 const char *propname, int index,
4969 enum gpiod_flags dflags,
4972 unsigned long lflags = GPIO_LOOKUP_FLAGS_DEFAULT;
4973 struct gpio_desc *desc = ERR_PTR(-ENODEV);
4977 return ERR_PTR(-EINVAL);
4979 if (is_of_node(fwnode)) {
4980 desc = gpiod_get_from_of_node(to_of_node(fwnode),
4985 } else if (is_acpi_node(fwnode)) {
4986 struct acpi_gpio_info info;
4988 desc = acpi_node_get_gpiod(fwnode, propname, index, &info);
4992 acpi_gpio_update_gpiod_flags(&dflags, &info);
4993 acpi_gpio_update_gpiod_lookup_flags(&lflags, &info);
4996 /* Currently only ACPI takes this path */
4997 ret = gpiod_request(desc, label);
4999 return ERR_PTR(ret);
5001 ret = gpiod_configure_flags(desc, propname, lflags, dflags);
5004 return ERR_PTR(ret);
5009 EXPORT_SYMBOL_GPL(fwnode_get_named_gpiod);
5012 * gpiod_get_index_optional - obtain an optional GPIO from a multi-index GPIO
5014 * @dev: GPIO consumer, can be NULL for system-global GPIOs
5015 * @con_id: function within the GPIO consumer
5016 * @index: index of the GPIO to obtain in the consumer
5017 * @flags: optional GPIO initialization flags
5019 * This is equivalent to gpiod_get_index(), except that when no GPIO with the
5020 * specified index was assigned to the requested function it will return NULL.
5021 * This is convenient for drivers that need to handle optional GPIOs.
5023 struct gpio_desc *__must_check gpiod_get_index_optional(struct device *dev,
5026 enum gpiod_flags flags)
5028 struct gpio_desc *desc;
5030 desc = gpiod_get_index(dev, con_id, index, flags);
5032 if (PTR_ERR(desc) == -ENOENT)
5038 EXPORT_SYMBOL_GPL(gpiod_get_index_optional);
5041 * gpiod_hog - Hog the specified GPIO desc given the provided flags
5042 * @desc: gpio whose value will be assigned
5043 * @name: gpio line name
5044 * @lflags: bitmask of gpio_lookup_flags GPIO_* values - returned from
5045 * of_find_gpio() or of_get_gpio_hog()
5046 * @dflags: gpiod_flags - optional GPIO initialization flags
5048 int gpiod_hog(struct gpio_desc *desc, const char *name,
5049 unsigned long lflags, enum gpiod_flags dflags)
5051 struct gpio_chip *chip;
5052 struct gpio_desc *local_desc;
5056 chip = gpiod_to_chip(desc);
5057 hwnum = gpio_chip_hwgpio(desc);
5059 local_desc = gpiochip_request_own_desc(chip, hwnum, name,
5061 if (IS_ERR(local_desc)) {
5062 ret = PTR_ERR(local_desc);
5063 pr_err("requesting hog GPIO %s (chip %s, offset %d) failed, %d\n",
5064 name, chip->label, hwnum, ret);
5068 /* Mark GPIO as hogged so it can be identified and removed later */
5069 set_bit(FLAG_IS_HOGGED, &desc->flags);
5071 pr_info("GPIO line %d (%s) hogged as %s%s\n",
5072 desc_to_gpio(desc), name,
5073 (dflags & GPIOD_FLAGS_BIT_DIR_OUT) ? "output" : "input",
5074 (dflags & GPIOD_FLAGS_BIT_DIR_OUT) ?
5075 (dflags & GPIOD_FLAGS_BIT_DIR_VAL) ? "/high" : "/low" : "");
5081 * gpiochip_free_hogs - Scan gpio-controller chip and release GPIO hog
5082 * @chip: gpio chip to act on
5084 static void gpiochip_free_hogs(struct gpio_chip *chip)
5088 for (id = 0; id < chip->ngpio; id++) {
5089 if (test_bit(FLAG_IS_HOGGED, &chip->gpiodev->descs[id].flags))
5090 gpiochip_free_own_desc(&chip->gpiodev->descs[id]);
5095 * gpiod_get_array - obtain multiple GPIOs from a multi-index GPIO function
5096 * @dev: GPIO consumer, can be NULL for system-global GPIOs
5097 * @con_id: function within the GPIO consumer
5098 * @flags: optional GPIO initialization flags
5100 * This function acquires all the GPIOs defined under a given function.
5102 * Return a struct gpio_descs containing an array of descriptors, -ENOENT if
5103 * no GPIO has been assigned to the requested function, or another IS_ERR()
5104 * code if an error occurred while trying to acquire the GPIOs.
5106 struct gpio_descs *__must_check gpiod_get_array(struct device *dev,
5108 enum gpiod_flags flags)
5110 struct gpio_desc *desc;
5111 struct gpio_descs *descs;
5112 struct gpio_array *array_info = NULL;
5113 struct gpio_chip *chip;
5114 int count, bitmap_size;
5116 count = gpiod_count(dev, con_id);
5118 return ERR_PTR(count);
5120 descs = kzalloc(struct_size(descs, desc, count), GFP_KERNEL);
5122 return ERR_PTR(-ENOMEM);
5124 for (descs->ndescs = 0; descs->ndescs < count; ) {
5125 desc = gpiod_get_index(dev, con_id, descs->ndescs, flags);
5127 gpiod_put_array(descs);
5128 return ERR_CAST(desc);
5131 descs->desc[descs->ndescs] = desc;
5133 chip = gpiod_to_chip(desc);
5135 * If pin hardware number of array member 0 is also 0, select
5136 * its chip as a candidate for fast bitmap processing path.
5138 if (descs->ndescs == 0 && gpio_chip_hwgpio(desc) == 0) {
5139 struct gpio_descs *array;
5141 bitmap_size = BITS_TO_LONGS(chip->ngpio > count ?
5142 chip->ngpio : count);
5144 array = kzalloc(struct_size(descs, desc, count) +
5145 struct_size(array_info, invert_mask,
5146 3 * bitmap_size), GFP_KERNEL);
5148 gpiod_put_array(descs);
5149 return ERR_PTR(-ENOMEM);
5152 memcpy(array, descs,
5153 struct_size(descs, desc, descs->ndescs + 1));
5157 array_info = (void *)(descs->desc + count);
5158 array_info->get_mask = array_info->invert_mask +
5160 array_info->set_mask = array_info->get_mask +
5163 array_info->desc = descs->desc;
5164 array_info->size = count;
5165 array_info->chip = chip;
5166 bitmap_set(array_info->get_mask, descs->ndescs,
5167 count - descs->ndescs);
5168 bitmap_set(array_info->set_mask, descs->ndescs,
5169 count - descs->ndescs);
5170 descs->info = array_info;
5172 /* Unmark array members which don't belong to the 'fast' chip */
5173 if (array_info && array_info->chip != chip) {
5174 __clear_bit(descs->ndescs, array_info->get_mask);
5175 __clear_bit(descs->ndescs, array_info->set_mask);
5178 * Detect array members which belong to the 'fast' chip
5179 * but their pins are not in hardware order.
5181 else if (array_info &&
5182 gpio_chip_hwgpio(desc) != descs->ndescs) {
5184 * Don't use fast path if all array members processed so
5185 * far belong to the same chip as this one but its pin
5186 * hardware number is different from its array index.
5188 if (bitmap_full(array_info->get_mask, descs->ndescs)) {
5191 __clear_bit(descs->ndescs,
5192 array_info->get_mask);
5193 __clear_bit(descs->ndescs,
5194 array_info->set_mask);
5196 } else if (array_info) {
5197 /* Exclude open drain or open source from fast output */
5198 if (gpiochip_line_is_open_drain(chip, descs->ndescs) ||
5199 gpiochip_line_is_open_source(chip, descs->ndescs))
5200 __clear_bit(descs->ndescs,
5201 array_info->set_mask);
5202 /* Identify 'fast' pins which require invertion */
5203 if (gpiod_is_active_low(desc))
5204 __set_bit(descs->ndescs,
5205 array_info->invert_mask);
5212 "GPIO array info: chip=%s, size=%d, get_mask=%lx, set_mask=%lx, invert_mask=%lx\n",
5213 array_info->chip->label, array_info->size,
5214 *array_info->get_mask, *array_info->set_mask,
5215 *array_info->invert_mask);
5218 EXPORT_SYMBOL_GPL(gpiod_get_array);
5221 * gpiod_get_array_optional - obtain multiple GPIOs from a multi-index GPIO
5223 * @dev: GPIO consumer, can be NULL for system-global GPIOs
5224 * @con_id: function within the GPIO consumer
5225 * @flags: optional GPIO initialization flags
5227 * This is equivalent to gpiod_get_array(), except that when no GPIO was
5228 * assigned to the requested function it will return NULL.
5230 struct gpio_descs *__must_check gpiod_get_array_optional(struct device *dev,
5232 enum gpiod_flags flags)
5234 struct gpio_descs *descs;
5236 descs = gpiod_get_array(dev, con_id, flags);
5237 if (PTR_ERR(descs) == -ENOENT)
5242 EXPORT_SYMBOL_GPL(gpiod_get_array_optional);
5245 * gpiod_put - dispose of a GPIO descriptor
5246 * @desc: GPIO descriptor to dispose of
5248 * No descriptor can be used after gpiod_put() has been called on it.
5250 void gpiod_put(struct gpio_desc *desc)
5255 EXPORT_SYMBOL_GPL(gpiod_put);
5258 * gpiod_put_array - dispose of multiple GPIO descriptors
5259 * @descs: struct gpio_descs containing an array of descriptors
5261 void gpiod_put_array(struct gpio_descs *descs)
5265 for (i = 0; i < descs->ndescs; i++)
5266 gpiod_put(descs->desc[i]);
5270 EXPORT_SYMBOL_GPL(gpiod_put_array);
5272 static int __init gpiolib_dev_init(void)
5276 /* Register GPIO sysfs bus */
5277 ret = bus_register(&gpio_bus_type);
5279 pr_err("gpiolib: could not register GPIO bus type\n");
5283 ret = alloc_chrdev_region(&gpio_devt, 0, GPIO_DEV_MAX, GPIOCHIP_NAME);
5285 pr_err("gpiolib: failed to allocate char dev region\n");
5286 bus_unregister(&gpio_bus_type);
5290 gpiolib_initialized = true;
5291 gpiochip_setup_devs();
5293 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
5294 WARN_ON(of_reconfig_notifier_register(&gpio_of_notifier));
5298 core_initcall(gpiolib_dev_init);
5300 #ifdef CONFIG_DEBUG_FS
5302 static void gpiolib_dbg_show(struct seq_file *s, struct gpio_device *gdev)
5305 struct gpio_chip *chip = gdev->chip;
5306 unsigned gpio = gdev->base;
5307 struct gpio_desc *gdesc = &gdev->descs[0];
5312 for (i = 0; i < gdev->ngpio; i++, gpio++, gdesc++) {
5313 if (!test_bit(FLAG_REQUESTED, &gdesc->flags)) {
5315 seq_printf(s, " gpio-%-3d (%-20.20s)\n",
5321 gpiod_get_direction(gdesc);
5322 is_out = test_bit(FLAG_IS_OUT, &gdesc->flags);
5323 is_irq = test_bit(FLAG_USED_AS_IRQ, &gdesc->flags);
5324 active_low = test_bit(FLAG_ACTIVE_LOW, &gdesc->flags);
5325 seq_printf(s, " gpio-%-3d (%-20.20s|%-20.20s) %s %s %s%s",
5326 gpio, gdesc->name ? gdesc->name : "", gdesc->label,
5327 is_out ? "out" : "in ",
5328 chip->get ? (chip->get(chip, i) ? "hi" : "lo") : "? ",
5329 is_irq ? "IRQ " : "",
5330 active_low ? "ACTIVE LOW" : "");
5331 seq_printf(s, "\n");
5335 static void *gpiolib_seq_start(struct seq_file *s, loff_t *pos)
5337 unsigned long flags;
5338 struct gpio_device *gdev = NULL;
5339 loff_t index = *pos;
5343 spin_lock_irqsave(&gpio_lock, flags);
5344 list_for_each_entry(gdev, &gpio_devices, list)
5346 spin_unlock_irqrestore(&gpio_lock, flags);
5349 spin_unlock_irqrestore(&gpio_lock, flags);
5354 static void *gpiolib_seq_next(struct seq_file *s, void *v, loff_t *pos)
5356 unsigned long flags;
5357 struct gpio_device *gdev = v;
5360 spin_lock_irqsave(&gpio_lock, flags);
5361 if (list_is_last(&gdev->list, &gpio_devices))
5364 ret = list_entry(gdev->list.next, struct gpio_device, list);
5365 spin_unlock_irqrestore(&gpio_lock, flags);
5373 static void gpiolib_seq_stop(struct seq_file *s, void *v)
5377 static int gpiolib_seq_show(struct seq_file *s, void *v)
5379 struct gpio_device *gdev = v;
5380 struct gpio_chip *chip = gdev->chip;
5381 struct device *parent;
5384 seq_printf(s, "%s%s: (dangling chip)", (char *)s->private,
5385 dev_name(&gdev->dev));
5389 seq_printf(s, "%s%s: GPIOs %d-%d", (char *)s->private,
5390 dev_name(&gdev->dev),
5391 gdev->base, gdev->base + gdev->ngpio - 1);
5392 parent = chip->parent;
5394 seq_printf(s, ", parent: %s/%s",
5395 parent->bus ? parent->bus->name : "no-bus",
5398 seq_printf(s, ", %s", chip->label);
5399 if (chip->can_sleep)
5400 seq_printf(s, ", can sleep");
5401 seq_printf(s, ":\n");
5404 chip->dbg_show(s, chip);
5406 gpiolib_dbg_show(s, gdev);
5411 static const struct seq_operations gpiolib_seq_ops = {
5412 .start = gpiolib_seq_start,
5413 .next = gpiolib_seq_next,
5414 .stop = gpiolib_seq_stop,
5415 .show = gpiolib_seq_show,
5418 static int gpiolib_open(struct inode *inode, struct file *file)
5420 return seq_open(file, &gpiolib_seq_ops);
5423 static const struct file_operations gpiolib_operations = {
5424 .owner = THIS_MODULE,
5425 .open = gpiolib_open,
5427 .llseek = seq_lseek,
5428 .release = seq_release,
5431 static int __init gpiolib_debugfs_init(void)
5433 /* /sys/kernel/debug/gpio */
5434 debugfs_create_file("gpio", S_IFREG | S_IRUGO, NULL, NULL,
5435 &gpiolib_operations);
5438 subsys_initcall(gpiolib_debugfs_init);
5440 #endif /* DEBUG_FS */