1 #include <linux/bitmap.h>
2 #include <linux/kernel.h>
3 #include <linux/module.h>
4 #include <linux/interrupt.h>
6 #include <linux/spinlock.h>
7 #include <linux/list.h>
8 #include <linux/device.h>
10 #include <linux/debugfs.h>
11 #include <linux/seq_file.h>
12 #include <linux/gpio.h>
13 #include <linux/of_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>
33 #define CREATE_TRACE_POINTS
34 #include <trace/events/gpio.h>
36 /* Implementation infrastructure for GPIO interfaces.
38 * The GPIO programming interface allows for inlining speed-critical
39 * get/set operations for common cases, so that access to SOC-integrated
40 * GPIOs can sometimes cost only an instruction or two per bit.
44 /* When debugging, extend minimal trust to callers and platform code.
45 * Also emit diagnostic messages that may help initial bringup, when
46 * board setup or driver bugs are most common.
48 * Otherwise, minimize overhead in what may be bitbanging codepaths.
51 #define extra_checks 1
53 #define extra_checks 0
56 /* Device and char device-related information */
57 static DEFINE_IDA(gpio_ida);
58 static dev_t gpio_devt;
59 #define GPIO_DEV_MAX 256 /* 256 GPIO chip devices supported */
60 static struct bus_type gpio_bus_type = {
65 * Number of GPIOs to use for the fast path in set array
67 #define FASTPATH_NGPIO CONFIG_GPIOLIB_FASTPATH_LIMIT
69 /* gpio_lock prevents conflicts during gpio_desc[] table updates.
70 * While any GPIO is requested, its gpio_chip is not removable;
71 * each GPIO's "requested" flag serves as a lock and refcount.
73 DEFINE_SPINLOCK(gpio_lock);
75 static DEFINE_MUTEX(gpio_lookup_lock);
76 static LIST_HEAD(gpio_lookup_list);
77 LIST_HEAD(gpio_devices);
79 static DEFINE_MUTEX(gpio_machine_hogs_mutex);
80 static LIST_HEAD(gpio_machine_hogs);
82 static void gpiochip_free_hogs(struct gpio_chip *chip);
83 static int gpiochip_add_irqchip(struct gpio_chip *gpiochip,
84 struct lock_class_key *lock_key,
85 struct lock_class_key *request_key);
86 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip);
87 static int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gpiochip);
88 static void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gpiochip);
90 static bool gpiolib_initialized;
92 static inline void desc_set_label(struct gpio_desc *d, const char *label)
98 * gpio_to_desc - Convert a GPIO number to its descriptor
99 * @gpio: global GPIO number
102 * The GPIO descriptor associated with the given GPIO, or %NULL if no GPIO
103 * with the given number exists in the system.
105 struct gpio_desc *gpio_to_desc(unsigned gpio)
107 struct gpio_device *gdev;
110 spin_lock_irqsave(&gpio_lock, flags);
112 list_for_each_entry(gdev, &gpio_devices, list) {
113 if (gdev->base <= gpio &&
114 gdev->base + gdev->ngpio > gpio) {
115 spin_unlock_irqrestore(&gpio_lock, flags);
116 return &gdev->descs[gpio - gdev->base];
120 spin_unlock_irqrestore(&gpio_lock, flags);
122 if (!gpio_is_valid(gpio))
123 WARN(1, "invalid GPIO %d\n", gpio);
127 EXPORT_SYMBOL_GPL(gpio_to_desc);
130 * gpiochip_get_desc - get the GPIO descriptor corresponding to the given
131 * hardware number for this chip
133 * @hwnum: hardware number of the GPIO for this chip
136 * A pointer to the GPIO descriptor or %ERR_PTR(-EINVAL) if no GPIO exists
137 * in the given chip for the specified hardware number.
139 struct gpio_desc *gpiochip_get_desc(struct gpio_chip *chip,
142 struct gpio_device *gdev = chip->gpiodev;
144 if (hwnum >= gdev->ngpio)
145 return ERR_PTR(-EINVAL);
147 return &gdev->descs[hwnum];
151 * desc_to_gpio - convert a GPIO descriptor to the integer namespace
152 * @desc: GPIO descriptor
154 * This should disappear in the future but is needed since we still
155 * use GPIO numbers for error messages and sysfs nodes.
158 * The global GPIO number for the GPIO specified by its descriptor.
160 int desc_to_gpio(const struct gpio_desc *desc)
162 return desc->gdev->base + (desc - &desc->gdev->descs[0]);
164 EXPORT_SYMBOL_GPL(desc_to_gpio);
168 * gpiod_to_chip - Return the GPIO chip to which a GPIO descriptor belongs
169 * @desc: descriptor to return the chip of
171 struct gpio_chip *gpiod_to_chip(const struct gpio_desc *desc)
173 if (!desc || !desc->gdev)
175 return desc->gdev->chip;
177 EXPORT_SYMBOL_GPL(gpiod_to_chip);
179 /* dynamic allocation of GPIOs, e.g. on a hotplugged device */
180 static int gpiochip_find_base(int ngpio)
182 struct gpio_device *gdev;
183 int base = ARCH_NR_GPIOS - ngpio;
185 list_for_each_entry_reverse(gdev, &gpio_devices, list) {
186 /* found a free space? */
187 if (gdev->base + gdev->ngpio <= base)
190 /* nope, check the space right before the chip */
191 base = gdev->base - ngpio;
194 if (gpio_is_valid(base)) {
195 pr_debug("%s: found new base at %d\n", __func__, base);
198 pr_err("%s: cannot find free range\n", __func__);
204 * gpiod_get_direction - return the current direction of a GPIO
205 * @desc: GPIO to get the direction of
207 * Returns 0 for output, 1 for input, or an error code in case of error.
209 * This function may sleep if gpiod_cansleep() is true.
211 int gpiod_get_direction(struct gpio_desc *desc)
213 struct gpio_chip *chip;
217 chip = gpiod_to_chip(desc);
218 offset = gpio_chip_hwgpio(desc);
220 if (!chip->get_direction)
223 status = chip->get_direction(chip, offset);
225 /* GPIOF_DIR_IN, or other positive */
227 clear_bit(FLAG_IS_OUT, &desc->flags);
231 set_bit(FLAG_IS_OUT, &desc->flags);
235 EXPORT_SYMBOL_GPL(gpiod_get_direction);
238 * Add a new chip to the global chips list, keeping the list of chips sorted
239 * by range(means [base, base + ngpio - 1]) order.
241 * Return -EBUSY if the new chip overlaps with some other chip's integer
244 static int gpiodev_add_to_list(struct gpio_device *gdev)
246 struct gpio_device *prev, *next;
248 if (list_empty(&gpio_devices)) {
249 /* initial entry in list */
250 list_add_tail(&gdev->list, &gpio_devices);
254 next = list_entry(gpio_devices.next, struct gpio_device, list);
255 if (gdev->base + gdev->ngpio <= next->base) {
256 /* add before first entry */
257 list_add(&gdev->list, &gpio_devices);
261 prev = list_entry(gpio_devices.prev, struct gpio_device, list);
262 if (prev->base + prev->ngpio <= gdev->base) {
263 /* add behind last entry */
264 list_add_tail(&gdev->list, &gpio_devices);
268 list_for_each_entry_safe(prev, next, &gpio_devices, list) {
269 /* at the end of the list */
270 if (&next->list == &gpio_devices)
273 /* add between prev and next */
274 if (prev->base + prev->ngpio <= gdev->base
275 && gdev->base + gdev->ngpio <= next->base) {
276 list_add(&gdev->list, &prev->list);
281 dev_err(&gdev->dev, "GPIO integer space overlap, cannot add chip\n");
286 * Convert a GPIO name to its descriptor
288 static struct gpio_desc *gpio_name_to_desc(const char * const name)
290 struct gpio_device *gdev;
293 spin_lock_irqsave(&gpio_lock, flags);
295 list_for_each_entry(gdev, &gpio_devices, list) {
298 for (i = 0; i != gdev->ngpio; ++i) {
299 struct gpio_desc *desc = &gdev->descs[i];
301 if (!desc->name || !name)
304 if (!strcmp(desc->name, name)) {
305 spin_unlock_irqrestore(&gpio_lock, flags);
311 spin_unlock_irqrestore(&gpio_lock, flags);
317 * Takes the names from gc->names and checks if they are all unique. If they
318 * are, they are assigned to their gpio descriptors.
320 * Warning if one of the names is already used for a different GPIO.
322 static int gpiochip_set_desc_names(struct gpio_chip *gc)
324 struct gpio_device *gdev = gc->gpiodev;
330 /* First check all names if they are unique */
331 for (i = 0; i != gc->ngpio; ++i) {
332 struct gpio_desc *gpio;
334 gpio = gpio_name_to_desc(gc->names[i]);
337 "Detected name collision for GPIO name '%s'\n",
341 /* Then add all names to the GPIO descriptors */
342 for (i = 0; i != gc->ngpio; ++i)
343 gdev->descs[i].name = gc->names[i];
348 static unsigned long *gpiochip_allocate_mask(struct gpio_chip *chip)
352 p = kmalloc_array(BITS_TO_LONGS(chip->ngpio), sizeof(*p), GFP_KERNEL);
356 /* Assume by default all GPIOs are valid */
357 bitmap_fill(p, chip->ngpio);
362 static int gpiochip_init_valid_mask(struct gpio_chip *gpiochip)
364 #ifdef CONFIG_OF_GPIO
366 struct device_node *np = gpiochip->of_node;
368 size = of_property_count_u32_elems(np, "gpio-reserved-ranges");
369 if (size > 0 && size % 2 == 0)
370 gpiochip->need_valid_mask = true;
373 if (!gpiochip->need_valid_mask)
376 gpiochip->valid_mask = gpiochip_allocate_mask(gpiochip);
377 if (!gpiochip->valid_mask)
383 static void gpiochip_free_valid_mask(struct gpio_chip *gpiochip)
385 kfree(gpiochip->valid_mask);
386 gpiochip->valid_mask = NULL;
389 bool gpiochip_line_is_valid(const struct gpio_chip *gpiochip,
392 /* No mask means all valid */
393 if (likely(!gpiochip->valid_mask))
395 return test_bit(offset, gpiochip->valid_mask);
397 EXPORT_SYMBOL_GPL(gpiochip_line_is_valid);
400 * GPIO line handle management
404 * struct linehandle_state - contains the state of a userspace handle
405 * @gdev: the GPIO device the handle pertains to
406 * @label: consumer label used to tag descriptors
407 * @descs: the GPIO descriptors held by this handle
408 * @numdescs: the number of descriptors held in the descs array
410 struct linehandle_state {
411 struct gpio_device *gdev;
413 struct gpio_desc *descs[GPIOHANDLES_MAX];
417 #define GPIOHANDLE_REQUEST_VALID_FLAGS \
418 (GPIOHANDLE_REQUEST_INPUT | \
419 GPIOHANDLE_REQUEST_OUTPUT | \
420 GPIOHANDLE_REQUEST_ACTIVE_LOW | \
421 GPIOHANDLE_REQUEST_OPEN_DRAIN | \
422 GPIOHANDLE_REQUEST_OPEN_SOURCE)
424 static long linehandle_ioctl(struct file *filep, unsigned int cmd,
427 struct linehandle_state *lh = filep->private_data;
428 void __user *ip = (void __user *)arg;
429 struct gpiohandle_data ghd;
430 DECLARE_BITMAP(vals, GPIOHANDLES_MAX);
433 if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
434 /* NOTE: It's ok to read values of output lines. */
435 int ret = gpiod_get_array_value_complex(false,
444 memset(&ghd, 0, sizeof(ghd));
445 for (i = 0; i < lh->numdescs; i++)
446 ghd.values[i] = test_bit(i, vals);
448 if (copy_to_user(ip, &ghd, sizeof(ghd)))
452 } else if (cmd == GPIOHANDLE_SET_LINE_VALUES_IOCTL) {
454 * All line descriptors were created at once with the same
455 * flags so just check if the first one is really output.
457 if (!test_bit(FLAG_IS_OUT, &lh->descs[0]->flags))
460 if (copy_from_user(&ghd, ip, sizeof(ghd)))
463 /* Clamp all values to [0,1] */
464 for (i = 0; i < lh->numdescs; i++)
465 __assign_bit(i, vals, ghd.values[i]);
467 /* Reuse the array setting function */
468 return gpiod_set_array_value_complex(false,
479 static long linehandle_ioctl_compat(struct file *filep, unsigned int cmd,
482 return linehandle_ioctl(filep, cmd, (unsigned long)compat_ptr(arg));
486 static int linehandle_release(struct inode *inode, struct file *filep)
488 struct linehandle_state *lh = filep->private_data;
489 struct gpio_device *gdev = lh->gdev;
492 for (i = 0; i < lh->numdescs; i++)
493 gpiod_free(lh->descs[i]);
496 put_device(&gdev->dev);
500 static const struct file_operations linehandle_fileops = {
501 .release = linehandle_release,
502 .owner = THIS_MODULE,
503 .llseek = noop_llseek,
504 .unlocked_ioctl = linehandle_ioctl,
506 .compat_ioctl = linehandle_ioctl_compat,
510 static int linehandle_create(struct gpio_device *gdev, void __user *ip)
512 struct gpiohandle_request handlereq;
513 struct linehandle_state *lh;
515 int fd, i, count = 0, ret;
518 if (copy_from_user(&handlereq, ip, sizeof(handlereq)))
520 if ((handlereq.lines == 0) || (handlereq.lines > GPIOHANDLES_MAX))
523 lflags = handlereq.flags;
525 /* Return an error if an unknown flag is set */
526 if (lflags & ~GPIOHANDLE_REQUEST_VALID_FLAGS)
530 * Do not allow OPEN_SOURCE & OPEN_DRAIN flags in a single request. If
531 * the hardware actually supports enabling both at the same time the
532 * electrical result would be disastrous.
534 if ((lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN) &&
535 (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE))
538 /* OPEN_DRAIN and OPEN_SOURCE flags only make sense for output mode. */
539 if (!(lflags & GPIOHANDLE_REQUEST_OUTPUT) &&
540 ((lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN) ||
541 (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE)))
544 lh = kzalloc(sizeof(*lh), GFP_KERNEL);
548 get_device(&gdev->dev);
550 /* Make sure this is terminated */
551 handlereq.consumer_label[sizeof(handlereq.consumer_label)-1] = '\0';
552 if (strlen(handlereq.consumer_label)) {
553 lh->label = kstrdup(handlereq.consumer_label,
561 /* Request each GPIO */
562 for (i = 0; i < handlereq.lines; i++) {
563 u32 offset = handlereq.lineoffsets[i];
564 struct gpio_desc *desc;
566 if (offset >= gdev->ngpio) {
571 desc = &gdev->descs[offset];
572 ret = gpiod_request(desc, lh->label);
578 if (lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW)
579 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
580 if (lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN)
581 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
582 if (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE)
583 set_bit(FLAG_OPEN_SOURCE, &desc->flags);
585 ret = gpiod_set_transitory(desc, false);
590 * Lines have to be requested explicitly for input
591 * or output, else the line will be treated "as is".
593 if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
594 int val = !!handlereq.default_values[i];
596 ret = gpiod_direction_output(desc, val);
599 } else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
600 ret = gpiod_direction_input(desc);
604 dev_dbg(&gdev->dev, "registered chardev handle for line %d\n",
607 /* Let i point at the last handle */
609 lh->numdescs = handlereq.lines;
611 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
617 file = anon_inode_getfile("gpio-linehandle",
620 O_RDONLY | O_CLOEXEC);
623 goto out_put_unused_fd;
627 if (copy_to_user(ip, &handlereq, sizeof(handlereq))) {
629 * fput() will trigger the release() callback, so do not go onto
630 * the regular error cleanup path here.
637 fd_install(fd, file);
639 dev_dbg(&gdev->dev, "registered chardev handle for %d lines\n",
647 for (i = 0; i < count; i++)
648 gpiod_free(lh->descs[i]);
652 put_device(&gdev->dev);
657 * GPIO line event management
661 * struct lineevent_state - contains the state of a userspace event
662 * @gdev: the GPIO device the event pertains to
663 * @label: consumer label used to tag descriptors
664 * @desc: the GPIO descriptor held by this event
665 * @eflags: the event flags this line was requested with
666 * @irq: the interrupt that trigger in response to events on this GPIO
667 * @wait: wait queue that handles blocking reads of events
668 * @events: KFIFO for the GPIO events
669 * @read_lock: mutex lock to protect reads from colliding with adding
670 * new events to the FIFO
671 * @timestamp: cache for the timestamp storing it between hardirq
672 * and IRQ thread, used to bring the timestamp close to the actual
675 struct lineevent_state {
676 struct gpio_device *gdev;
678 struct gpio_desc *desc;
681 wait_queue_head_t wait;
682 DECLARE_KFIFO(events, struct gpioevent_data, 16);
683 struct mutex read_lock;
687 #define GPIOEVENT_REQUEST_VALID_FLAGS \
688 (GPIOEVENT_REQUEST_RISING_EDGE | \
689 GPIOEVENT_REQUEST_FALLING_EDGE)
691 static __poll_t lineevent_poll(struct file *filep,
692 struct poll_table_struct *wait)
694 struct lineevent_state *le = filep->private_data;
697 poll_wait(filep, &le->wait, wait);
699 if (!kfifo_is_empty(&le->events))
700 events = EPOLLIN | EPOLLRDNORM;
706 static ssize_t lineevent_read(struct file *filep,
711 struct lineevent_state *le = filep->private_data;
715 if (count < sizeof(struct gpioevent_data))
719 if (kfifo_is_empty(&le->events)) {
720 if (filep->f_flags & O_NONBLOCK)
723 ret = wait_event_interruptible(le->wait,
724 !kfifo_is_empty(&le->events));
729 if (mutex_lock_interruptible(&le->read_lock))
731 ret = kfifo_to_user(&le->events, buf, count, &copied);
732 mutex_unlock(&le->read_lock);
738 * If we couldn't read anything from the fifo (a different
739 * thread might have been faster) we either return -EAGAIN if
740 * the file descriptor is non-blocking, otherwise we go back to
741 * sleep and wait for more data to arrive.
743 if (copied == 0 && (filep->f_flags & O_NONBLOCK))
746 } while (copied == 0);
751 static int lineevent_release(struct inode *inode, struct file *filep)
753 struct lineevent_state *le = filep->private_data;
754 struct gpio_device *gdev = le->gdev;
756 free_irq(le->irq, le);
757 gpiod_free(le->desc);
760 put_device(&gdev->dev);
764 static long lineevent_ioctl(struct file *filep, unsigned int cmd,
767 struct lineevent_state *le = filep->private_data;
768 void __user *ip = (void __user *)arg;
769 struct gpiohandle_data ghd;
772 * We can get the value for an event line but not set it,
773 * because it is input by definition.
775 if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
778 memset(&ghd, 0, sizeof(ghd));
780 val = gpiod_get_value_cansleep(le->desc);
785 if (copy_to_user(ip, &ghd, sizeof(ghd)))
794 static long lineevent_ioctl_compat(struct file *filep, unsigned int cmd,
797 return lineevent_ioctl(filep, cmd, (unsigned long)compat_ptr(arg));
801 static const struct file_operations lineevent_fileops = {
802 .release = lineevent_release,
803 .read = lineevent_read,
804 .poll = lineevent_poll,
805 .owner = THIS_MODULE,
806 .llseek = noop_llseek,
807 .unlocked_ioctl = lineevent_ioctl,
809 .compat_ioctl = lineevent_ioctl_compat,
813 static irqreturn_t lineevent_irq_thread(int irq, void *p)
815 struct lineevent_state *le = p;
816 struct gpioevent_data ge;
819 /* Do not leak kernel stack to userspace */
820 memset(&ge, 0, sizeof(ge));
822 ge.timestamp = le->timestamp;
824 if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE
825 && le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
826 int level = gpiod_get_value_cansleep(le->desc);
828 /* Emit low-to-high event */
829 ge.id = GPIOEVENT_EVENT_RISING_EDGE;
831 /* Emit high-to-low event */
832 ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
833 } else if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE) {
834 /* Emit low-to-high event */
835 ge.id = GPIOEVENT_EVENT_RISING_EDGE;
836 } else if (le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
837 /* Emit high-to-low event */
838 ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
843 ret = kfifo_put(&le->events, ge);
845 wake_up_poll(&le->wait, EPOLLIN);
850 static irqreturn_t lineevent_irq_handler(int irq, void *p)
852 struct lineevent_state *le = p;
855 * Just store the timestamp in hardirq context so we get it as
856 * close in time as possible to the actual event.
858 le->timestamp = ktime_get_real_ns();
860 return IRQ_WAKE_THREAD;
863 static int lineevent_create(struct gpio_device *gdev, void __user *ip)
865 struct gpioevent_request eventreq;
866 struct lineevent_state *le;
867 struct gpio_desc *desc;
876 if (copy_from_user(&eventreq, ip, sizeof(eventreq)))
879 le = kzalloc(sizeof(*le), GFP_KERNEL);
883 get_device(&gdev->dev);
885 /* Make sure this is terminated */
886 eventreq.consumer_label[sizeof(eventreq.consumer_label)-1] = '\0';
887 if (strlen(eventreq.consumer_label)) {
888 le->label = kstrdup(eventreq.consumer_label,
896 offset = eventreq.lineoffset;
897 lflags = eventreq.handleflags;
898 eflags = eventreq.eventflags;
900 if (offset >= gdev->ngpio) {
905 /* Return an error if a unknown flag is set */
906 if ((lflags & ~GPIOHANDLE_REQUEST_VALID_FLAGS) ||
907 (eflags & ~GPIOEVENT_REQUEST_VALID_FLAGS)) {
912 /* This is just wrong: we don't look for events on output lines */
913 if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
918 desc = &gdev->descs[offset];
919 ret = gpiod_request(desc, le->label);
925 if (lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW)
926 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
927 if (lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN)
928 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
929 if (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE)
930 set_bit(FLAG_OPEN_SOURCE, &desc->flags);
932 ret = gpiod_direction_input(desc);
936 le->irq = gpiod_to_irq(desc);
942 if (eflags & GPIOEVENT_REQUEST_RISING_EDGE)
943 irqflags |= IRQF_TRIGGER_RISING;
944 if (eflags & GPIOEVENT_REQUEST_FALLING_EDGE)
945 irqflags |= IRQF_TRIGGER_FALLING;
946 irqflags |= IRQF_ONESHOT;
948 INIT_KFIFO(le->events);
949 init_waitqueue_head(&le->wait);
950 mutex_init(&le->read_lock);
952 /* Request a thread to read the events */
953 ret = request_threaded_irq(le->irq,
954 lineevent_irq_handler,
955 lineevent_irq_thread,
962 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
968 file = anon_inode_getfile("gpio-event",
971 O_RDONLY | O_CLOEXEC);
974 goto out_put_unused_fd;
978 if (copy_to_user(ip, &eventreq, sizeof(eventreq))) {
980 * fput() will trigger the release() callback, so do not go onto
981 * the regular error cleanup path here.
988 fd_install(fd, file);
995 free_irq(le->irq, le);
997 gpiod_free(le->desc);
1002 put_device(&gdev->dev);
1007 * gpio_ioctl() - ioctl handler for the GPIO chardev
1009 static long gpio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1011 struct gpio_device *gdev = filp->private_data;
1012 struct gpio_chip *chip = gdev->chip;
1013 void __user *ip = (void __user *)arg;
1015 /* We fail any subsequent ioctl():s when the chip is gone */
1019 /* Fill in the struct and pass to userspace */
1020 if (cmd == GPIO_GET_CHIPINFO_IOCTL) {
1021 struct gpiochip_info chipinfo;
1023 memset(&chipinfo, 0, sizeof(chipinfo));
1025 strncpy(chipinfo.name, dev_name(&gdev->dev),
1026 sizeof(chipinfo.name));
1027 chipinfo.name[sizeof(chipinfo.name)-1] = '\0';
1028 strncpy(chipinfo.label, gdev->label,
1029 sizeof(chipinfo.label));
1030 chipinfo.label[sizeof(chipinfo.label)-1] = '\0';
1031 chipinfo.lines = gdev->ngpio;
1032 if (copy_to_user(ip, &chipinfo, sizeof(chipinfo)))
1035 } else if (cmd == GPIO_GET_LINEINFO_IOCTL) {
1036 struct gpioline_info lineinfo;
1037 struct gpio_desc *desc;
1039 if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
1041 if (lineinfo.line_offset >= gdev->ngpio)
1044 desc = &gdev->descs[lineinfo.line_offset];
1046 strncpy(lineinfo.name, desc->name,
1047 sizeof(lineinfo.name));
1048 lineinfo.name[sizeof(lineinfo.name)-1] = '\0';
1050 lineinfo.name[0] = '\0';
1053 strncpy(lineinfo.consumer, desc->label,
1054 sizeof(lineinfo.consumer));
1055 lineinfo.consumer[sizeof(lineinfo.consumer)-1] = '\0';
1057 lineinfo.consumer[0] = '\0';
1061 * Userspace only need to know that the kernel is using
1062 * this GPIO so it can't use it.
1065 if (test_bit(FLAG_REQUESTED, &desc->flags) ||
1066 test_bit(FLAG_IS_HOGGED, &desc->flags) ||
1067 test_bit(FLAG_USED_AS_IRQ, &desc->flags) ||
1068 test_bit(FLAG_EXPORT, &desc->flags) ||
1069 test_bit(FLAG_SYSFS, &desc->flags))
1070 lineinfo.flags |= GPIOLINE_FLAG_KERNEL;
1071 if (test_bit(FLAG_IS_OUT, &desc->flags))
1072 lineinfo.flags |= GPIOLINE_FLAG_IS_OUT;
1073 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
1074 lineinfo.flags |= GPIOLINE_FLAG_ACTIVE_LOW;
1075 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
1076 lineinfo.flags |= GPIOLINE_FLAG_OPEN_DRAIN;
1077 if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
1078 lineinfo.flags |= GPIOLINE_FLAG_OPEN_SOURCE;
1080 if (copy_to_user(ip, &lineinfo, sizeof(lineinfo)))
1083 } else if (cmd == GPIO_GET_LINEHANDLE_IOCTL) {
1084 return linehandle_create(gdev, ip);
1085 } else if (cmd == GPIO_GET_LINEEVENT_IOCTL) {
1086 return lineevent_create(gdev, ip);
1091 #ifdef CONFIG_COMPAT
1092 static long gpio_ioctl_compat(struct file *filp, unsigned int cmd,
1095 return gpio_ioctl(filp, cmd, (unsigned long)compat_ptr(arg));
1100 * gpio_chrdev_open() - open the chardev for ioctl operations
1101 * @inode: inode for this chardev
1102 * @filp: file struct for storing private data
1103 * Returns 0 on success
1105 static int gpio_chrdev_open(struct inode *inode, struct file *filp)
1107 struct gpio_device *gdev = container_of(inode->i_cdev,
1108 struct gpio_device, chrdev);
1110 /* Fail on open if the backing gpiochip is gone */
1113 get_device(&gdev->dev);
1114 filp->private_data = gdev;
1116 return nonseekable_open(inode, filp);
1120 * gpio_chrdev_release() - close chardev after ioctl operations
1121 * @inode: inode for this chardev
1122 * @filp: file struct for storing private data
1123 * Returns 0 on success
1125 static int gpio_chrdev_release(struct inode *inode, struct file *filp)
1127 struct gpio_device *gdev = container_of(inode->i_cdev,
1128 struct gpio_device, chrdev);
1130 put_device(&gdev->dev);
1135 static const struct file_operations gpio_fileops = {
1136 .release = gpio_chrdev_release,
1137 .open = gpio_chrdev_open,
1138 .owner = THIS_MODULE,
1139 .llseek = no_llseek,
1140 .unlocked_ioctl = gpio_ioctl,
1141 #ifdef CONFIG_COMPAT
1142 .compat_ioctl = gpio_ioctl_compat,
1146 static void gpiodevice_release(struct device *dev)
1148 struct gpio_device *gdev = dev_get_drvdata(dev);
1150 list_del(&gdev->list);
1151 ida_simple_remove(&gpio_ida, gdev->id);
1152 kfree_const(gdev->label);
1157 static int gpiochip_setup_dev(struct gpio_device *gdev)
1161 cdev_init(&gdev->chrdev, &gpio_fileops);
1162 gdev->chrdev.owner = THIS_MODULE;
1163 gdev->dev.devt = MKDEV(MAJOR(gpio_devt), gdev->id);
1165 status = cdev_device_add(&gdev->chrdev, &gdev->dev);
1169 chip_dbg(gdev->chip, "added GPIO chardev (%d:%d)\n",
1170 MAJOR(gpio_devt), gdev->id);
1172 status = gpiochip_sysfs_register(gdev);
1174 goto err_remove_device;
1176 /* From this point, the .release() function cleans up gpio_device */
1177 gdev->dev.release = gpiodevice_release;
1178 pr_debug("%s: registered GPIOs %d to %d on device: %s (%s)\n",
1179 __func__, gdev->base, gdev->base + gdev->ngpio - 1,
1180 dev_name(&gdev->dev), gdev->chip->label ? : "generic");
1185 cdev_device_del(&gdev->chrdev, &gdev->dev);
1189 static void gpiochip_machine_hog(struct gpio_chip *chip, struct gpiod_hog *hog)
1191 struct gpio_desc *desc;
1194 desc = gpiochip_get_desc(chip, hog->chip_hwnum);
1196 pr_err("%s: unable to get GPIO desc: %ld\n",
1197 __func__, PTR_ERR(desc));
1201 if (test_bit(FLAG_IS_HOGGED, &desc->flags))
1204 rv = gpiod_hog(desc, hog->line_name, hog->lflags, hog->dflags);
1206 pr_err("%s: unable to hog GPIO line (%s:%u): %d\n",
1207 __func__, chip->label, hog->chip_hwnum, rv);
1210 static void machine_gpiochip_add(struct gpio_chip *chip)
1212 struct gpiod_hog *hog;
1214 mutex_lock(&gpio_machine_hogs_mutex);
1216 list_for_each_entry(hog, &gpio_machine_hogs, list) {
1217 if (!strcmp(chip->label, hog->chip_label))
1218 gpiochip_machine_hog(chip, hog);
1221 mutex_unlock(&gpio_machine_hogs_mutex);
1224 static void gpiochip_setup_devs(void)
1226 struct gpio_device *gdev;
1229 list_for_each_entry(gdev, &gpio_devices, list) {
1230 err = gpiochip_setup_dev(gdev);
1232 pr_err("%s: Failed to initialize gpio device (%d)\n",
1233 dev_name(&gdev->dev), err);
1237 int gpiochip_add_data_with_key(struct gpio_chip *chip, void *data,
1238 struct lock_class_key *lock_key,
1239 struct lock_class_key *request_key)
1241 unsigned long flags;
1244 int base = chip->base;
1245 struct gpio_device *gdev;
1248 * First: allocate and populate the internal stat container, and
1249 * set up the struct device.
1251 gdev = kzalloc(sizeof(*gdev), GFP_KERNEL);
1254 gdev->dev.bus = &gpio_bus_type;
1256 chip->gpiodev = gdev;
1258 gdev->dev.parent = chip->parent;
1259 gdev->dev.of_node = chip->parent->of_node;
1262 #ifdef CONFIG_OF_GPIO
1263 /* If the gpiochip has an assigned OF node this takes precedence */
1265 gdev->dev.of_node = chip->of_node;
1267 chip->of_node = gdev->dev.of_node;
1270 gdev->id = ida_simple_get(&gpio_ida, 0, 0, GFP_KERNEL);
1275 dev_set_name(&gdev->dev, "gpiochip%d", gdev->id);
1276 device_initialize(&gdev->dev);
1277 dev_set_drvdata(&gdev->dev, gdev);
1278 if (chip->parent && chip->parent->driver)
1279 gdev->owner = chip->parent->driver->owner;
1280 else if (chip->owner)
1281 /* TODO: remove chip->owner */
1282 gdev->owner = chip->owner;
1284 gdev->owner = THIS_MODULE;
1286 gdev->descs = kcalloc(chip->ngpio, sizeof(gdev->descs[0]), GFP_KERNEL);
1292 if (chip->ngpio == 0) {
1293 chip_err(chip, "tried to insert a GPIO chip with zero lines\n");
1295 goto err_free_descs;
1298 if (chip->ngpio > FASTPATH_NGPIO)
1299 chip_warn(chip, "line cnt %u is greater than fast path cnt %u\n",
1300 chip->ngpio, FASTPATH_NGPIO);
1302 gdev->label = kstrdup_const(chip->label ?: "unknown", GFP_KERNEL);
1305 goto err_free_descs;
1308 gdev->ngpio = chip->ngpio;
1311 spin_lock_irqsave(&gpio_lock, flags);
1314 * TODO: this allocates a Linux GPIO number base in the global
1315 * GPIO numberspace for this chip. In the long run we want to
1316 * get *rid* of this numberspace and use only descriptors, but
1317 * it may be a pipe dream. It will not happen before we get rid
1318 * of the sysfs interface anyways.
1321 base = gpiochip_find_base(chip->ngpio);
1324 spin_unlock_irqrestore(&gpio_lock, flags);
1325 goto err_free_label;
1328 * TODO: it should not be necessary to reflect the assigned
1329 * base outside of the GPIO subsystem. Go over drivers and
1330 * see if anyone makes use of this, else drop this and assign
1337 status = gpiodev_add_to_list(gdev);
1339 spin_unlock_irqrestore(&gpio_lock, flags);
1340 goto err_free_label;
1343 spin_unlock_irqrestore(&gpio_lock, flags);
1345 for (i = 0; i < chip->ngpio; i++) {
1346 struct gpio_desc *desc = &gdev->descs[i];
1350 /* REVISIT: most hardware initializes GPIOs as inputs (often
1351 * with pullups enabled) so power usage is minimized. Linux
1352 * code should set the gpio direction first thing; but until
1353 * it does, and in case chip->get_direction is not set, we may
1354 * expose the wrong direction in sysfs.
1356 desc->flags = !chip->direction_input ? (1 << FLAG_IS_OUT) : 0;
1359 #ifdef CONFIG_PINCTRL
1360 INIT_LIST_HEAD(&gdev->pin_ranges);
1363 status = gpiochip_set_desc_names(chip);
1365 goto err_remove_from_list;
1367 status = gpiochip_irqchip_init_valid_mask(chip);
1369 goto err_remove_from_list;
1371 status = gpiochip_init_valid_mask(chip);
1373 goto err_remove_irqchip_mask;
1375 status = gpiochip_add_irqchip(chip, lock_key, request_key);
1377 goto err_remove_chip;
1379 status = of_gpiochip_add(chip);
1381 goto err_remove_chip;
1383 acpi_gpiochip_add(chip);
1385 machine_gpiochip_add(chip);
1388 * By first adding the chardev, and then adding the device,
1389 * we get a device node entry in sysfs under
1390 * /sys/bus/gpio/devices/gpiochipN/dev that can be used for
1391 * coldplug of device nodes and other udev business.
1392 * We can do this only if gpiolib has been initialized.
1393 * Otherwise, defer until later.
1395 if (gpiolib_initialized) {
1396 status = gpiochip_setup_dev(gdev);
1398 goto err_remove_chip;
1403 acpi_gpiochip_remove(chip);
1404 gpiochip_free_hogs(chip);
1405 of_gpiochip_remove(chip);
1406 gpiochip_free_valid_mask(chip);
1407 err_remove_irqchip_mask:
1408 gpiochip_irqchip_free_valid_mask(chip);
1409 err_remove_from_list:
1410 spin_lock_irqsave(&gpio_lock, flags);
1411 list_del(&gdev->list);
1412 spin_unlock_irqrestore(&gpio_lock, flags);
1414 kfree_const(gdev->label);
1418 ida_simple_remove(&gpio_ida, gdev->id);
1419 /* failures here can mean systems won't boot... */
1420 pr_err("%s: GPIOs %d..%d (%s) failed to register, %d\n", __func__,
1421 gdev->base, gdev->base + gdev->ngpio - 1,
1422 chip->label ? : "generic", status);
1426 EXPORT_SYMBOL_GPL(gpiochip_add_data_with_key);
1429 * gpiochip_get_data() - get per-subdriver data for the chip
1433 * The per-subdriver data for the chip.
1435 void *gpiochip_get_data(struct gpio_chip *chip)
1437 return chip->gpiodev->data;
1439 EXPORT_SYMBOL_GPL(gpiochip_get_data);
1442 * gpiochip_remove() - unregister a gpio_chip
1443 * @chip: the chip to unregister
1445 * A gpio_chip with any GPIOs still requested may not be removed.
1447 void gpiochip_remove(struct gpio_chip *chip)
1449 struct gpio_device *gdev = chip->gpiodev;
1450 struct gpio_desc *desc;
1451 unsigned long flags;
1453 bool requested = false;
1455 /* FIXME: should the legacy sysfs handling be moved to gpio_device? */
1456 gpiochip_sysfs_unregister(gdev);
1457 gpiochip_free_hogs(chip);
1458 /* Numb the device, cancelling all outstanding operations */
1460 gpiochip_irqchip_remove(chip);
1461 acpi_gpiochip_remove(chip);
1462 gpiochip_remove_pin_ranges(chip);
1463 of_gpiochip_remove(chip);
1464 gpiochip_free_valid_mask(chip);
1466 * We accept no more calls into the driver from this point, so
1467 * NULL the driver data pointer
1471 spin_lock_irqsave(&gpio_lock, flags);
1472 for (i = 0; i < gdev->ngpio; i++) {
1473 desc = &gdev->descs[i];
1474 if (test_bit(FLAG_REQUESTED, &desc->flags))
1477 spin_unlock_irqrestore(&gpio_lock, flags);
1480 dev_crit(&gdev->dev,
1481 "REMOVING GPIOCHIP WITH GPIOS STILL REQUESTED\n");
1484 * The gpiochip side puts its use of the device to rest here:
1485 * if there are no userspace clients, the chardev and device will
1486 * be removed, else it will be dangling until the last user is
1489 cdev_device_del(&gdev->chrdev, &gdev->dev);
1490 put_device(&gdev->dev);
1492 EXPORT_SYMBOL_GPL(gpiochip_remove);
1494 static void devm_gpio_chip_release(struct device *dev, void *res)
1496 struct gpio_chip *chip = *(struct gpio_chip **)res;
1498 gpiochip_remove(chip);
1501 static int devm_gpio_chip_match(struct device *dev, void *res, void *data)
1504 struct gpio_chip **r = res;
1515 * devm_gpiochip_add_data() - Resource manager gpiochip_add_data()
1516 * @dev: the device pointer on which irq_chip belongs to.
1517 * @chip: the chip to register, with chip->base initialized
1518 * @data: driver-private data associated with this chip
1520 * Context: potentially before irqs will work
1522 * The gpio chip automatically be released when the device is unbound.
1525 * A negative errno if the chip can't be registered, such as because the
1526 * chip->base is invalid or already associated with a different chip.
1527 * Otherwise it returns zero as a success code.
1529 int devm_gpiochip_add_data(struct device *dev, struct gpio_chip *chip,
1532 struct gpio_chip **ptr;
1535 ptr = devres_alloc(devm_gpio_chip_release, sizeof(*ptr),
1540 ret = gpiochip_add_data(chip, data);
1547 devres_add(dev, ptr);
1551 EXPORT_SYMBOL_GPL(devm_gpiochip_add_data);
1554 * devm_gpiochip_remove() - Resource manager of gpiochip_remove()
1555 * @dev: device for which which resource was allocated
1556 * @chip: the chip to remove
1558 * A gpio_chip with any GPIOs still requested may not be removed.
1560 void devm_gpiochip_remove(struct device *dev, struct gpio_chip *chip)
1564 ret = devres_release(dev, devm_gpio_chip_release,
1565 devm_gpio_chip_match, chip);
1568 EXPORT_SYMBOL_GPL(devm_gpiochip_remove);
1571 * gpiochip_find() - iterator for locating a specific gpio_chip
1572 * @data: data to pass to match function
1573 * @match: Callback function to check gpio_chip
1575 * Similar to bus_find_device. It returns a reference to a gpio_chip as
1576 * determined by a user supplied @match callback. The callback should return
1577 * 0 if the device doesn't match and non-zero if it does. If the callback is
1578 * non-zero, this function will return to the caller and not iterate over any
1581 struct gpio_chip *gpiochip_find(void *data,
1582 int (*match)(struct gpio_chip *chip,
1585 struct gpio_device *gdev;
1586 struct gpio_chip *chip = NULL;
1587 unsigned long flags;
1589 spin_lock_irqsave(&gpio_lock, flags);
1590 list_for_each_entry(gdev, &gpio_devices, list)
1591 if (gdev->chip && match(gdev->chip, data)) {
1596 spin_unlock_irqrestore(&gpio_lock, flags);
1600 EXPORT_SYMBOL_GPL(gpiochip_find);
1602 static int gpiochip_match_name(struct gpio_chip *chip, void *data)
1604 const char *name = data;
1606 return !strcmp(chip->label, name);
1609 static struct gpio_chip *find_chip_by_name(const char *name)
1611 return gpiochip_find((void *)name, gpiochip_match_name);
1614 #ifdef CONFIG_GPIOLIB_IRQCHIP
1617 * The following is irqchip helper code for gpiochips.
1620 static int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gpiochip)
1622 if (!gpiochip->irq.need_valid_mask)
1625 gpiochip->irq.valid_mask = gpiochip_allocate_mask(gpiochip);
1626 if (!gpiochip->irq.valid_mask)
1632 static void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gpiochip)
1634 kfree(gpiochip->irq.valid_mask);
1635 gpiochip->irq.valid_mask = NULL;
1638 bool gpiochip_irqchip_irq_valid(const struct gpio_chip *gpiochip,
1639 unsigned int offset)
1641 if (!gpiochip_line_is_valid(gpiochip, offset))
1643 /* No mask means all valid */
1644 if (likely(!gpiochip->irq.valid_mask))
1646 return test_bit(offset, gpiochip->irq.valid_mask);
1648 EXPORT_SYMBOL_GPL(gpiochip_irqchip_irq_valid);
1651 * gpiochip_set_cascaded_irqchip() - connects a cascaded irqchip to a gpiochip
1652 * @gpiochip: the gpiochip to set the irqchip chain to
1653 * @irqchip: the irqchip to chain to the gpiochip
1654 * @parent_irq: the irq number corresponding to the parent IRQ for this
1656 * @parent_handler: the parent interrupt handler for the accumulated IRQ
1657 * coming out of the gpiochip. If the interrupt is nested rather than
1658 * cascaded, pass NULL in this handler argument
1660 static void gpiochip_set_cascaded_irqchip(struct gpio_chip *gpiochip,
1661 struct irq_chip *irqchip,
1662 unsigned int parent_irq,
1663 irq_flow_handler_t parent_handler)
1665 unsigned int offset;
1667 if (!gpiochip->irq.domain) {
1668 chip_err(gpiochip, "called %s before setting up irqchip\n",
1673 if (parent_handler) {
1674 if (gpiochip->can_sleep) {
1676 "you cannot have chained interrupts on a chip that may sleep\n");
1680 * The parent irqchip is already using the chip_data for this
1681 * irqchip, so our callbacks simply use the handler_data.
1683 irq_set_chained_handler_and_data(parent_irq, parent_handler,
1686 gpiochip->irq.parents = &parent_irq;
1687 gpiochip->irq.num_parents = 1;
1690 /* Set the parent IRQ for all affected IRQs */
1691 for (offset = 0; offset < gpiochip->ngpio; offset++) {
1692 if (!gpiochip_irqchip_irq_valid(gpiochip, offset))
1694 irq_set_parent(irq_find_mapping(gpiochip->irq.domain, offset),
1700 * gpiochip_set_chained_irqchip() - connects a chained irqchip to a gpiochip
1701 * @gpiochip: the gpiochip to set the irqchip chain to
1702 * @irqchip: the irqchip to chain to the gpiochip
1703 * @parent_irq: the irq number corresponding to the parent IRQ for this
1705 * @parent_handler: the parent interrupt handler for the accumulated IRQ
1706 * coming out of the gpiochip. If the interrupt is nested rather than
1707 * cascaded, pass NULL in this handler argument
1709 void gpiochip_set_chained_irqchip(struct gpio_chip *gpiochip,
1710 struct irq_chip *irqchip,
1711 unsigned int parent_irq,
1712 irq_flow_handler_t parent_handler)
1714 if (gpiochip->irq.threaded) {
1715 chip_err(gpiochip, "tried to chain a threaded gpiochip\n");
1719 gpiochip_set_cascaded_irqchip(gpiochip, irqchip, parent_irq,
1722 EXPORT_SYMBOL_GPL(gpiochip_set_chained_irqchip);
1725 * gpiochip_set_nested_irqchip() - connects a nested irqchip to a gpiochip
1726 * @gpiochip: the gpiochip to set the irqchip nested handler to
1727 * @irqchip: the irqchip to nest to the gpiochip
1728 * @parent_irq: the irq number corresponding to the parent IRQ for this
1731 void gpiochip_set_nested_irqchip(struct gpio_chip *gpiochip,
1732 struct irq_chip *irqchip,
1733 unsigned int parent_irq)
1735 gpiochip_set_cascaded_irqchip(gpiochip, irqchip, parent_irq,
1738 EXPORT_SYMBOL_GPL(gpiochip_set_nested_irqchip);
1741 * gpiochip_irq_map() - maps an IRQ into a GPIO irqchip
1742 * @d: the irqdomain used by this irqchip
1743 * @irq: the global irq number used by this GPIO irqchip irq
1744 * @hwirq: the local IRQ/GPIO line offset on this gpiochip
1746 * This function will set up the mapping for a certain IRQ line on a
1747 * gpiochip by assigning the gpiochip as chip data, and using the irqchip
1748 * stored inside the gpiochip.
1750 int gpiochip_irq_map(struct irq_domain *d, unsigned int irq,
1751 irq_hw_number_t hwirq)
1753 struct gpio_chip *chip = d->host_data;
1756 if (!gpiochip_irqchip_irq_valid(chip, hwirq))
1759 irq_set_chip_data(irq, chip);
1761 * This lock class tells lockdep that GPIO irqs are in a different
1762 * category than their parents, so it won't report false recursion.
1764 irq_set_lockdep_class(irq, chip->irq.lock_key, chip->irq.request_key);
1765 irq_set_chip_and_handler(irq, chip->irq.chip, chip->irq.handler);
1766 /* Chips that use nested thread handlers have them marked */
1767 if (chip->irq.threaded)
1768 irq_set_nested_thread(irq, 1);
1769 irq_set_noprobe(irq);
1771 if (chip->irq.num_parents == 1)
1772 err = irq_set_parent(irq, chip->irq.parents[0]);
1773 else if (chip->irq.map)
1774 err = irq_set_parent(irq, chip->irq.map[hwirq]);
1780 * No set-up of the hardware will happen if IRQ_TYPE_NONE
1781 * is passed as default type.
1783 if (chip->irq.default_type != IRQ_TYPE_NONE)
1784 irq_set_irq_type(irq, chip->irq.default_type);
1788 EXPORT_SYMBOL_GPL(gpiochip_irq_map);
1790 void gpiochip_irq_unmap(struct irq_domain *d, unsigned int irq)
1792 struct gpio_chip *chip = d->host_data;
1794 if (chip->irq.threaded)
1795 irq_set_nested_thread(irq, 0);
1796 irq_set_chip_and_handler(irq, NULL, NULL);
1797 irq_set_chip_data(irq, NULL);
1799 EXPORT_SYMBOL_GPL(gpiochip_irq_unmap);
1801 static const struct irq_domain_ops gpiochip_domain_ops = {
1802 .map = gpiochip_irq_map,
1803 .unmap = gpiochip_irq_unmap,
1804 /* Virtually all GPIO irqchips are twocell:ed */
1805 .xlate = irq_domain_xlate_twocell,
1808 static int gpiochip_to_irq(struct gpio_chip *chip, unsigned offset)
1810 if (!gpiochip_irqchip_irq_valid(chip, offset))
1813 return irq_create_mapping(chip->irq.domain, offset);
1816 static int gpiochip_irq_reqres(struct irq_data *d)
1818 struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
1820 return gpiochip_reqres_irq(chip, d->hwirq);
1823 static void gpiochip_irq_relres(struct irq_data *d)
1825 struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
1827 gpiochip_relres_irq(chip, d->hwirq);
1830 static void gpiochip_irq_enable(struct irq_data *d)
1832 struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
1834 gpiochip_enable_irq(chip, d->hwirq);
1835 if (chip->irq.irq_enable)
1836 chip->irq.irq_enable(d);
1838 chip->irq.chip->irq_unmask(d);
1841 static void gpiochip_irq_disable(struct irq_data *d)
1843 struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
1845 if (chip->irq.irq_disable)
1846 chip->irq.irq_disable(d);
1848 chip->irq.chip->irq_mask(d);
1849 gpiochip_disable_irq(chip, d->hwirq);
1852 static void gpiochip_set_irq_hooks(struct gpio_chip *gpiochip)
1854 struct irq_chip *irqchip = gpiochip->irq.chip;
1856 if (!irqchip->irq_request_resources &&
1857 !irqchip->irq_release_resources) {
1858 irqchip->irq_request_resources = gpiochip_irq_reqres;
1859 irqchip->irq_release_resources = gpiochip_irq_relres;
1861 if (WARN_ON(gpiochip->irq.irq_enable))
1863 /* Check if the irqchip already has this hook... */
1864 if (irqchip->irq_enable == gpiochip_irq_enable) {
1866 * ...and if so, give a gentle warning that this is bad
1870 "detected irqchip that is shared with multiple gpiochips: please fix the driver.\n");
1873 gpiochip->irq.irq_enable = irqchip->irq_enable;
1874 gpiochip->irq.irq_disable = irqchip->irq_disable;
1875 irqchip->irq_enable = gpiochip_irq_enable;
1876 irqchip->irq_disable = gpiochip_irq_disable;
1880 * gpiochip_add_irqchip() - adds an IRQ chip to a GPIO chip
1881 * @gpiochip: the GPIO chip to add the IRQ chip to
1882 * @lock_key: lockdep class for IRQ lock
1883 * @request_key: lockdep class for IRQ request
1885 static int gpiochip_add_irqchip(struct gpio_chip *gpiochip,
1886 struct lock_class_key *lock_key,
1887 struct lock_class_key *request_key)
1889 struct irq_chip *irqchip = gpiochip->irq.chip;
1890 const struct irq_domain_ops *ops;
1891 struct device_node *np;
1898 if (gpiochip->irq.parent_handler && gpiochip->can_sleep) {
1899 chip_err(gpiochip, "you cannot have chained interrupts on a chip that may sleep\n");
1903 np = gpiochip->gpiodev->dev.of_node;
1904 type = gpiochip->irq.default_type;
1907 * Specifying a default trigger is a terrible idea if DT or ACPI is
1908 * used to configure the interrupts, as you may end up with
1909 * conflicting triggers. Tell the user, and reset to NONE.
1911 if (WARN(np && type != IRQ_TYPE_NONE,
1912 "%s: Ignoring %u default trigger\n", np->full_name, type))
1913 type = IRQ_TYPE_NONE;
1915 if (has_acpi_companion(gpiochip->parent) && type != IRQ_TYPE_NONE) {
1916 acpi_handle_warn(ACPI_HANDLE(gpiochip->parent),
1917 "Ignoring %u default trigger\n", type);
1918 type = IRQ_TYPE_NONE;
1921 gpiochip->to_irq = gpiochip_to_irq;
1922 gpiochip->irq.default_type = type;
1923 gpiochip->irq.lock_key = lock_key;
1924 gpiochip->irq.request_key = request_key;
1926 if (gpiochip->irq.domain_ops)
1927 ops = gpiochip->irq.domain_ops;
1929 ops = &gpiochip_domain_ops;
1931 gpiochip->irq.domain = irq_domain_add_simple(np, gpiochip->ngpio,
1932 gpiochip->irq.first,
1934 if (!gpiochip->irq.domain)
1937 if (gpiochip->irq.parent_handler) {
1938 void *data = gpiochip->irq.parent_handler_data ?: gpiochip;
1940 for (i = 0; i < gpiochip->irq.num_parents; i++) {
1942 * The parent IRQ chip is already using the chip_data
1943 * for this IRQ chip, so our callbacks simply use the
1946 irq_set_chained_handler_and_data(gpiochip->irq.parents[i],
1947 gpiochip->irq.parent_handler,
1952 gpiochip_set_irq_hooks(gpiochip);
1954 acpi_gpiochip_request_interrupts(gpiochip);
1960 * gpiochip_irqchip_remove() - removes an irqchip added to a gpiochip
1961 * @gpiochip: the gpiochip to remove the irqchip from
1963 * This is called only from gpiochip_remove()
1965 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip)
1967 struct irq_chip *irqchip = gpiochip->irq.chip;
1968 unsigned int offset;
1970 acpi_gpiochip_free_interrupts(gpiochip);
1972 if (irqchip && gpiochip->irq.parent_handler) {
1973 struct gpio_irq_chip *irq = &gpiochip->irq;
1976 for (i = 0; i < irq->num_parents; i++)
1977 irq_set_chained_handler_and_data(irq->parents[i],
1981 /* Remove all IRQ mappings and delete the domain */
1982 if (gpiochip->irq.domain) {
1985 for (offset = 0; offset < gpiochip->ngpio; offset++) {
1986 if (!gpiochip_irqchip_irq_valid(gpiochip, offset))
1989 irq = irq_find_mapping(gpiochip->irq.domain, offset);
1990 irq_dispose_mapping(irq);
1993 irq_domain_remove(gpiochip->irq.domain);
1997 if (irqchip->irq_request_resources == gpiochip_irq_reqres) {
1998 irqchip->irq_request_resources = NULL;
1999 irqchip->irq_release_resources = NULL;
2001 if (irqchip->irq_enable == gpiochip_irq_enable) {
2002 irqchip->irq_enable = gpiochip->irq.irq_enable;
2003 irqchip->irq_disable = gpiochip->irq.irq_disable;
2006 gpiochip->irq.irq_enable = NULL;
2007 gpiochip->irq.irq_disable = NULL;
2008 gpiochip->irq.chip = NULL;
2010 gpiochip_irqchip_free_valid_mask(gpiochip);
2014 * gpiochip_irqchip_add_key() - adds an irqchip to a gpiochip
2015 * @gpiochip: the gpiochip to add the irqchip to
2016 * @irqchip: the irqchip to add to the gpiochip
2017 * @first_irq: if not dynamically assigned, the base (first) IRQ to
2018 * allocate gpiochip irqs from
2019 * @handler: the irq handler to use (often a predefined irq core function)
2020 * @type: the default type for IRQs on this irqchip, pass IRQ_TYPE_NONE
2021 * to have the core avoid setting up any default type in the hardware.
2022 * @threaded: whether this irqchip uses a nested thread handler
2023 * @lock_key: lockdep class for IRQ lock
2024 * @request_key: lockdep class for IRQ request
2026 * This function closely associates a certain irqchip with a certain
2027 * gpiochip, providing an irq domain to translate the local IRQs to
2028 * global irqs in the gpiolib core, and making sure that the gpiochip
2029 * is passed as chip data to all related functions. Driver callbacks
2030 * need to use gpiochip_get_data() to get their local state containers back
2031 * from the gpiochip passed as chip data. An irqdomain will be stored
2032 * in the gpiochip that shall be used by the driver to handle IRQ number
2033 * translation. The gpiochip will need to be initialized and registered
2034 * before calling this function.
2036 * This function will handle two cell:ed simple IRQs and assumes all
2037 * the pins on the gpiochip can generate a unique IRQ. Everything else
2038 * need to be open coded.
2040 int gpiochip_irqchip_add_key(struct gpio_chip *gpiochip,
2041 struct irq_chip *irqchip,
2042 unsigned int first_irq,
2043 irq_flow_handler_t handler,
2046 struct lock_class_key *lock_key,
2047 struct lock_class_key *request_key)
2049 struct device_node *of_node;
2051 if (!gpiochip || !irqchip)
2054 if (!gpiochip->parent) {
2055 pr_err("missing gpiochip .dev parent pointer\n");
2058 gpiochip->irq.threaded = threaded;
2059 of_node = gpiochip->parent->of_node;
2060 #ifdef CONFIG_OF_GPIO
2062 * If the gpiochip has an assigned OF node this takes precedence
2063 * FIXME: get rid of this and use gpiochip->parent->of_node
2066 if (gpiochip->of_node)
2067 of_node = gpiochip->of_node;
2070 * Specifying a default trigger is a terrible idea if DT or ACPI is
2071 * used to configure the interrupts, as you may end-up with
2072 * conflicting triggers. Tell the user, and reset to NONE.
2074 if (WARN(of_node && type != IRQ_TYPE_NONE,
2075 "%pOF: Ignoring %d default trigger\n", of_node, type))
2076 type = IRQ_TYPE_NONE;
2077 if (has_acpi_companion(gpiochip->parent) && type != IRQ_TYPE_NONE) {
2078 acpi_handle_warn(ACPI_HANDLE(gpiochip->parent),
2079 "Ignoring %d default trigger\n", type);
2080 type = IRQ_TYPE_NONE;
2083 gpiochip->irq.chip = irqchip;
2084 gpiochip->irq.handler = handler;
2085 gpiochip->irq.default_type = type;
2086 gpiochip->to_irq = gpiochip_to_irq;
2087 gpiochip->irq.lock_key = lock_key;
2088 gpiochip->irq.request_key = request_key;
2089 gpiochip->irq.domain = irq_domain_add_simple(of_node,
2090 gpiochip->ngpio, first_irq,
2091 &gpiochip_domain_ops, gpiochip);
2092 if (!gpiochip->irq.domain) {
2093 gpiochip->irq.chip = NULL;
2097 gpiochip_set_irq_hooks(gpiochip);
2099 acpi_gpiochip_request_interrupts(gpiochip);
2103 EXPORT_SYMBOL_GPL(gpiochip_irqchip_add_key);
2105 #else /* CONFIG_GPIOLIB_IRQCHIP */
2107 static inline int gpiochip_add_irqchip(struct gpio_chip *gpiochip,
2108 struct lock_class_key *lock_key,
2109 struct lock_class_key *request_key)
2114 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip) {}
2115 static inline int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gpiochip)
2119 static inline void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gpiochip)
2122 #endif /* CONFIG_GPIOLIB_IRQCHIP */
2125 * gpiochip_generic_request() - request the gpio function for a pin
2126 * @chip: the gpiochip owning the GPIO
2127 * @offset: the offset of the GPIO to request for GPIO function
2129 int gpiochip_generic_request(struct gpio_chip *chip, unsigned offset)
2131 return pinctrl_gpio_request(chip->gpiodev->base + offset);
2133 EXPORT_SYMBOL_GPL(gpiochip_generic_request);
2136 * gpiochip_generic_free() - free the gpio function from a pin
2137 * @chip: the gpiochip to request the gpio function for
2138 * @offset: the offset of the GPIO to free from GPIO function
2140 void gpiochip_generic_free(struct gpio_chip *chip, unsigned offset)
2142 pinctrl_gpio_free(chip->gpiodev->base + offset);
2144 EXPORT_SYMBOL_GPL(gpiochip_generic_free);
2147 * gpiochip_generic_config() - apply configuration for a pin
2148 * @chip: the gpiochip owning the GPIO
2149 * @offset: the offset of the GPIO to apply the configuration
2150 * @config: the configuration to be applied
2152 int gpiochip_generic_config(struct gpio_chip *chip, unsigned offset,
2153 unsigned long config)
2155 return pinctrl_gpio_set_config(chip->gpiodev->base + offset, config);
2157 EXPORT_SYMBOL_GPL(gpiochip_generic_config);
2159 #ifdef CONFIG_PINCTRL
2162 * gpiochip_add_pingroup_range() - add a range for GPIO <-> pin mapping
2163 * @chip: the gpiochip to add the range for
2164 * @pctldev: the pin controller to map to
2165 * @gpio_offset: the start offset in the current gpio_chip number space
2166 * @pin_group: name of the pin group inside the pin controller
2168 * Calling this function directly from a DeviceTree-supported
2169 * pinctrl driver is DEPRECATED. Please see Section 2.1 of
2170 * Documentation/devicetree/bindings/gpio/gpio.txt on how to
2171 * bind pinctrl and gpio drivers via the "gpio-ranges" property.
2173 int gpiochip_add_pingroup_range(struct gpio_chip *chip,
2174 struct pinctrl_dev *pctldev,
2175 unsigned int gpio_offset, const char *pin_group)
2177 struct gpio_pin_range *pin_range;
2178 struct gpio_device *gdev = chip->gpiodev;
2181 pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
2183 chip_err(chip, "failed to allocate pin ranges\n");
2187 /* Use local offset as range ID */
2188 pin_range->range.id = gpio_offset;
2189 pin_range->range.gc = chip;
2190 pin_range->range.name = chip->label;
2191 pin_range->range.base = gdev->base + gpio_offset;
2192 pin_range->pctldev = pctldev;
2194 ret = pinctrl_get_group_pins(pctldev, pin_group,
2195 &pin_range->range.pins,
2196 &pin_range->range.npins);
2202 pinctrl_add_gpio_range(pctldev, &pin_range->range);
2204 chip_dbg(chip, "created GPIO range %d->%d ==> %s PINGRP %s\n",
2205 gpio_offset, gpio_offset + pin_range->range.npins - 1,
2206 pinctrl_dev_get_devname(pctldev), pin_group);
2208 list_add_tail(&pin_range->node, &gdev->pin_ranges);
2212 EXPORT_SYMBOL_GPL(gpiochip_add_pingroup_range);
2215 * gpiochip_add_pin_range() - add a range for GPIO <-> pin mapping
2216 * @chip: the gpiochip to add the range for
2217 * @pinctl_name: the dev_name() of the pin controller to map to
2218 * @gpio_offset: the start offset in the current gpio_chip number space
2219 * @pin_offset: the start offset in the pin controller number space
2220 * @npins: the number of pins from the offset of each pin space (GPIO and
2221 * pin controller) to accumulate in this range
2224 * 0 on success, or a negative error-code on failure.
2226 * Calling this function directly from a DeviceTree-supported
2227 * pinctrl driver is DEPRECATED. Please see Section 2.1 of
2228 * Documentation/devicetree/bindings/gpio/gpio.txt on how to
2229 * bind pinctrl and gpio drivers via the "gpio-ranges" property.
2231 int gpiochip_add_pin_range(struct gpio_chip *chip, const char *pinctl_name,
2232 unsigned int gpio_offset, unsigned int pin_offset,
2235 struct gpio_pin_range *pin_range;
2236 struct gpio_device *gdev = chip->gpiodev;
2239 pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
2241 chip_err(chip, "failed to allocate pin ranges\n");
2245 /* Use local offset as range ID */
2246 pin_range->range.id = gpio_offset;
2247 pin_range->range.gc = chip;
2248 pin_range->range.name = chip->label;
2249 pin_range->range.base = gdev->base + gpio_offset;
2250 pin_range->range.pin_base = pin_offset;
2251 pin_range->range.npins = npins;
2252 pin_range->pctldev = pinctrl_find_and_add_gpio_range(pinctl_name,
2254 if (IS_ERR(pin_range->pctldev)) {
2255 ret = PTR_ERR(pin_range->pctldev);
2256 chip_err(chip, "could not create pin range\n");
2260 chip_dbg(chip, "created GPIO range %d->%d ==> %s PIN %d->%d\n",
2261 gpio_offset, gpio_offset + npins - 1,
2263 pin_offset, pin_offset + npins - 1);
2265 list_add_tail(&pin_range->node, &gdev->pin_ranges);
2269 EXPORT_SYMBOL_GPL(gpiochip_add_pin_range);
2272 * gpiochip_remove_pin_ranges() - remove all the GPIO <-> pin mappings
2273 * @chip: the chip to remove all the mappings for
2275 void gpiochip_remove_pin_ranges(struct gpio_chip *chip)
2277 struct gpio_pin_range *pin_range, *tmp;
2278 struct gpio_device *gdev = chip->gpiodev;
2280 list_for_each_entry_safe(pin_range, tmp, &gdev->pin_ranges, node) {
2281 list_del(&pin_range->node);
2282 pinctrl_remove_gpio_range(pin_range->pctldev,
2287 EXPORT_SYMBOL_GPL(gpiochip_remove_pin_ranges);
2289 #endif /* CONFIG_PINCTRL */
2291 /* These "optional" allocation calls help prevent drivers from stomping
2292 * on each other, and help provide better diagnostics in debugfs.
2293 * They're called even less than the "set direction" calls.
2295 static int gpiod_request_commit(struct gpio_desc *desc, const char *label)
2297 struct gpio_chip *chip = desc->gdev->chip;
2299 unsigned long flags;
2302 spin_lock_irqsave(&gpio_lock, flags);
2304 /* NOTE: gpio_request() can be called in early boot,
2305 * before IRQs are enabled, for non-sleeping (SOC) GPIOs.
2308 if (test_and_set_bit(FLAG_REQUESTED, &desc->flags) == 0) {
2309 desc_set_label(desc, label ? : "?");
2316 if (chip->request) {
2317 /* chip->request may sleep */
2318 spin_unlock_irqrestore(&gpio_lock, flags);
2319 offset = gpio_chip_hwgpio(desc);
2320 if (gpiochip_line_is_valid(chip, offset))
2321 status = chip->request(chip, offset);
2324 spin_lock_irqsave(&gpio_lock, flags);
2327 desc_set_label(desc, NULL);
2328 clear_bit(FLAG_REQUESTED, &desc->flags);
2332 if (chip->get_direction) {
2333 /* chip->get_direction may sleep */
2334 spin_unlock_irqrestore(&gpio_lock, flags);
2335 gpiod_get_direction(desc);
2336 spin_lock_irqsave(&gpio_lock, flags);
2339 spin_unlock_irqrestore(&gpio_lock, flags);
2344 * This descriptor validation needs to be inserted verbatim into each
2345 * function taking a descriptor, so we need to use a preprocessor
2346 * macro to avoid endless duplication. If the desc is NULL it is an
2347 * optional GPIO and calls should just bail out.
2349 static int validate_desc(const struct gpio_desc *desc, const char *func)
2354 pr_warn("%s: invalid GPIO (errorpointer)\n", func);
2355 return PTR_ERR(desc);
2358 pr_warn("%s: invalid GPIO (no device)\n", func);
2361 if (!desc->gdev->chip) {
2362 dev_warn(&desc->gdev->dev,
2363 "%s: backing chip is gone\n", func);
2369 #define VALIDATE_DESC(desc) do { \
2370 int __valid = validate_desc(desc, __func__); \
2375 #define VALIDATE_DESC_VOID(desc) do { \
2376 int __valid = validate_desc(desc, __func__); \
2381 int gpiod_request(struct gpio_desc *desc, const char *label)
2383 int status = -EPROBE_DEFER;
2384 struct gpio_device *gdev;
2386 VALIDATE_DESC(desc);
2389 if (try_module_get(gdev->owner)) {
2390 status = gpiod_request_commit(desc, label);
2392 module_put(gdev->owner);
2394 get_device(&gdev->dev);
2398 gpiod_dbg(desc, "%s: status %d\n", __func__, status);
2403 static bool gpiod_free_commit(struct gpio_desc *desc)
2406 unsigned long flags;
2407 struct gpio_chip *chip;
2411 gpiod_unexport(desc);
2413 spin_lock_irqsave(&gpio_lock, flags);
2415 chip = desc->gdev->chip;
2416 if (chip && test_bit(FLAG_REQUESTED, &desc->flags)) {
2418 spin_unlock_irqrestore(&gpio_lock, flags);
2419 might_sleep_if(chip->can_sleep);
2420 chip->free(chip, gpio_chip_hwgpio(desc));
2421 spin_lock_irqsave(&gpio_lock, flags);
2423 desc_set_label(desc, NULL);
2424 clear_bit(FLAG_ACTIVE_LOW, &desc->flags);
2425 clear_bit(FLAG_REQUESTED, &desc->flags);
2426 clear_bit(FLAG_OPEN_DRAIN, &desc->flags);
2427 clear_bit(FLAG_OPEN_SOURCE, &desc->flags);
2428 clear_bit(FLAG_IS_HOGGED, &desc->flags);
2432 spin_unlock_irqrestore(&gpio_lock, flags);
2436 void gpiod_free(struct gpio_desc *desc)
2438 if (desc && desc->gdev && gpiod_free_commit(desc)) {
2439 module_put(desc->gdev->owner);
2440 put_device(&desc->gdev->dev);
2442 WARN_ON(extra_checks);
2447 * gpiochip_is_requested - return string iff signal was requested
2448 * @chip: controller managing the signal
2449 * @offset: of signal within controller's 0..(ngpio - 1) range
2451 * Returns NULL if the GPIO is not currently requested, else a string.
2452 * The string returned is the label passed to gpio_request(); if none has been
2453 * passed it is a meaningless, non-NULL constant.
2455 * This function is for use by GPIO controller drivers. The label can
2456 * help with diagnostics, and knowing that the signal is used as a GPIO
2457 * can help avoid accidentally multiplexing it to another controller.
2459 const char *gpiochip_is_requested(struct gpio_chip *chip, unsigned offset)
2461 struct gpio_desc *desc;
2463 if (offset >= chip->ngpio)
2466 desc = &chip->gpiodev->descs[offset];
2468 if (test_bit(FLAG_REQUESTED, &desc->flags) == 0)
2472 EXPORT_SYMBOL_GPL(gpiochip_is_requested);
2475 * gpiochip_request_own_desc - Allow GPIO chip to request its own descriptor
2477 * @hwnum: hardware number of the GPIO for which to request the descriptor
2478 * @label: label for the GPIO
2480 * Function allows GPIO chip drivers to request and use their own GPIO
2481 * descriptors via gpiolib API. Difference to gpiod_request() is that this
2482 * function will not increase reference count of the GPIO chip module. This
2483 * allows the GPIO chip module to be unloaded as needed (we assume that the
2484 * GPIO chip driver handles freeing the GPIOs it has requested).
2487 * A pointer to the GPIO descriptor, or an ERR_PTR()-encoded negative error
2490 struct gpio_desc *gpiochip_request_own_desc(struct gpio_chip *chip, u16 hwnum,
2493 struct gpio_desc *desc = gpiochip_get_desc(chip, hwnum);
2497 chip_err(chip, "failed to get GPIO descriptor\n");
2501 err = gpiod_request_commit(desc, label);
2503 return ERR_PTR(err);
2507 EXPORT_SYMBOL_GPL(gpiochip_request_own_desc);
2510 * gpiochip_free_own_desc - Free GPIO requested by the chip driver
2511 * @desc: GPIO descriptor to free
2513 * Function frees the given GPIO requested previously with
2514 * gpiochip_request_own_desc().
2516 void gpiochip_free_own_desc(struct gpio_desc *desc)
2519 gpiod_free_commit(desc);
2521 EXPORT_SYMBOL_GPL(gpiochip_free_own_desc);
2524 * Drivers MUST set GPIO direction before making get/set calls. In
2525 * some cases this is done in early boot, before IRQs are enabled.
2527 * As a rule these aren't called more than once (except for drivers
2528 * using the open-drain emulation idiom) so these are natural places
2529 * to accumulate extra debugging checks. Note that we can't (yet)
2530 * rely on gpio_request() having been called beforehand.
2534 * gpiod_direction_input - set the GPIO direction to input
2535 * @desc: GPIO to set to input
2537 * Set the direction of the passed GPIO to input, such as gpiod_get_value() can
2538 * be called safely on it.
2540 * Return 0 in case of success, else an error code.
2542 int gpiod_direction_input(struct gpio_desc *desc)
2544 struct gpio_chip *chip;
2545 int status = -EINVAL;
2547 VALIDATE_DESC(desc);
2548 chip = desc->gdev->chip;
2550 if (!chip->get || !chip->direction_input) {
2552 "%s: missing get() or direction_input() operations\n",
2557 status = chip->direction_input(chip, gpio_chip_hwgpio(desc));
2559 clear_bit(FLAG_IS_OUT, &desc->flags);
2561 trace_gpio_direction(desc_to_gpio(desc), 1, status);
2565 EXPORT_SYMBOL_GPL(gpiod_direction_input);
2567 static int gpio_set_drive_single_ended(struct gpio_chip *gc, unsigned offset,
2568 enum pin_config_param mode)
2570 unsigned long config = { PIN_CONF_PACKED(mode, 0) };
2572 return gc->set_config ? gc->set_config(gc, offset, config) : -ENOTSUPP;
2575 static int gpiod_direction_output_raw_commit(struct gpio_desc *desc, int value)
2577 struct gpio_chip *gc = desc->gdev->chip;
2581 if (!gc->set || !gc->direction_output) {
2583 "%s: missing set() or direction_output() operations\n",
2588 ret = gc->direction_output(gc, gpio_chip_hwgpio(desc), val);
2590 set_bit(FLAG_IS_OUT, &desc->flags);
2591 trace_gpio_value(desc_to_gpio(desc), 0, val);
2592 trace_gpio_direction(desc_to_gpio(desc), 0, ret);
2597 * gpiod_direction_output_raw - set the GPIO direction to output
2598 * @desc: GPIO to set to output
2599 * @value: initial output value of the GPIO
2601 * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
2602 * be called safely on it. The initial value of the output must be specified
2603 * as raw value on the physical line without regard for the ACTIVE_LOW status.
2605 * Return 0 in case of success, else an error code.
2607 int gpiod_direction_output_raw(struct gpio_desc *desc, int value)
2609 VALIDATE_DESC(desc);
2610 return gpiod_direction_output_raw_commit(desc, value);
2612 EXPORT_SYMBOL_GPL(gpiod_direction_output_raw);
2615 * gpiod_direction_output - set the GPIO direction to output
2616 * @desc: GPIO to set to output
2617 * @value: initial output value of the GPIO
2619 * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
2620 * be called safely on it. The initial value of the output must be specified
2621 * as the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
2624 * Return 0 in case of success, else an error code.
2626 int gpiod_direction_output(struct gpio_desc *desc, int value)
2628 struct gpio_chip *gc;
2631 VALIDATE_DESC(desc);
2632 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2637 /* GPIOs used for enabled IRQs shall not be set as output */
2638 if (test_bit(FLAG_USED_AS_IRQ, &desc->flags) &&
2639 test_bit(FLAG_IRQ_IS_ENABLED, &desc->flags)) {
2641 "%s: tried to set a GPIO tied to an IRQ as output\n",
2646 gc = desc->gdev->chip;
2647 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags)) {
2648 /* First see if we can enable open drain in hardware */
2649 ret = gpio_set_drive_single_ended(gc, gpio_chip_hwgpio(desc),
2650 PIN_CONFIG_DRIVE_OPEN_DRAIN);
2652 goto set_output_value;
2653 /* Emulate open drain by not actively driving the line high */
2655 return gpiod_direction_input(desc);
2657 else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags)) {
2658 ret = gpio_set_drive_single_ended(gc, gpio_chip_hwgpio(desc),
2659 PIN_CONFIG_DRIVE_OPEN_SOURCE);
2661 goto set_output_value;
2662 /* Emulate open source by not actively driving the line low */
2664 return gpiod_direction_input(desc);
2666 gpio_set_drive_single_ended(gc, gpio_chip_hwgpio(desc),
2667 PIN_CONFIG_DRIVE_PUSH_PULL);
2671 return gpiod_direction_output_raw_commit(desc, value);
2673 EXPORT_SYMBOL_GPL(gpiod_direction_output);
2676 * gpiod_set_debounce - sets @debounce time for a GPIO
2677 * @desc: descriptor of the GPIO for which to set debounce time
2678 * @debounce: debounce time in microseconds
2681 * 0 on success, %-ENOTSUPP if the controller doesn't support setting the
2684 int gpiod_set_debounce(struct gpio_desc *desc, unsigned debounce)
2686 struct gpio_chip *chip;
2687 unsigned long config;
2689 VALIDATE_DESC(desc);
2690 chip = desc->gdev->chip;
2691 if (!chip->set || !chip->set_config) {
2693 "%s: missing set() or set_config() operations\n",
2698 config = pinconf_to_config_packed(PIN_CONFIG_INPUT_DEBOUNCE, debounce);
2699 return chip->set_config(chip, gpio_chip_hwgpio(desc), config);
2701 EXPORT_SYMBOL_GPL(gpiod_set_debounce);
2704 * gpiod_set_transitory - Lose or retain GPIO state on suspend or reset
2705 * @desc: descriptor of the GPIO for which to configure persistence
2706 * @transitory: True to lose state on suspend or reset, false for persistence
2709 * 0 on success, otherwise a negative error code.
2711 int gpiod_set_transitory(struct gpio_desc *desc, bool transitory)
2713 struct gpio_chip *chip;
2714 unsigned long packed;
2718 VALIDATE_DESC(desc);
2720 * Handle FLAG_TRANSITORY first, enabling queries to gpiolib for
2721 * persistence state.
2724 set_bit(FLAG_TRANSITORY, &desc->flags);
2726 clear_bit(FLAG_TRANSITORY, &desc->flags);
2728 /* If the driver supports it, set the persistence state now */
2729 chip = desc->gdev->chip;
2730 if (!chip->set_config)
2733 packed = pinconf_to_config_packed(PIN_CONFIG_PERSIST_STATE,
2735 gpio = gpio_chip_hwgpio(desc);
2736 rc = chip->set_config(chip, gpio, packed);
2737 if (rc == -ENOTSUPP) {
2738 dev_dbg(&desc->gdev->dev, "Persistence not supported for GPIO %d\n",
2745 EXPORT_SYMBOL_GPL(gpiod_set_transitory);
2748 * gpiod_is_active_low - test whether a GPIO is active-low or not
2749 * @desc: the gpio descriptor to test
2751 * Returns 1 if the GPIO is active-low, 0 otherwise.
2753 int gpiod_is_active_low(const struct gpio_desc *desc)
2755 VALIDATE_DESC(desc);
2756 return test_bit(FLAG_ACTIVE_LOW, &desc->flags);
2758 EXPORT_SYMBOL_GPL(gpiod_is_active_low);
2760 /* I/O calls are only valid after configuration completed; the relevant
2761 * "is this a valid GPIO" error checks should already have been done.
2763 * "Get" operations are often inlinable as reading a pin value register,
2764 * and masking the relevant bit in that register.
2766 * When "set" operations are inlinable, they involve writing that mask to
2767 * one register to set a low value, or a different register to set it high.
2768 * Otherwise locking is needed, so there may be little value to inlining.
2770 *------------------------------------------------------------------------
2772 * IMPORTANT!!! The hot paths -- get/set value -- assume that callers
2773 * have requested the GPIO. That can include implicit requesting by
2774 * a direction setting call. Marking a gpio as requested locks its chip
2775 * in memory, guaranteeing that these table lookups need no more locking
2776 * and that gpiochip_remove() will fail.
2778 * REVISIT when debugging, consider adding some instrumentation to ensure
2779 * that the GPIO was actually requested.
2782 static int gpiod_get_raw_value_commit(const struct gpio_desc *desc)
2784 struct gpio_chip *chip;
2788 chip = desc->gdev->chip;
2789 offset = gpio_chip_hwgpio(desc);
2790 value = chip->get ? chip->get(chip, offset) : -EIO;
2791 value = value < 0 ? value : !!value;
2792 trace_gpio_value(desc_to_gpio(desc), 1, value);
2796 static int gpio_chip_get_multiple(struct gpio_chip *chip,
2797 unsigned long *mask, unsigned long *bits)
2799 if (chip->get_multiple) {
2800 return chip->get_multiple(chip, mask, bits);
2801 } else if (chip->get) {
2804 for_each_set_bit(i, mask, chip->ngpio) {
2805 value = chip->get(chip, i);
2808 __assign_bit(i, bits, value);
2815 int gpiod_get_array_value_complex(bool raw, bool can_sleep,
2816 unsigned int array_size,
2817 struct gpio_desc **desc_array,
2818 struct gpio_array *array_info,
2819 unsigned long *value_bitmap)
2824 * Validate array_info against desc_array and its size.
2825 * It should immediately follow desc_array if both
2826 * have been obtained from the same gpiod_get_array() call.
2828 if (array_info && array_info->desc == desc_array &&
2829 array_size <= array_info->size &&
2830 (void *)array_info == desc_array + array_info->size) {
2832 WARN_ON(array_info->chip->can_sleep);
2834 err = gpio_chip_get_multiple(array_info->chip,
2835 array_info->get_mask,
2840 if (!raw && !bitmap_empty(array_info->invert_mask, array_size))
2841 bitmap_xor(value_bitmap, value_bitmap,
2842 array_info->invert_mask, array_size);
2844 if (bitmap_full(array_info->get_mask, array_size))
2847 i = find_first_zero_bit(array_info->get_mask, array_size);
2852 while (i < array_size) {
2853 struct gpio_chip *chip = desc_array[i]->gdev->chip;
2854 unsigned long fastpath[2 * BITS_TO_LONGS(FASTPATH_NGPIO)];
2855 unsigned long *mask, *bits;
2858 if (likely(chip->ngpio <= FASTPATH_NGPIO)) {
2861 mask = kmalloc_array(2 * BITS_TO_LONGS(chip->ngpio),
2863 can_sleep ? GFP_KERNEL : GFP_ATOMIC);
2868 bits = mask + BITS_TO_LONGS(chip->ngpio);
2869 bitmap_zero(mask, chip->ngpio);
2872 WARN_ON(chip->can_sleep);
2874 /* collect all inputs belonging to the same chip */
2877 const struct gpio_desc *desc = desc_array[i];
2878 int hwgpio = gpio_chip_hwgpio(desc);
2880 __set_bit(hwgpio, mask);
2883 i = find_next_zero_bit(array_info->get_mask,
2887 } while ((i < array_size) &&
2888 (desc_array[i]->gdev->chip == chip));
2890 ret = gpio_chip_get_multiple(chip, mask, bits);
2892 if (mask != fastpath)
2897 for (j = first; j < i; ) {
2898 const struct gpio_desc *desc = desc_array[j];
2899 int hwgpio = gpio_chip_hwgpio(desc);
2900 int value = test_bit(hwgpio, bits);
2902 if (!raw && test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2904 __assign_bit(j, value_bitmap, value);
2905 trace_gpio_value(desc_to_gpio(desc), 1, value);
2908 j = find_next_zero_bit(array_info->get_mask, i,
2914 if (mask != fastpath)
2921 * gpiod_get_raw_value() - return a gpio's raw value
2922 * @desc: gpio whose value will be returned
2924 * Return the GPIO's raw value, i.e. the value of the physical line disregarding
2925 * its ACTIVE_LOW status, or negative errno on failure.
2927 * This function should be called from contexts where we cannot sleep, and will
2928 * complain if the GPIO chip functions potentially sleep.
2930 int gpiod_get_raw_value(const struct gpio_desc *desc)
2932 VALIDATE_DESC(desc);
2933 /* Should be using gpio_get_value_cansleep() */
2934 WARN_ON(desc->gdev->chip->can_sleep);
2935 return gpiod_get_raw_value_commit(desc);
2937 EXPORT_SYMBOL_GPL(gpiod_get_raw_value);
2940 * gpiod_get_value() - return a gpio's value
2941 * @desc: gpio whose value will be returned
2943 * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
2944 * account, or negative errno on failure.
2946 * This function should be called from contexts where we cannot sleep, and will
2947 * complain if the GPIO chip functions potentially sleep.
2949 int gpiod_get_value(const struct gpio_desc *desc)
2953 VALIDATE_DESC(desc);
2954 /* Should be using gpio_get_value_cansleep() */
2955 WARN_ON(desc->gdev->chip->can_sleep);
2957 value = gpiod_get_raw_value_commit(desc);
2961 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2966 EXPORT_SYMBOL_GPL(gpiod_get_value);
2969 * gpiod_get_raw_array_value() - read raw values from an array of GPIOs
2970 * @array_size: number of elements in the descriptor array / value bitmap
2971 * @desc_array: array of GPIO descriptors whose values will be read
2972 * @array_info: information on applicability of fast bitmap processing path
2973 * @value_bitmap: bitmap to store the read values
2975 * Read the raw values of the GPIOs, i.e. the values of the physical lines
2976 * without regard for their ACTIVE_LOW status. Return 0 in case of success,
2977 * else an error code.
2979 * This function should be called from contexts where we cannot sleep,
2980 * and it will complain if the GPIO chip functions potentially sleep.
2982 int gpiod_get_raw_array_value(unsigned int array_size,
2983 struct gpio_desc **desc_array,
2984 struct gpio_array *array_info,
2985 unsigned long *value_bitmap)
2989 return gpiod_get_array_value_complex(true, false, array_size,
2990 desc_array, array_info,
2993 EXPORT_SYMBOL_GPL(gpiod_get_raw_array_value);
2996 * gpiod_get_array_value() - read values from an array of GPIOs
2997 * @array_size: number of elements in the descriptor array / value bitmap
2998 * @desc_array: array of GPIO descriptors whose values will be read
2999 * @array_info: information on applicability of fast bitmap processing path
3000 * @value_bitmap: bitmap to store the read values
3002 * Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3003 * into account. Return 0 in case of success, else an error code.
3005 * This function should be called from contexts where we cannot sleep,
3006 * and it will complain if the GPIO chip functions potentially sleep.
3008 int gpiod_get_array_value(unsigned int array_size,
3009 struct gpio_desc **desc_array,
3010 struct gpio_array *array_info,
3011 unsigned long *value_bitmap)
3015 return gpiod_get_array_value_complex(false, false, array_size,
3016 desc_array, array_info,
3019 EXPORT_SYMBOL_GPL(gpiod_get_array_value);
3022 * gpio_set_open_drain_value_commit() - Set the open drain gpio's value.
3023 * @desc: gpio descriptor whose state need to be set.
3024 * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
3026 static void gpio_set_open_drain_value_commit(struct gpio_desc *desc, bool value)
3029 struct gpio_chip *chip = desc->gdev->chip;
3030 int offset = gpio_chip_hwgpio(desc);
3033 err = chip->direction_input(chip, offset);
3035 clear_bit(FLAG_IS_OUT, &desc->flags);
3037 err = chip->direction_output(chip, offset, 0);
3039 set_bit(FLAG_IS_OUT, &desc->flags);
3041 trace_gpio_direction(desc_to_gpio(desc), value, err);
3044 "%s: Error in set_value for open drain err %d\n",
3049 * _gpio_set_open_source_value() - Set the open source gpio's value.
3050 * @desc: gpio descriptor whose state need to be set.
3051 * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
3053 static void gpio_set_open_source_value_commit(struct gpio_desc *desc, bool value)
3056 struct gpio_chip *chip = desc->gdev->chip;
3057 int offset = gpio_chip_hwgpio(desc);
3060 err = chip->direction_output(chip, offset, 1);
3062 set_bit(FLAG_IS_OUT, &desc->flags);
3064 err = chip->direction_input(chip, offset);
3066 clear_bit(FLAG_IS_OUT, &desc->flags);
3068 trace_gpio_direction(desc_to_gpio(desc), !value, err);
3071 "%s: Error in set_value for open source err %d\n",
3075 static void gpiod_set_raw_value_commit(struct gpio_desc *desc, bool value)
3077 struct gpio_chip *chip;
3079 chip = desc->gdev->chip;
3080 trace_gpio_value(desc_to_gpio(desc), 0, value);
3081 chip->set(chip, gpio_chip_hwgpio(desc), value);
3085 * set multiple outputs on the same chip;
3086 * use the chip's set_multiple function if available;
3087 * otherwise set the outputs sequentially;
3088 * @mask: bit mask array; one bit per output; BITS_PER_LONG bits per word
3089 * defines which outputs are to be changed
3090 * @bits: bit value array; one bit per output; BITS_PER_LONG bits per word
3091 * defines the values the outputs specified by mask are to be set to
3093 static void gpio_chip_set_multiple(struct gpio_chip *chip,
3094 unsigned long *mask, unsigned long *bits)
3096 if (chip->set_multiple) {
3097 chip->set_multiple(chip, mask, bits);
3101 /* set outputs if the corresponding mask bit is set */
3102 for_each_set_bit(i, mask, chip->ngpio)
3103 chip->set(chip, i, test_bit(i, bits));
3107 int gpiod_set_array_value_complex(bool raw, bool can_sleep,
3108 unsigned int array_size,
3109 struct gpio_desc **desc_array,
3110 struct gpio_array *array_info,
3111 unsigned long *value_bitmap)
3116 * Validate array_info against desc_array and its size.
3117 * It should immediately follow desc_array if both
3118 * have been obtained from the same gpiod_get_array() call.
3120 if (array_info && array_info->desc == desc_array &&
3121 array_size <= array_info->size &&
3122 (void *)array_info == desc_array + array_info->size) {
3124 WARN_ON(array_info->chip->can_sleep);
3126 if (!raw && !bitmap_empty(array_info->invert_mask, array_size))
3127 bitmap_xor(value_bitmap, value_bitmap,
3128 array_info->invert_mask, array_size);
3130 gpio_chip_set_multiple(array_info->chip, array_info->set_mask,
3133 if (bitmap_full(array_info->set_mask, array_size))
3136 i = find_first_zero_bit(array_info->set_mask, array_size);
3141 while (i < array_size) {
3142 struct gpio_chip *chip = desc_array[i]->gdev->chip;
3143 unsigned long fastpath[2 * BITS_TO_LONGS(FASTPATH_NGPIO)];
3144 unsigned long *mask, *bits;
3147 if (likely(chip->ngpio <= FASTPATH_NGPIO)) {
3150 mask = kmalloc_array(2 * BITS_TO_LONGS(chip->ngpio),
3152 can_sleep ? GFP_KERNEL : GFP_ATOMIC);
3157 bits = mask + BITS_TO_LONGS(chip->ngpio);
3158 bitmap_zero(mask, chip->ngpio);
3161 WARN_ON(chip->can_sleep);
3164 struct gpio_desc *desc = desc_array[i];
3165 int hwgpio = gpio_chip_hwgpio(desc);
3166 int value = test_bit(i, value_bitmap);
3169 * Pins applicable for fast input but not for
3170 * fast output processing may have been already
3171 * inverted inside the fast path, skip them.
3173 if (!raw && !(array_info &&
3174 test_bit(i, array_info->invert_mask)) &&
3175 test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3177 trace_gpio_value(desc_to_gpio(desc), 0, value);
3179 * collect all normal outputs belonging to the same chip
3180 * open drain and open source outputs are set individually
3182 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags) && !raw) {
3183 gpio_set_open_drain_value_commit(desc, value);
3184 } else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags) && !raw) {
3185 gpio_set_open_source_value_commit(desc, value);
3187 __set_bit(hwgpio, mask);
3189 __set_bit(hwgpio, bits);
3191 __clear_bit(hwgpio, bits);
3196 i = find_next_zero_bit(array_info->set_mask,
3200 } while ((i < array_size) &&
3201 (desc_array[i]->gdev->chip == chip));
3202 /* push collected bits to outputs */
3204 gpio_chip_set_multiple(chip, mask, bits);
3206 if (mask != fastpath)
3213 * gpiod_set_raw_value() - assign a gpio's raw value
3214 * @desc: gpio whose value will be assigned
3215 * @value: value to assign
3217 * Set the raw value of the GPIO, i.e. the value of its physical line without
3218 * regard for its ACTIVE_LOW status.
3220 * This function should be called from contexts where we cannot sleep, and will
3221 * complain if the GPIO chip functions potentially sleep.
3223 void gpiod_set_raw_value(struct gpio_desc *desc, int value)
3225 VALIDATE_DESC_VOID(desc);
3226 /* Should be using gpiod_set_value_cansleep() */
3227 WARN_ON(desc->gdev->chip->can_sleep);
3228 gpiod_set_raw_value_commit(desc, value);
3230 EXPORT_SYMBOL_GPL(gpiod_set_raw_value);
3233 * gpiod_set_value_nocheck() - set a GPIO line value without checking
3234 * @desc: the descriptor to set the value on
3235 * @value: value to set
3237 * This sets the value of a GPIO line backing a descriptor, applying
3238 * different semantic quirks like active low and open drain/source
3241 static void gpiod_set_value_nocheck(struct gpio_desc *desc, int value)
3243 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3245 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
3246 gpio_set_open_drain_value_commit(desc, value);
3247 else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
3248 gpio_set_open_source_value_commit(desc, value);
3250 gpiod_set_raw_value_commit(desc, value);
3254 * gpiod_set_value() - assign a gpio's value
3255 * @desc: gpio whose value will be assigned
3256 * @value: value to assign
3258 * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW,
3259 * OPEN_DRAIN and OPEN_SOURCE flags into account.
3261 * This function should be called from contexts where we cannot sleep, and will
3262 * complain if the GPIO chip functions potentially sleep.
3264 void gpiod_set_value(struct gpio_desc *desc, int value)
3266 VALIDATE_DESC_VOID(desc);
3267 WARN_ON(desc->gdev->chip->can_sleep);
3268 gpiod_set_value_nocheck(desc, value);
3270 EXPORT_SYMBOL_GPL(gpiod_set_value);
3273 * gpiod_set_raw_array_value() - assign values to an array of GPIOs
3274 * @array_size: number of elements in the descriptor array / value bitmap
3275 * @desc_array: array of GPIO descriptors whose values will be assigned
3276 * @array_info: information on applicability of fast bitmap processing path
3277 * @value_bitmap: bitmap of values to assign
3279 * Set the raw values of the GPIOs, i.e. the values of the physical lines
3280 * without regard for their ACTIVE_LOW status.
3282 * This function should be called from contexts where we cannot sleep, and will
3283 * complain if the GPIO chip functions potentially sleep.
3285 int gpiod_set_raw_array_value(unsigned int array_size,
3286 struct gpio_desc **desc_array,
3287 struct gpio_array *array_info,
3288 unsigned long *value_bitmap)
3292 return gpiod_set_array_value_complex(true, false, array_size,
3293 desc_array, array_info, value_bitmap);
3295 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value);
3298 * gpiod_set_array_value() - assign values to an array of GPIOs
3299 * @array_size: number of elements in the descriptor array / value bitmap
3300 * @desc_array: array of GPIO descriptors whose values will be assigned
3301 * @array_info: information on applicability of fast bitmap processing path
3302 * @value_bitmap: bitmap of values to assign
3304 * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3307 * This function should be called from contexts where we cannot sleep, and will
3308 * complain if the GPIO chip functions potentially sleep.
3310 void gpiod_set_array_value(unsigned int array_size,
3311 struct gpio_desc **desc_array,
3312 struct gpio_array *array_info,
3313 unsigned long *value_bitmap)
3317 gpiod_set_array_value_complex(false, false, array_size, desc_array,
3318 array_info, value_bitmap);
3320 EXPORT_SYMBOL_GPL(gpiod_set_array_value);
3323 * gpiod_cansleep() - report whether gpio value access may sleep
3324 * @desc: gpio to check
3327 int gpiod_cansleep(const struct gpio_desc *desc)
3329 VALIDATE_DESC(desc);
3330 return desc->gdev->chip->can_sleep;
3332 EXPORT_SYMBOL_GPL(gpiod_cansleep);
3335 * gpiod_set_consumer_name() - set the consumer name for the descriptor
3336 * @desc: gpio to set the consumer name on
3337 * @name: the new consumer name
3339 void gpiod_set_consumer_name(struct gpio_desc *desc, const char *name)
3341 VALIDATE_DESC_VOID(desc);
3342 /* Just overwrite whatever the previous name was */
3345 EXPORT_SYMBOL_GPL(gpiod_set_consumer_name);
3348 * gpiod_to_irq() - return the IRQ corresponding to a GPIO
3349 * @desc: gpio whose IRQ will be returned (already requested)
3351 * Return the IRQ corresponding to the passed GPIO, or an error code in case of
3354 int gpiod_to_irq(const struct gpio_desc *desc)
3356 struct gpio_chip *chip;
3360 * Cannot VALIDATE_DESC() here as gpiod_to_irq() consumer semantics
3361 * requires this function to not return zero on an invalid descriptor
3362 * but rather a negative error number.
3364 if (!desc || IS_ERR(desc) || !desc->gdev || !desc->gdev->chip)
3367 chip = desc->gdev->chip;
3368 offset = gpio_chip_hwgpio(desc);
3370 int retirq = chip->to_irq(chip, offset);
3372 /* Zero means NO_IRQ */
3380 EXPORT_SYMBOL_GPL(gpiod_to_irq);
3383 * gpiochip_lock_as_irq() - lock a GPIO to be used as IRQ
3384 * @chip: the chip the GPIO to lock belongs to
3385 * @offset: the offset of the GPIO to lock as IRQ
3387 * This is used directly by GPIO drivers that want to lock down
3388 * a certain GPIO line to be used for IRQs.
3390 int gpiochip_lock_as_irq(struct gpio_chip *chip, unsigned int offset)
3392 struct gpio_desc *desc;
3394 desc = gpiochip_get_desc(chip, offset);
3396 return PTR_ERR(desc);
3399 * If it's fast: flush the direction setting if something changed
3402 if (!chip->can_sleep && chip->get_direction) {
3403 int dir = gpiod_get_direction(desc);
3406 chip_err(chip, "%s: cannot get GPIO direction\n",
3412 if (test_bit(FLAG_IS_OUT, &desc->flags)) {
3414 "%s: tried to flag a GPIO set as output for IRQ\n",
3419 set_bit(FLAG_USED_AS_IRQ, &desc->flags);
3420 set_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
3423 * If the consumer has not set up a label (such as when the
3424 * IRQ is referenced from .to_irq()) we set up a label here
3425 * so it is clear this is used as an interrupt.
3428 desc_set_label(desc, "interrupt");
3432 EXPORT_SYMBOL_GPL(gpiochip_lock_as_irq);
3435 * gpiochip_unlock_as_irq() - unlock a GPIO used as IRQ
3436 * @chip: the chip the GPIO to lock belongs to
3437 * @offset: the offset of the GPIO to lock as IRQ
3439 * This is used directly by GPIO drivers that want to indicate
3440 * that a certain GPIO is no longer used exclusively for IRQ.
3442 void gpiochip_unlock_as_irq(struct gpio_chip *chip, unsigned int offset)
3444 struct gpio_desc *desc;
3446 desc = gpiochip_get_desc(chip, offset);
3450 clear_bit(FLAG_USED_AS_IRQ, &desc->flags);
3451 clear_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
3453 /* If we only had this marking, erase it */
3454 if (desc->label && !strcmp(desc->label, "interrupt"))
3455 desc_set_label(desc, NULL);
3457 EXPORT_SYMBOL_GPL(gpiochip_unlock_as_irq);
3459 void gpiochip_disable_irq(struct gpio_chip *chip, unsigned int offset)
3461 struct gpio_desc *desc = gpiochip_get_desc(chip, offset);
3463 if (!IS_ERR(desc) &&
3464 !WARN_ON(!test_bit(FLAG_USED_AS_IRQ, &desc->flags)))
3465 clear_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
3467 EXPORT_SYMBOL_GPL(gpiochip_disable_irq);
3469 void gpiochip_enable_irq(struct gpio_chip *chip, unsigned int offset)
3471 struct gpio_desc *desc = gpiochip_get_desc(chip, offset);
3473 if (!IS_ERR(desc) &&
3474 !WARN_ON(!test_bit(FLAG_USED_AS_IRQ, &desc->flags))) {
3475 WARN_ON(test_bit(FLAG_IS_OUT, &desc->flags));
3476 set_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
3479 EXPORT_SYMBOL_GPL(gpiochip_enable_irq);
3481 bool gpiochip_line_is_irq(struct gpio_chip *chip, unsigned int offset)
3483 if (offset >= chip->ngpio)
3486 return test_bit(FLAG_USED_AS_IRQ, &chip->gpiodev->descs[offset].flags);
3488 EXPORT_SYMBOL_GPL(gpiochip_line_is_irq);
3490 int gpiochip_reqres_irq(struct gpio_chip *chip, unsigned int offset)
3494 if (!try_module_get(chip->gpiodev->owner))
3497 ret = gpiochip_lock_as_irq(chip, offset);
3499 chip_err(chip, "unable to lock HW IRQ %u for IRQ\n", offset);
3500 module_put(chip->gpiodev->owner);
3505 EXPORT_SYMBOL_GPL(gpiochip_reqres_irq);
3507 void gpiochip_relres_irq(struct gpio_chip *chip, unsigned int offset)
3509 gpiochip_unlock_as_irq(chip, offset);
3510 module_put(chip->gpiodev->owner);
3512 EXPORT_SYMBOL_GPL(gpiochip_relres_irq);
3514 bool gpiochip_line_is_open_drain(struct gpio_chip *chip, unsigned int offset)
3516 if (offset >= chip->ngpio)
3519 return test_bit(FLAG_OPEN_DRAIN, &chip->gpiodev->descs[offset].flags);
3521 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_drain);
3523 bool gpiochip_line_is_open_source(struct gpio_chip *chip, unsigned int offset)
3525 if (offset >= chip->ngpio)
3528 return test_bit(FLAG_OPEN_SOURCE, &chip->gpiodev->descs[offset].flags);
3530 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_source);
3532 bool gpiochip_line_is_persistent(struct gpio_chip *chip, unsigned int offset)
3534 if (offset >= chip->ngpio)
3537 return !test_bit(FLAG_TRANSITORY, &chip->gpiodev->descs[offset].flags);
3539 EXPORT_SYMBOL_GPL(gpiochip_line_is_persistent);
3542 * gpiod_get_raw_value_cansleep() - return a gpio's raw value
3543 * @desc: gpio whose value will be returned
3545 * Return the GPIO's raw value, i.e. the value of the physical line disregarding
3546 * its ACTIVE_LOW status, or negative errno on failure.
3548 * This function is to be called from contexts that can sleep.
3550 int gpiod_get_raw_value_cansleep(const struct gpio_desc *desc)
3552 might_sleep_if(extra_checks);
3553 VALIDATE_DESC(desc);
3554 return gpiod_get_raw_value_commit(desc);
3556 EXPORT_SYMBOL_GPL(gpiod_get_raw_value_cansleep);
3559 * gpiod_get_value_cansleep() - return a gpio's value
3560 * @desc: gpio whose value will be returned
3562 * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
3563 * account, or negative errno on failure.
3565 * This function is to be called from contexts that can sleep.
3567 int gpiod_get_value_cansleep(const struct gpio_desc *desc)
3571 might_sleep_if(extra_checks);
3572 VALIDATE_DESC(desc);
3573 value = gpiod_get_raw_value_commit(desc);
3577 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3582 EXPORT_SYMBOL_GPL(gpiod_get_value_cansleep);
3585 * gpiod_get_raw_array_value_cansleep() - read raw values from an array of GPIOs
3586 * @array_size: number of elements in the descriptor array / value bitmap
3587 * @desc_array: array of GPIO descriptors whose values will be read
3588 * @array_info: information on applicability of fast bitmap processing path
3589 * @value_bitmap: bitmap to store the read values
3591 * Read the raw values of the GPIOs, i.e. the values of the physical lines
3592 * without regard for their ACTIVE_LOW status. Return 0 in case of success,
3593 * else an error code.
3595 * This function is to be called from contexts that can sleep.
3597 int gpiod_get_raw_array_value_cansleep(unsigned int array_size,
3598 struct gpio_desc **desc_array,
3599 struct gpio_array *array_info,
3600 unsigned long *value_bitmap)
3602 might_sleep_if(extra_checks);
3605 return gpiod_get_array_value_complex(true, true, array_size,
3606 desc_array, array_info,
3609 EXPORT_SYMBOL_GPL(gpiod_get_raw_array_value_cansleep);
3612 * gpiod_get_array_value_cansleep() - read values from an array of GPIOs
3613 * @array_size: number of elements in the descriptor array / value bitmap
3614 * @desc_array: array of GPIO descriptors whose values will be read
3615 * @array_info: information on applicability of fast bitmap processing path
3616 * @value_bitmap: bitmap to store the read values
3618 * Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3619 * into account. Return 0 in case of success, else an error code.
3621 * This function is to be called from contexts that can sleep.
3623 int gpiod_get_array_value_cansleep(unsigned int array_size,
3624 struct gpio_desc **desc_array,
3625 struct gpio_array *array_info,
3626 unsigned long *value_bitmap)
3628 might_sleep_if(extra_checks);
3631 return gpiod_get_array_value_complex(false, true, array_size,
3632 desc_array, array_info,
3635 EXPORT_SYMBOL_GPL(gpiod_get_array_value_cansleep);
3638 * gpiod_set_raw_value_cansleep() - assign a gpio's raw value
3639 * @desc: gpio whose value will be assigned
3640 * @value: value to assign
3642 * Set the raw value of the GPIO, i.e. the value of its physical line without
3643 * regard for its ACTIVE_LOW status.
3645 * This function is to be called from contexts that can sleep.
3647 void gpiod_set_raw_value_cansleep(struct gpio_desc *desc, int value)
3649 might_sleep_if(extra_checks);
3650 VALIDATE_DESC_VOID(desc);
3651 gpiod_set_raw_value_commit(desc, value);
3653 EXPORT_SYMBOL_GPL(gpiod_set_raw_value_cansleep);
3656 * gpiod_set_value_cansleep() - assign a gpio's value
3657 * @desc: gpio whose value will be assigned
3658 * @value: value to assign
3660 * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
3663 * This function is to be called from contexts that can sleep.
3665 void gpiod_set_value_cansleep(struct gpio_desc *desc, int value)
3667 might_sleep_if(extra_checks);
3668 VALIDATE_DESC_VOID(desc);
3669 gpiod_set_value_nocheck(desc, value);
3671 EXPORT_SYMBOL_GPL(gpiod_set_value_cansleep);
3674 * gpiod_set_raw_array_value_cansleep() - assign values to an array of GPIOs
3675 * @array_size: number of elements in the descriptor array / value bitmap
3676 * @desc_array: array of GPIO descriptors whose values will be assigned
3677 * @array_info: information on applicability of fast bitmap processing path
3678 * @value_bitmap: bitmap of values to assign
3680 * Set the raw values of the GPIOs, i.e. the values of the physical lines
3681 * without regard for their ACTIVE_LOW status.
3683 * This function is to be called from contexts that can sleep.
3685 int gpiod_set_raw_array_value_cansleep(unsigned int array_size,
3686 struct gpio_desc **desc_array,
3687 struct gpio_array *array_info,
3688 unsigned long *value_bitmap)
3690 might_sleep_if(extra_checks);
3693 return gpiod_set_array_value_complex(true, true, array_size, desc_array,
3694 array_info, value_bitmap);
3696 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value_cansleep);
3699 * gpiod_add_lookup_tables() - register GPIO device consumers
3700 * @tables: list of tables of consumers to register
3701 * @n: number of tables in the list
3703 void gpiod_add_lookup_tables(struct gpiod_lookup_table **tables, size_t n)
3707 mutex_lock(&gpio_lookup_lock);
3709 for (i = 0; i < n; i++)
3710 list_add_tail(&tables[i]->list, &gpio_lookup_list);
3712 mutex_unlock(&gpio_lookup_lock);
3716 * gpiod_set_array_value_cansleep() - assign values to an array of GPIOs
3717 * @array_size: number of elements in the descriptor array / value bitmap
3718 * @desc_array: array of GPIO descriptors whose values will be assigned
3719 * @array_info: information on applicability of fast bitmap processing path
3720 * @value_bitmap: bitmap of values to assign
3722 * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3725 * This function is to be called from contexts that can sleep.
3727 void gpiod_set_array_value_cansleep(unsigned int array_size,
3728 struct gpio_desc **desc_array,
3729 struct gpio_array *array_info,
3730 unsigned long *value_bitmap)
3732 might_sleep_if(extra_checks);
3735 gpiod_set_array_value_complex(false, true, array_size, desc_array,
3736 array_info, value_bitmap);
3738 EXPORT_SYMBOL_GPL(gpiod_set_array_value_cansleep);
3741 * gpiod_add_lookup_table() - register GPIO device consumers
3742 * @table: table of consumers to register
3744 void gpiod_add_lookup_table(struct gpiod_lookup_table *table)
3746 mutex_lock(&gpio_lookup_lock);
3748 list_add_tail(&table->list, &gpio_lookup_list);
3750 mutex_unlock(&gpio_lookup_lock);
3752 EXPORT_SYMBOL_GPL(gpiod_add_lookup_table);
3755 * gpiod_remove_lookup_table() - unregister GPIO device consumers
3756 * @table: table of consumers to unregister
3758 void gpiod_remove_lookup_table(struct gpiod_lookup_table *table)
3760 mutex_lock(&gpio_lookup_lock);
3762 list_del(&table->list);
3764 mutex_unlock(&gpio_lookup_lock);
3766 EXPORT_SYMBOL_GPL(gpiod_remove_lookup_table);
3769 * gpiod_add_hogs() - register a set of GPIO hogs from machine code
3770 * @hogs: table of gpio hog entries with a zeroed sentinel at the end
3772 void gpiod_add_hogs(struct gpiod_hog *hogs)
3774 struct gpio_chip *chip;
3775 struct gpiod_hog *hog;
3777 mutex_lock(&gpio_machine_hogs_mutex);
3779 for (hog = &hogs[0]; hog->chip_label; hog++) {
3780 list_add_tail(&hog->list, &gpio_machine_hogs);
3783 * The chip may have been registered earlier, so check if it
3784 * exists and, if so, try to hog the line now.
3786 chip = find_chip_by_name(hog->chip_label);
3788 gpiochip_machine_hog(chip, hog);
3791 mutex_unlock(&gpio_machine_hogs_mutex);
3793 EXPORT_SYMBOL_GPL(gpiod_add_hogs);
3795 static struct gpiod_lookup_table *gpiod_find_lookup_table(struct device *dev)
3797 const char *dev_id = dev ? dev_name(dev) : NULL;
3798 struct gpiod_lookup_table *table;
3800 mutex_lock(&gpio_lookup_lock);
3802 list_for_each_entry(table, &gpio_lookup_list, list) {
3803 if (table->dev_id && dev_id) {
3805 * Valid strings on both ends, must be identical to have
3808 if (!strcmp(table->dev_id, dev_id))
3812 * One of the pointers is NULL, so both must be to have
3815 if (dev_id == table->dev_id)
3822 mutex_unlock(&gpio_lookup_lock);
3826 static struct gpio_desc *gpiod_find(struct device *dev, const char *con_id,
3828 enum gpio_lookup_flags *flags)
3830 struct gpio_desc *desc = ERR_PTR(-ENOENT);
3831 struct gpiod_lookup_table *table;
3832 struct gpiod_lookup *p;
3834 table = gpiod_find_lookup_table(dev);
3838 for (p = &table->table[0]; p->chip_label; p++) {
3839 struct gpio_chip *chip;
3841 /* idx must always match exactly */
3845 /* If the lookup entry has a con_id, require exact match */
3846 if (p->con_id && (!con_id || strcmp(p->con_id, con_id)))
3849 chip = find_chip_by_name(p->chip_label);
3853 * As the lookup table indicates a chip with
3854 * p->chip_label should exist, assume it may
3855 * still appear later and let the interested
3856 * consumer be probed again or let the Deferred
3857 * Probe infrastructure handle the error.
3859 dev_warn(dev, "cannot find GPIO chip %s, deferring\n",
3861 return ERR_PTR(-EPROBE_DEFER);
3864 if (chip->ngpio <= p->chip_hwnum) {
3866 "requested GPIO %d is out of range [0..%d] for chip %s\n",
3867 idx, chip->ngpio, chip->label);
3868 return ERR_PTR(-EINVAL);
3871 desc = gpiochip_get_desc(chip, p->chip_hwnum);
3880 static int dt_gpio_count(struct device *dev, const char *con_id)
3886 for (i = 0; i < ARRAY_SIZE(gpio_suffixes); i++) {
3888 snprintf(propname, sizeof(propname), "%s-%s",
3889 con_id, gpio_suffixes[i]);
3891 snprintf(propname, sizeof(propname), "%s",
3894 ret = of_gpio_named_count(dev->of_node, propname);
3898 return ret ? ret : -ENOENT;
3901 static int platform_gpio_count(struct device *dev, const char *con_id)
3903 struct gpiod_lookup_table *table;
3904 struct gpiod_lookup *p;
3905 unsigned int count = 0;
3907 table = gpiod_find_lookup_table(dev);
3911 for (p = &table->table[0]; p->chip_label; p++) {
3912 if ((con_id && p->con_id && !strcmp(con_id, p->con_id)) ||
3913 (!con_id && !p->con_id))
3923 * gpiod_count - return the number of GPIOs associated with a device / function
3924 * or -ENOENT if no GPIO has been assigned to the requested function
3925 * @dev: GPIO consumer, can be NULL for system-global GPIOs
3926 * @con_id: function within the GPIO consumer
3928 int gpiod_count(struct device *dev, const char *con_id)
3930 int count = -ENOENT;
3932 if (IS_ENABLED(CONFIG_OF) && dev && dev->of_node)
3933 count = dt_gpio_count(dev, con_id);
3934 else if (IS_ENABLED(CONFIG_ACPI) && dev && ACPI_HANDLE(dev))
3935 count = acpi_gpio_count(dev, con_id);
3938 count = platform_gpio_count(dev, con_id);
3942 EXPORT_SYMBOL_GPL(gpiod_count);
3945 * gpiod_get - obtain a GPIO for a given GPIO function
3946 * @dev: GPIO consumer, can be NULL for system-global GPIOs
3947 * @con_id: function within the GPIO consumer
3948 * @flags: optional GPIO initialization flags
3950 * Return the GPIO descriptor corresponding to the function con_id of device
3951 * dev, -ENOENT if no GPIO has been assigned to the requested function, or
3952 * another IS_ERR() code if an error occurred while trying to acquire the GPIO.
3954 struct gpio_desc *__must_check gpiod_get(struct device *dev, const char *con_id,
3955 enum gpiod_flags flags)
3957 return gpiod_get_index(dev, con_id, 0, flags);
3959 EXPORT_SYMBOL_GPL(gpiod_get);
3962 * gpiod_get_optional - obtain an optional GPIO for a given GPIO function
3963 * @dev: GPIO consumer, can be NULL for system-global GPIOs
3964 * @con_id: function within the GPIO consumer
3965 * @flags: optional GPIO initialization flags
3967 * This is equivalent to gpiod_get(), except that when no GPIO was assigned to
3968 * the requested function it will return NULL. This is convenient for drivers
3969 * that need to handle optional GPIOs.
3971 struct gpio_desc *__must_check gpiod_get_optional(struct device *dev,
3973 enum gpiod_flags flags)
3975 return gpiod_get_index_optional(dev, con_id, 0, flags);
3977 EXPORT_SYMBOL_GPL(gpiod_get_optional);
3981 * gpiod_configure_flags - helper function to configure a given GPIO
3982 * @desc: gpio whose value will be assigned
3983 * @con_id: function within the GPIO consumer
3984 * @lflags: gpio_lookup_flags - returned from of_find_gpio() or
3986 * @dflags: gpiod_flags - optional GPIO initialization flags
3988 * Return 0 on success, -ENOENT if no GPIO has been assigned to the
3989 * requested function and/or index, or another IS_ERR() code if an error
3990 * occurred while trying to acquire the GPIO.
3992 int gpiod_configure_flags(struct gpio_desc *desc, const char *con_id,
3993 unsigned long lflags, enum gpiod_flags dflags)
3997 if (lflags & GPIO_ACTIVE_LOW)
3998 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
4000 if (lflags & GPIO_OPEN_DRAIN)
4001 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
4002 else if (dflags & GPIOD_FLAGS_BIT_OPEN_DRAIN) {
4004 * This enforces open drain mode from the consumer side.
4005 * This is necessary for some busses like I2C, but the lookup
4006 * should *REALLY* have specified them as open drain in the
4007 * first place, so print a little warning here.
4009 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
4011 "enforced open drain please flag it properly in DT/ACPI DSDT/board file\n");
4014 if (lflags & GPIO_OPEN_SOURCE)
4015 set_bit(FLAG_OPEN_SOURCE, &desc->flags);
4017 status = gpiod_set_transitory(desc, (lflags & GPIO_TRANSITORY));
4021 /* No particular flag request, return here... */
4022 if (!(dflags & GPIOD_FLAGS_BIT_DIR_SET)) {
4023 pr_debug("no flags found for %s\n", con_id);
4028 if (dflags & GPIOD_FLAGS_BIT_DIR_OUT)
4029 status = gpiod_direction_output(desc,
4030 !!(dflags & GPIOD_FLAGS_BIT_DIR_VAL));
4032 status = gpiod_direction_input(desc);
4038 * gpiod_get_index - obtain a GPIO from a multi-index GPIO function
4039 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4040 * @con_id: function within the GPIO consumer
4041 * @idx: index of the GPIO to obtain in the consumer
4042 * @flags: optional GPIO initialization flags
4044 * This variant of gpiod_get() allows to access GPIOs other than the first
4045 * defined one for functions that define several GPIOs.
4047 * Return a valid GPIO descriptor, -ENOENT if no GPIO has been assigned to the
4048 * requested function and/or index, or another IS_ERR() code if an error
4049 * occurred while trying to acquire the GPIO.
4051 struct gpio_desc *__must_check gpiod_get_index(struct device *dev,
4054 enum gpiod_flags flags)
4056 struct gpio_desc *desc = NULL;
4058 enum gpio_lookup_flags lookupflags = 0;
4059 /* Maybe we have a device name, maybe not */
4060 const char *devname = dev ? dev_name(dev) : "?";
4062 dev_dbg(dev, "GPIO lookup for consumer %s\n", con_id);
4065 /* Using device tree? */
4066 if (IS_ENABLED(CONFIG_OF) && dev->of_node) {
4067 dev_dbg(dev, "using device tree for GPIO lookup\n");
4068 desc = of_find_gpio(dev, con_id, idx, &lookupflags);
4069 } else if (ACPI_COMPANION(dev)) {
4070 dev_dbg(dev, "using ACPI for GPIO lookup\n");
4071 desc = acpi_find_gpio(dev, con_id, idx, &flags, &lookupflags);
4076 * Either we are not using DT or ACPI, or their lookup did not return
4077 * a result. In that case, use platform lookup as a fallback.
4079 if (!desc || desc == ERR_PTR(-ENOENT)) {
4080 dev_dbg(dev, "using lookup tables for GPIO lookup\n");
4081 desc = gpiod_find(dev, con_id, idx, &lookupflags);
4085 dev_dbg(dev, "No GPIO consumer %s found\n", con_id);
4090 * If a connection label was passed use that, else attempt to use
4091 * the device name as label
4093 status = gpiod_request(desc, con_id ? con_id : devname);
4095 return ERR_PTR(status);
4097 status = gpiod_configure_flags(desc, con_id, lookupflags, flags);
4099 dev_dbg(dev, "setup of GPIO %s failed\n", con_id);
4101 return ERR_PTR(status);
4106 EXPORT_SYMBOL_GPL(gpiod_get_index);
4109 * gpiod_get_from_of_node() - obtain a GPIO from an OF node
4110 * @node: handle of the OF node
4111 * @propname: name of the DT property representing the GPIO
4112 * @index: index of the GPIO to obtain for the consumer
4113 * @dflags: GPIO initialization flags
4114 * @label: label to attach to the requested GPIO
4117 * On successful request the GPIO pin is configured in accordance with
4118 * provided @dflags. If the node does not have the requested GPIO
4119 * property, NULL is returned.
4121 * In case of error an ERR_PTR() is returned.
4123 struct gpio_desc *gpiod_get_from_of_node(struct device_node *node,
4124 const char *propname, int index,
4125 enum gpiod_flags dflags,
4128 struct gpio_desc *desc;
4129 unsigned long lflags = 0;
4130 enum of_gpio_flags flags;
4131 bool active_low = false;
4132 bool single_ended = false;
4133 bool open_drain = false;
4134 bool transitory = false;
4137 desc = of_get_named_gpiod_flags(node, propname,
4140 if (!desc || IS_ERR(desc)) {
4141 /* If it is not there, just return NULL */
4142 if (PTR_ERR(desc) == -ENOENT)
4147 active_low = flags & OF_GPIO_ACTIVE_LOW;
4148 single_ended = flags & OF_GPIO_SINGLE_ENDED;
4149 open_drain = flags & OF_GPIO_OPEN_DRAIN;
4150 transitory = flags & OF_GPIO_TRANSITORY;
4152 ret = gpiod_request(desc, label);
4154 return ERR_PTR(ret);
4157 lflags |= GPIO_ACTIVE_LOW;
4161 lflags |= GPIO_OPEN_DRAIN;
4163 lflags |= GPIO_OPEN_SOURCE;
4167 lflags |= GPIO_TRANSITORY;
4169 ret = gpiod_configure_flags(desc, propname, lflags, dflags);
4172 return ERR_PTR(ret);
4177 EXPORT_SYMBOL(gpiod_get_from_of_node);
4180 * fwnode_get_named_gpiod - obtain a GPIO from firmware node
4181 * @fwnode: handle of the firmware node
4182 * @propname: name of the firmware property representing the GPIO
4183 * @index: index of the GPIO to obtain for the consumer
4184 * @dflags: GPIO initialization flags
4185 * @label: label to attach to the requested GPIO
4187 * This function can be used for drivers that get their configuration
4188 * from opaque firmware.
4190 * The function properly finds the corresponding GPIO using whatever is the
4191 * underlying firmware interface and then makes sure that the GPIO
4192 * descriptor is requested before it is returned to the caller.
4195 * On successful request the GPIO pin is configured in accordance with
4198 * In case of error an ERR_PTR() is returned.
4200 struct gpio_desc *fwnode_get_named_gpiod(struct fwnode_handle *fwnode,
4201 const char *propname, int index,
4202 enum gpiod_flags dflags,
4205 struct gpio_desc *desc = ERR_PTR(-ENODEV);
4206 unsigned long lflags = 0;
4210 return ERR_PTR(-EINVAL);
4212 if (is_of_node(fwnode)) {
4213 desc = gpiod_get_from_of_node(to_of_node(fwnode),
4218 } else if (is_acpi_node(fwnode)) {
4219 struct acpi_gpio_info info;
4221 desc = acpi_node_get_gpiod(fwnode, propname, index, &info);
4225 acpi_gpio_update_gpiod_flags(&dflags, &info);
4227 if (info.polarity == GPIO_ACTIVE_LOW)
4228 lflags |= GPIO_ACTIVE_LOW;
4231 /* Currently only ACPI takes this path */
4232 ret = gpiod_request(desc, label);
4234 return ERR_PTR(ret);
4236 ret = gpiod_configure_flags(desc, propname, lflags, dflags);
4239 return ERR_PTR(ret);
4244 EXPORT_SYMBOL_GPL(fwnode_get_named_gpiod);
4247 * gpiod_get_index_optional - obtain an optional GPIO from a multi-index GPIO
4249 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4250 * @con_id: function within the GPIO consumer
4251 * @index: index of the GPIO to obtain in the consumer
4252 * @flags: optional GPIO initialization flags
4254 * This is equivalent to gpiod_get_index(), except that when no GPIO with the
4255 * specified index was assigned to the requested function it will return NULL.
4256 * This is convenient for drivers that need to handle optional GPIOs.
4258 struct gpio_desc *__must_check gpiod_get_index_optional(struct device *dev,
4261 enum gpiod_flags flags)
4263 struct gpio_desc *desc;
4265 desc = gpiod_get_index(dev, con_id, index, flags);
4267 if (PTR_ERR(desc) == -ENOENT)
4273 EXPORT_SYMBOL_GPL(gpiod_get_index_optional);
4276 * gpiod_hog - Hog the specified GPIO desc given the provided flags
4277 * @desc: gpio whose value will be assigned
4278 * @name: gpio line name
4279 * @lflags: gpio_lookup_flags - returned from of_find_gpio() or
4281 * @dflags: gpiod_flags - optional GPIO initialization flags
4283 int gpiod_hog(struct gpio_desc *desc, const char *name,
4284 unsigned long lflags, enum gpiod_flags dflags)
4286 struct gpio_chip *chip;
4287 struct gpio_desc *local_desc;
4291 chip = gpiod_to_chip(desc);
4292 hwnum = gpio_chip_hwgpio(desc);
4294 local_desc = gpiochip_request_own_desc(chip, hwnum, name);
4295 if (IS_ERR(local_desc)) {
4296 status = PTR_ERR(local_desc);
4297 pr_err("requesting hog GPIO %s (chip %s, offset %d) failed, %d\n",
4298 name, chip->label, hwnum, status);
4302 status = gpiod_configure_flags(desc, name, lflags, dflags);
4304 pr_err("setup of hog GPIO %s (chip %s, offset %d) failed, %d\n",
4305 name, chip->label, hwnum, status);
4306 gpiochip_free_own_desc(desc);
4310 /* Mark GPIO as hogged so it can be identified and removed later */
4311 set_bit(FLAG_IS_HOGGED, &desc->flags);
4313 pr_info("GPIO line %d (%s) hogged as %s%s\n",
4314 desc_to_gpio(desc), name,
4315 (dflags&GPIOD_FLAGS_BIT_DIR_OUT) ? "output" : "input",
4316 (dflags&GPIOD_FLAGS_BIT_DIR_OUT) ?
4317 (dflags&GPIOD_FLAGS_BIT_DIR_VAL) ? "/high" : "/low":"");
4323 * gpiochip_free_hogs - Scan gpio-controller chip and release GPIO hog
4324 * @chip: gpio chip to act on
4326 * This is only used by of_gpiochip_remove to free hogged gpios
4328 static void gpiochip_free_hogs(struct gpio_chip *chip)
4332 for (id = 0; id < chip->ngpio; id++) {
4333 if (test_bit(FLAG_IS_HOGGED, &chip->gpiodev->descs[id].flags))
4334 gpiochip_free_own_desc(&chip->gpiodev->descs[id]);
4339 * gpiod_get_array - obtain multiple GPIOs from a multi-index GPIO function
4340 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4341 * @con_id: function within the GPIO consumer
4342 * @flags: optional GPIO initialization flags
4344 * This function acquires all the GPIOs defined under a given function.
4346 * Return a struct gpio_descs containing an array of descriptors, -ENOENT if
4347 * no GPIO has been assigned to the requested function, or another IS_ERR()
4348 * code if an error occurred while trying to acquire the GPIOs.
4350 struct gpio_descs *__must_check gpiod_get_array(struct device *dev,
4352 enum gpiod_flags flags)
4354 struct gpio_desc *desc;
4355 struct gpio_descs *descs;
4356 struct gpio_array *array_info = NULL;
4357 struct gpio_chip *chip;
4358 int count, bitmap_size;
4360 count = gpiod_count(dev, con_id);
4362 return ERR_PTR(count);
4364 descs = kzalloc(struct_size(descs, desc, count), GFP_KERNEL);
4366 return ERR_PTR(-ENOMEM);
4368 for (descs->ndescs = 0; descs->ndescs < count; ) {
4369 desc = gpiod_get_index(dev, con_id, descs->ndescs, flags);
4371 gpiod_put_array(descs);
4372 return ERR_CAST(desc);
4375 descs->desc[descs->ndescs] = desc;
4377 chip = gpiod_to_chip(desc);
4379 * Select a chip of first array member
4380 * whose index matches its pin hardware number
4381 * as a candidate for fast bitmap processing.
4383 if (!array_info && gpio_chip_hwgpio(desc) == descs->ndescs) {
4384 struct gpio_descs *array;
4386 bitmap_size = BITS_TO_LONGS(chip->ngpio > count ?
4387 chip->ngpio : count);
4389 array = kzalloc(struct_size(descs, desc, count) +
4390 struct_size(array_info, invert_mask,
4391 3 * bitmap_size), GFP_KERNEL);
4393 gpiod_put_array(descs);
4394 return ERR_PTR(-ENOMEM);
4397 memcpy(array, descs,
4398 struct_size(descs, desc, descs->ndescs + 1));
4402 array_info = (void *)(descs->desc + count);
4403 array_info->get_mask = array_info->invert_mask +
4405 array_info->set_mask = array_info->get_mask +
4408 array_info->desc = descs->desc;
4409 array_info->size = count;
4410 array_info->chip = chip;
4411 bitmap_set(array_info->get_mask, descs->ndescs,
4412 count - descs->ndescs);
4413 bitmap_set(array_info->set_mask, descs->ndescs,
4414 count - descs->ndescs);
4415 descs->info = array_info;
4418 * Unmark members which don't qualify for fast bitmap
4419 * processing (different chip, not in hardware order)
4421 if (array_info && (chip != array_info->chip ||
4422 gpio_chip_hwgpio(desc) != descs->ndescs)) {
4423 __clear_bit(descs->ndescs, array_info->get_mask);
4424 __clear_bit(descs->ndescs, array_info->set_mask);
4425 } else if (array_info) {
4426 /* Exclude open drain or open source from fast output */
4427 if (gpiochip_line_is_open_drain(chip, descs->ndescs) ||
4428 gpiochip_line_is_open_source(chip, descs->ndescs))
4429 __clear_bit(descs->ndescs,
4430 array_info->set_mask);
4431 /* Identify 'fast' pins which require invertion */
4432 if (gpiod_is_active_low(desc))
4433 __set_bit(descs->ndescs,
4434 array_info->invert_mask);
4441 "GPIO array info: chip=%s, size=%d, get_mask=%lx, set_mask=%lx, invert_mask=%lx\n",
4442 array_info->chip->label, array_info->size,
4443 *array_info->get_mask, *array_info->set_mask,
4444 *array_info->invert_mask);
4447 EXPORT_SYMBOL_GPL(gpiod_get_array);
4450 * gpiod_get_array_optional - obtain multiple GPIOs from a multi-index GPIO
4452 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4453 * @con_id: function within the GPIO consumer
4454 * @flags: optional GPIO initialization flags
4456 * This is equivalent to gpiod_get_array(), except that when no GPIO was
4457 * assigned to the requested function it will return NULL.
4459 struct gpio_descs *__must_check gpiod_get_array_optional(struct device *dev,
4461 enum gpiod_flags flags)
4463 struct gpio_descs *descs;
4465 descs = gpiod_get_array(dev, con_id, flags);
4466 if (IS_ERR(descs) && (PTR_ERR(descs) == -ENOENT))
4471 EXPORT_SYMBOL_GPL(gpiod_get_array_optional);
4474 * gpiod_put - dispose of a GPIO descriptor
4475 * @desc: GPIO descriptor to dispose of
4477 * No descriptor can be used after gpiod_put() has been called on it.
4479 void gpiod_put(struct gpio_desc *desc)
4483 EXPORT_SYMBOL_GPL(gpiod_put);
4486 * gpiod_put_array - dispose of multiple GPIO descriptors
4487 * @descs: struct gpio_descs containing an array of descriptors
4489 void gpiod_put_array(struct gpio_descs *descs)
4493 for (i = 0; i < descs->ndescs; i++)
4494 gpiod_put(descs->desc[i]);
4498 EXPORT_SYMBOL_GPL(gpiod_put_array);
4500 static int __init gpiolib_dev_init(void)
4504 /* Register GPIO sysfs bus */
4505 ret = bus_register(&gpio_bus_type);
4507 pr_err("gpiolib: could not register GPIO bus type\n");
4511 ret = alloc_chrdev_region(&gpio_devt, 0, GPIO_DEV_MAX, "gpiochip");
4513 pr_err("gpiolib: failed to allocate char dev region\n");
4514 bus_unregister(&gpio_bus_type);
4516 gpiolib_initialized = true;
4517 gpiochip_setup_devs();
4521 core_initcall(gpiolib_dev_init);
4523 #ifdef CONFIG_DEBUG_FS
4525 static void gpiolib_dbg_show(struct seq_file *s, struct gpio_device *gdev)
4528 struct gpio_chip *chip = gdev->chip;
4529 unsigned gpio = gdev->base;
4530 struct gpio_desc *gdesc = &gdev->descs[0];
4534 for (i = 0; i < gdev->ngpio; i++, gpio++, gdesc++) {
4535 if (!test_bit(FLAG_REQUESTED, &gdesc->flags)) {
4537 seq_printf(s, " gpio-%-3d (%-20.20s)\n",
4543 gpiod_get_direction(gdesc);
4544 is_out = test_bit(FLAG_IS_OUT, &gdesc->flags);
4545 is_irq = test_bit(FLAG_USED_AS_IRQ, &gdesc->flags);
4546 seq_printf(s, " gpio-%-3d (%-20.20s|%-20.20s) %s %s %s",
4547 gpio, gdesc->name ? gdesc->name : "", gdesc->label,
4548 is_out ? "out" : "in ",
4549 chip->get ? (chip->get(chip, i) ? "hi" : "lo") : "? ",
4550 is_irq ? "IRQ" : " ");
4551 seq_printf(s, "\n");
4555 static void *gpiolib_seq_start(struct seq_file *s, loff_t *pos)
4557 unsigned long flags;
4558 struct gpio_device *gdev = NULL;
4559 loff_t index = *pos;
4563 spin_lock_irqsave(&gpio_lock, flags);
4564 list_for_each_entry(gdev, &gpio_devices, list)
4566 spin_unlock_irqrestore(&gpio_lock, flags);
4569 spin_unlock_irqrestore(&gpio_lock, flags);
4574 static void *gpiolib_seq_next(struct seq_file *s, void *v, loff_t *pos)
4576 unsigned long flags;
4577 struct gpio_device *gdev = v;
4580 spin_lock_irqsave(&gpio_lock, flags);
4581 if (list_is_last(&gdev->list, &gpio_devices))
4584 ret = list_entry(gdev->list.next, struct gpio_device, list);
4585 spin_unlock_irqrestore(&gpio_lock, flags);
4593 static void gpiolib_seq_stop(struct seq_file *s, void *v)
4597 static int gpiolib_seq_show(struct seq_file *s, void *v)
4599 struct gpio_device *gdev = v;
4600 struct gpio_chip *chip = gdev->chip;
4601 struct device *parent;
4604 seq_printf(s, "%s%s: (dangling chip)", (char *)s->private,
4605 dev_name(&gdev->dev));
4609 seq_printf(s, "%s%s: GPIOs %d-%d", (char *)s->private,
4610 dev_name(&gdev->dev),
4611 gdev->base, gdev->base + gdev->ngpio - 1);
4612 parent = chip->parent;
4614 seq_printf(s, ", parent: %s/%s",
4615 parent->bus ? parent->bus->name : "no-bus",
4618 seq_printf(s, ", %s", chip->label);
4619 if (chip->can_sleep)
4620 seq_printf(s, ", can sleep");
4621 seq_printf(s, ":\n");
4624 chip->dbg_show(s, chip);
4626 gpiolib_dbg_show(s, gdev);
4631 static const struct seq_operations gpiolib_seq_ops = {
4632 .start = gpiolib_seq_start,
4633 .next = gpiolib_seq_next,
4634 .stop = gpiolib_seq_stop,
4635 .show = gpiolib_seq_show,
4638 static int gpiolib_open(struct inode *inode, struct file *file)
4640 return seq_open(file, &gpiolib_seq_ops);
4643 static const struct file_operations gpiolib_operations = {
4644 .owner = THIS_MODULE,
4645 .open = gpiolib_open,
4647 .llseek = seq_lseek,
4648 .release = seq_release,
4651 static int __init gpiolib_debugfs_init(void)
4653 /* /sys/kernel/debug/gpio */
4654 (void) debugfs_create_file("gpio", S_IFREG | S_IRUGO,
4655 NULL, NULL, &gpiolib_operations);
4658 subsys_initcall(gpiolib_debugfs_init);
4660 #endif /* DEBUG_FS */