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 = {
64 /* gpio_lock prevents conflicts during gpio_desc[] table updates.
65 * While any GPIO is requested, its gpio_chip is not removable;
66 * each GPIO's "requested" flag serves as a lock and refcount.
68 DEFINE_SPINLOCK(gpio_lock);
70 static DEFINE_MUTEX(gpio_lookup_lock);
71 static LIST_HEAD(gpio_lookup_list);
72 LIST_HEAD(gpio_devices);
74 static void gpiochip_free_hogs(struct gpio_chip *chip);
75 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip);
76 static int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gpiochip);
77 static void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gpiochip);
79 static bool gpiolib_initialized;
81 static inline void desc_set_label(struct gpio_desc *d, const char *label)
87 * gpio_to_desc - Convert a GPIO number to its descriptor
88 * @gpio: global GPIO number
91 * The GPIO descriptor associated with the given GPIO, or %NULL if no GPIO
92 * with the given number exists in the system.
94 struct gpio_desc *gpio_to_desc(unsigned gpio)
96 struct gpio_device *gdev;
99 spin_lock_irqsave(&gpio_lock, flags);
101 list_for_each_entry(gdev, &gpio_devices, list) {
102 if (gdev->base <= gpio &&
103 gdev->base + gdev->ngpio > gpio) {
104 spin_unlock_irqrestore(&gpio_lock, flags);
105 return &gdev->descs[gpio - gdev->base];
109 spin_unlock_irqrestore(&gpio_lock, flags);
111 if (!gpio_is_valid(gpio))
112 WARN(1, "invalid GPIO %d\n", gpio);
116 EXPORT_SYMBOL_GPL(gpio_to_desc);
119 * gpiochip_get_desc - get the GPIO descriptor corresponding to the given
120 * hardware number for this chip
122 * @hwnum: hardware number of the GPIO for this chip
125 * A pointer to the GPIO descriptor or %ERR_PTR(-EINVAL) if no GPIO exists
126 * in the given chip for the specified hardware number.
128 struct gpio_desc *gpiochip_get_desc(struct gpio_chip *chip,
131 struct gpio_device *gdev = chip->gpiodev;
133 if (hwnum >= gdev->ngpio)
134 return ERR_PTR(-EINVAL);
136 return &gdev->descs[hwnum];
140 * desc_to_gpio - convert a GPIO descriptor to the integer namespace
141 * @desc: GPIO descriptor
143 * This should disappear in the future but is needed since we still
144 * use GPIO numbers for error messages and sysfs nodes.
147 * The global GPIO number for the GPIO specified by its descriptor.
149 int desc_to_gpio(const struct gpio_desc *desc)
151 return desc->gdev->base + (desc - &desc->gdev->descs[0]);
153 EXPORT_SYMBOL_GPL(desc_to_gpio);
157 * gpiod_to_chip - Return the GPIO chip to which a GPIO descriptor belongs
158 * @desc: descriptor to return the chip of
160 struct gpio_chip *gpiod_to_chip(const struct gpio_desc *desc)
162 if (!desc || !desc->gdev || !desc->gdev->chip)
164 return desc->gdev->chip;
166 EXPORT_SYMBOL_GPL(gpiod_to_chip);
168 /* dynamic allocation of GPIOs, e.g. on a hotplugged device */
169 static int gpiochip_find_base(int ngpio)
171 struct gpio_device *gdev;
172 int base = ARCH_NR_GPIOS - ngpio;
174 list_for_each_entry_reverse(gdev, &gpio_devices, list) {
175 /* found a free space? */
176 if (gdev->base + gdev->ngpio <= base)
179 /* nope, check the space right before the chip */
180 base = gdev->base - ngpio;
183 if (gpio_is_valid(base)) {
184 pr_debug("%s: found new base at %d\n", __func__, base);
187 pr_err("%s: cannot find free range\n", __func__);
193 * gpiod_get_direction - return the current direction of a GPIO
194 * @desc: GPIO to get the direction of
196 * Return GPIOF_DIR_IN or GPIOF_DIR_OUT, or an error code in case of error.
198 * This function may sleep if gpiod_cansleep() is true.
200 int gpiod_get_direction(struct gpio_desc *desc)
202 struct gpio_chip *chip;
204 int status = -EINVAL;
206 chip = gpiod_to_chip(desc);
207 offset = gpio_chip_hwgpio(desc);
210 * Open drain emulation using input mode may incorrectly report
211 * input here, fix that up.
213 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags) &&
214 test_bit(FLAG_IS_OUT, &desc->flags))
217 if (!chip->get_direction)
220 status = chip->get_direction(chip, offset);
222 /* GPIOF_DIR_IN, or other positive */
224 clear_bit(FLAG_IS_OUT, &desc->flags);
228 set_bit(FLAG_IS_OUT, &desc->flags);
232 EXPORT_SYMBOL_GPL(gpiod_get_direction);
235 * Add a new chip to the global chips list, keeping the list of chips sorted
236 * by range(means [base, base + ngpio - 1]) order.
238 * Return -EBUSY if the new chip overlaps with some other chip's integer
241 static int gpiodev_add_to_list(struct gpio_device *gdev)
243 struct gpio_device *prev, *next;
245 if (list_empty(&gpio_devices)) {
246 /* initial entry in list */
247 list_add_tail(&gdev->list, &gpio_devices);
251 next = list_entry(gpio_devices.next, struct gpio_device, list);
252 if (gdev->base + gdev->ngpio <= next->base) {
253 /* add before first entry */
254 list_add(&gdev->list, &gpio_devices);
258 prev = list_entry(gpio_devices.prev, struct gpio_device, list);
259 if (prev->base + prev->ngpio <= gdev->base) {
260 /* add behind last entry */
261 list_add_tail(&gdev->list, &gpio_devices);
265 list_for_each_entry_safe(prev, next, &gpio_devices, list) {
266 /* at the end of the list */
267 if (&next->list == &gpio_devices)
270 /* add between prev and next */
271 if (prev->base + prev->ngpio <= gdev->base
272 && gdev->base + gdev->ngpio <= next->base) {
273 list_add(&gdev->list, &prev->list);
278 dev_err(&gdev->dev, "GPIO integer space overlap, cannot add chip\n");
283 * Convert a GPIO name to its descriptor
285 static struct gpio_desc *gpio_name_to_desc(const char * const name)
287 struct gpio_device *gdev;
290 spin_lock_irqsave(&gpio_lock, flags);
292 list_for_each_entry(gdev, &gpio_devices, list) {
295 for (i = 0; i != gdev->ngpio; ++i) {
296 struct gpio_desc *desc = &gdev->descs[i];
298 if (!desc->name || !name)
301 if (!strcmp(desc->name, name)) {
302 spin_unlock_irqrestore(&gpio_lock, flags);
308 spin_unlock_irqrestore(&gpio_lock, flags);
314 * Takes the names from gc->names and checks if they are all unique. If they
315 * are, they are assigned to their gpio descriptors.
317 * Warning if one of the names is already used for a different GPIO.
319 static int gpiochip_set_desc_names(struct gpio_chip *gc)
321 struct gpio_device *gdev = gc->gpiodev;
327 /* First check all names if they are unique */
328 for (i = 0; i != gc->ngpio; ++i) {
329 struct gpio_desc *gpio;
331 gpio = gpio_name_to_desc(gc->names[i]);
334 "Detected name collision for GPIO name '%s'\n",
338 /* Then add all names to the GPIO descriptors */
339 for (i = 0; i != gc->ngpio; ++i)
340 gdev->descs[i].name = gc->names[i];
346 * GPIO line handle management
350 * struct linehandle_state - contains the state of a userspace handle
351 * @gdev: the GPIO device the handle pertains to
352 * @label: consumer label used to tag descriptors
353 * @descs: the GPIO descriptors held by this handle
354 * @numdescs: the number of descriptors held in the descs array
356 struct linehandle_state {
357 struct gpio_device *gdev;
359 struct gpio_desc *descs[GPIOHANDLES_MAX];
363 #define GPIOHANDLE_REQUEST_VALID_FLAGS \
364 (GPIOHANDLE_REQUEST_INPUT | \
365 GPIOHANDLE_REQUEST_OUTPUT | \
366 GPIOHANDLE_REQUEST_ACTIVE_LOW | \
367 GPIOHANDLE_REQUEST_OPEN_DRAIN | \
368 GPIOHANDLE_REQUEST_OPEN_SOURCE)
370 static long linehandle_ioctl(struct file *filep, unsigned int cmd,
373 struct linehandle_state *lh = filep->private_data;
374 void __user *ip = (void __user *)arg;
375 struct gpiohandle_data ghd;
378 if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
381 memset(&ghd, 0, sizeof(ghd));
383 /* TODO: check if descriptors are really input */
384 for (i = 0; i < lh->numdescs; i++) {
385 val = gpiod_get_value_cansleep(lh->descs[i]);
391 if (copy_to_user(ip, &ghd, sizeof(ghd)))
395 } else if (cmd == GPIOHANDLE_SET_LINE_VALUES_IOCTL) {
396 int vals[GPIOHANDLES_MAX];
398 /* TODO: check if descriptors are really output */
399 if (copy_from_user(&ghd, ip, sizeof(ghd)))
402 /* Clamp all values to [0,1] */
403 for (i = 0; i < lh->numdescs; i++)
404 vals[i] = !!ghd.values[i];
406 /* Reuse the array setting function */
407 gpiod_set_array_value_complex(false,
418 static long linehandle_ioctl_compat(struct file *filep, unsigned int cmd,
421 return linehandle_ioctl(filep, cmd, (unsigned long)compat_ptr(arg));
425 static int linehandle_release(struct inode *inode, struct file *filep)
427 struct linehandle_state *lh = filep->private_data;
428 struct gpio_device *gdev = lh->gdev;
431 for (i = 0; i < lh->numdescs; i++)
432 gpiod_free(lh->descs[i]);
435 put_device(&gdev->dev);
439 static const struct file_operations linehandle_fileops = {
440 .release = linehandle_release,
441 .owner = THIS_MODULE,
442 .llseek = noop_llseek,
443 .unlocked_ioctl = linehandle_ioctl,
445 .compat_ioctl = linehandle_ioctl_compat,
449 static int linehandle_create(struct gpio_device *gdev, void __user *ip)
451 struct gpiohandle_request handlereq;
452 struct linehandle_state *lh;
454 int fd, i, count = 0, ret;
457 if (copy_from_user(&handlereq, ip, sizeof(handlereq)))
459 if ((handlereq.lines == 0) || (handlereq.lines > GPIOHANDLES_MAX))
462 lflags = handlereq.flags;
465 * Do not allow both INPUT & OUTPUT flags to be set as they are
468 if ((lflags & GPIOHANDLE_REQUEST_INPUT) &&
469 (lflags & GPIOHANDLE_REQUEST_OUTPUT))
472 lh = kzalloc(sizeof(*lh), GFP_KERNEL);
476 get_device(&gdev->dev);
478 /* Make sure this is terminated */
479 handlereq.consumer_label[sizeof(handlereq.consumer_label)-1] = '\0';
480 if (strlen(handlereq.consumer_label)) {
481 lh->label = kstrdup(handlereq.consumer_label,
489 /* Request each GPIO */
490 for (i = 0; i < handlereq.lines; i++) {
491 u32 offset = handlereq.lineoffsets[i];
492 struct gpio_desc *desc;
494 if (offset >= gdev->ngpio) {
499 /* Return an error if a unknown flag is set */
500 if (lflags & ~GPIOHANDLE_REQUEST_VALID_FLAGS) {
505 desc = &gdev->descs[offset];
506 ret = gpiod_request(desc, lh->label);
512 if (lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW)
513 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
514 if (lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN)
515 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
516 if (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE)
517 set_bit(FLAG_OPEN_SOURCE, &desc->flags);
520 * Lines have to be requested explicitly for input
521 * or output, else the line will be treated "as is".
523 if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
524 int val = !!handlereq.default_values[i];
526 ret = gpiod_direction_output(desc, val);
529 } else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
530 ret = gpiod_direction_input(desc);
534 dev_dbg(&gdev->dev, "registered chardev handle for line %d\n",
537 /* Let i point at the last handle */
539 lh->numdescs = handlereq.lines;
541 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
547 file = anon_inode_getfile("gpio-linehandle",
550 O_RDONLY | O_CLOEXEC);
553 goto out_put_unused_fd;
557 if (copy_to_user(ip, &handlereq, sizeof(handlereq))) {
559 * fput() will trigger the release() callback, so do not go onto
560 * the regular error cleanup path here.
567 fd_install(fd, file);
569 dev_dbg(&gdev->dev, "registered chardev handle for %d lines\n",
577 for (i = 0; i < count; i++)
578 gpiod_free(lh->descs[i]);
582 put_device(&gdev->dev);
587 * GPIO line event management
591 * struct lineevent_state - contains the state of a userspace event
592 * @gdev: the GPIO device the event pertains to
593 * @label: consumer label used to tag descriptors
594 * @desc: the GPIO descriptor held by this event
595 * @eflags: the event flags this line was requested with
596 * @irq: the interrupt that trigger in response to events on this GPIO
597 * @wait: wait queue that handles blocking reads of events
598 * @events: KFIFO for the GPIO events
599 * @read_lock: mutex lock to protect reads from colliding with adding
600 * new events to the FIFO
602 struct lineevent_state {
603 struct gpio_device *gdev;
605 struct gpio_desc *desc;
608 wait_queue_head_t wait;
609 DECLARE_KFIFO(events, struct gpioevent_data, 16);
610 struct mutex read_lock;
613 #define GPIOEVENT_REQUEST_VALID_FLAGS \
614 (GPIOEVENT_REQUEST_RISING_EDGE | \
615 GPIOEVENT_REQUEST_FALLING_EDGE)
617 static unsigned int lineevent_poll(struct file *filep,
618 struct poll_table_struct *wait)
620 struct lineevent_state *le = filep->private_data;
621 unsigned int events = 0;
623 poll_wait(filep, &le->wait, wait);
625 if (!kfifo_is_empty(&le->events))
626 events = POLLIN | POLLRDNORM;
632 static ssize_t lineevent_read(struct file *filep,
637 struct lineevent_state *le = filep->private_data;
641 if (count < sizeof(struct gpioevent_data))
645 if (kfifo_is_empty(&le->events)) {
646 if (filep->f_flags & O_NONBLOCK)
649 ret = wait_event_interruptible(le->wait,
650 !kfifo_is_empty(&le->events));
655 if (mutex_lock_interruptible(&le->read_lock))
657 ret = kfifo_to_user(&le->events, buf, count, &copied);
658 mutex_unlock(&le->read_lock);
664 * If we couldn't read anything from the fifo (a different
665 * thread might have been faster) we either return -EAGAIN if
666 * the file descriptor is non-blocking, otherwise we go back to
667 * sleep and wait for more data to arrive.
669 if (copied == 0 && (filep->f_flags & O_NONBLOCK))
672 } while (copied == 0);
677 static int lineevent_release(struct inode *inode, struct file *filep)
679 struct lineevent_state *le = filep->private_data;
680 struct gpio_device *gdev = le->gdev;
682 free_irq(le->irq, le);
683 gpiod_free(le->desc);
686 put_device(&gdev->dev);
690 static long lineevent_ioctl(struct file *filep, unsigned int cmd,
693 struct lineevent_state *le = filep->private_data;
694 void __user *ip = (void __user *)arg;
695 struct gpiohandle_data ghd;
698 * We can get the value for an event line but not set it,
699 * because it is input by definition.
701 if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
704 memset(&ghd, 0, sizeof(ghd));
706 val = gpiod_get_value_cansleep(le->desc);
711 if (copy_to_user(ip, &ghd, sizeof(ghd)))
720 static long lineevent_ioctl_compat(struct file *filep, unsigned int cmd,
723 return lineevent_ioctl(filep, cmd, (unsigned long)compat_ptr(arg));
727 static const struct file_operations lineevent_fileops = {
728 .release = lineevent_release,
729 .read = lineevent_read,
730 .poll = lineevent_poll,
731 .owner = THIS_MODULE,
732 .llseek = noop_llseek,
733 .unlocked_ioctl = lineevent_ioctl,
735 .compat_ioctl = lineevent_ioctl_compat,
739 static irqreturn_t lineevent_irq_thread(int irq, void *p)
741 struct lineevent_state *le = p;
742 struct gpioevent_data ge;
745 /* Do not leak kernel stack to userspace */
746 memset(&ge, 0, sizeof(ge));
748 ge.timestamp = ktime_get_real_ns();
749 level = gpiod_get_value_cansleep(le->desc);
751 if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE
752 && le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
754 /* Emit low-to-high event */
755 ge.id = GPIOEVENT_EVENT_RISING_EDGE;
757 /* Emit high-to-low event */
758 ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
759 } else if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE && level) {
760 /* Emit low-to-high event */
761 ge.id = GPIOEVENT_EVENT_RISING_EDGE;
762 } else if (le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE && !level) {
763 /* Emit high-to-low event */
764 ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
769 ret = kfifo_put(&le->events, ge);
771 wake_up_poll(&le->wait, POLLIN);
776 static int lineevent_create(struct gpio_device *gdev, void __user *ip)
778 struct gpioevent_request eventreq;
779 struct lineevent_state *le;
780 struct gpio_desc *desc;
789 if (copy_from_user(&eventreq, ip, sizeof(eventreq)))
792 le = kzalloc(sizeof(*le), GFP_KERNEL);
796 get_device(&gdev->dev);
798 /* Make sure this is terminated */
799 eventreq.consumer_label[sizeof(eventreq.consumer_label)-1] = '\0';
800 if (strlen(eventreq.consumer_label)) {
801 le->label = kstrdup(eventreq.consumer_label,
809 offset = eventreq.lineoffset;
810 lflags = eventreq.handleflags;
811 eflags = eventreq.eventflags;
813 if (offset >= gdev->ngpio) {
818 /* Return an error if a unknown flag is set */
819 if ((lflags & ~GPIOHANDLE_REQUEST_VALID_FLAGS) ||
820 (eflags & ~GPIOEVENT_REQUEST_VALID_FLAGS)) {
825 /* This is just wrong: we don't look for events on output lines */
826 if ((lflags & GPIOHANDLE_REQUEST_OUTPUT) ||
827 (lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN) ||
828 (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE)) {
833 desc = &gdev->descs[offset];
834 ret = gpiod_request(desc, le->label);
840 if (lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW)
841 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
843 ret = gpiod_direction_input(desc);
847 le->irq = gpiod_to_irq(desc);
853 if (eflags & GPIOEVENT_REQUEST_RISING_EDGE)
854 irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
855 IRQF_TRIGGER_FALLING : IRQF_TRIGGER_RISING;
856 if (eflags & GPIOEVENT_REQUEST_FALLING_EDGE)
857 irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
858 IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING;
859 irqflags |= IRQF_ONESHOT;
860 irqflags |= IRQF_SHARED;
862 INIT_KFIFO(le->events);
863 init_waitqueue_head(&le->wait);
864 mutex_init(&le->read_lock);
866 /* Request a thread to read the events */
867 ret = request_threaded_irq(le->irq,
869 lineevent_irq_thread,
876 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
882 file = anon_inode_getfile("gpio-event",
885 O_RDONLY | O_CLOEXEC);
888 goto out_put_unused_fd;
892 if (copy_to_user(ip, &eventreq, sizeof(eventreq))) {
894 * fput() will trigger the release() callback, so do not go onto
895 * the regular error cleanup path here.
902 fd_install(fd, file);
909 free_irq(le->irq, le);
911 gpiod_free(le->desc);
916 put_device(&gdev->dev);
921 * gpio_ioctl() - ioctl handler for the GPIO chardev
923 static long gpio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
925 struct gpio_device *gdev = filp->private_data;
926 struct gpio_chip *chip = gdev->chip;
927 void __user *ip = (void __user *)arg;
929 /* We fail any subsequent ioctl():s when the chip is gone */
933 /* Fill in the struct and pass to userspace */
934 if (cmd == GPIO_GET_CHIPINFO_IOCTL) {
935 struct gpiochip_info chipinfo;
937 memset(&chipinfo, 0, sizeof(chipinfo));
939 strncpy(chipinfo.name, dev_name(&gdev->dev),
940 sizeof(chipinfo.name));
941 chipinfo.name[sizeof(chipinfo.name)-1] = '\0';
942 strncpy(chipinfo.label, gdev->label,
943 sizeof(chipinfo.label));
944 chipinfo.label[sizeof(chipinfo.label)-1] = '\0';
945 chipinfo.lines = gdev->ngpio;
946 if (copy_to_user(ip, &chipinfo, sizeof(chipinfo)))
949 } else if (cmd == GPIO_GET_LINEINFO_IOCTL) {
950 struct gpioline_info lineinfo;
951 struct gpio_desc *desc;
953 if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
955 if (lineinfo.line_offset >= gdev->ngpio)
958 desc = &gdev->descs[lineinfo.line_offset];
960 strncpy(lineinfo.name, desc->name,
961 sizeof(lineinfo.name));
962 lineinfo.name[sizeof(lineinfo.name)-1] = '\0';
964 lineinfo.name[0] = '\0';
967 strncpy(lineinfo.consumer, desc->label,
968 sizeof(lineinfo.consumer));
969 lineinfo.consumer[sizeof(lineinfo.consumer)-1] = '\0';
971 lineinfo.consumer[0] = '\0';
975 * Userspace only need to know that the kernel is using
976 * this GPIO so it can't use it.
979 if (test_bit(FLAG_REQUESTED, &desc->flags) ||
980 test_bit(FLAG_IS_HOGGED, &desc->flags) ||
981 test_bit(FLAG_USED_AS_IRQ, &desc->flags) ||
982 test_bit(FLAG_EXPORT, &desc->flags) ||
983 test_bit(FLAG_SYSFS, &desc->flags))
984 lineinfo.flags |= GPIOLINE_FLAG_KERNEL;
985 if (test_bit(FLAG_IS_OUT, &desc->flags))
986 lineinfo.flags |= GPIOLINE_FLAG_IS_OUT;
987 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
988 lineinfo.flags |= GPIOLINE_FLAG_ACTIVE_LOW;
989 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
990 lineinfo.flags |= (GPIOLINE_FLAG_OPEN_DRAIN |
991 GPIOLINE_FLAG_IS_OUT);
992 if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
993 lineinfo.flags |= (GPIOLINE_FLAG_OPEN_SOURCE |
994 GPIOLINE_FLAG_IS_OUT);
996 if (copy_to_user(ip, &lineinfo, sizeof(lineinfo)))
999 } else if (cmd == GPIO_GET_LINEHANDLE_IOCTL) {
1000 return linehandle_create(gdev, ip);
1001 } else if (cmd == GPIO_GET_LINEEVENT_IOCTL) {
1002 return lineevent_create(gdev, ip);
1007 #ifdef CONFIG_COMPAT
1008 static long gpio_ioctl_compat(struct file *filp, unsigned int cmd,
1011 return gpio_ioctl(filp, cmd, (unsigned long)compat_ptr(arg));
1016 * gpio_chrdev_open() - open the chardev for ioctl operations
1017 * @inode: inode for this chardev
1018 * @filp: file struct for storing private data
1019 * Returns 0 on success
1021 static int gpio_chrdev_open(struct inode *inode, struct file *filp)
1023 struct gpio_device *gdev = container_of(inode->i_cdev,
1024 struct gpio_device, chrdev);
1026 /* Fail on open if the backing gpiochip is gone */
1029 get_device(&gdev->dev);
1030 filp->private_data = gdev;
1032 return nonseekable_open(inode, filp);
1036 * gpio_chrdev_release() - close chardev after ioctl operations
1037 * @inode: inode for this chardev
1038 * @filp: file struct for storing private data
1039 * Returns 0 on success
1041 static int gpio_chrdev_release(struct inode *inode, struct file *filp)
1043 struct gpio_device *gdev = container_of(inode->i_cdev,
1044 struct gpio_device, chrdev);
1046 put_device(&gdev->dev);
1051 static const struct file_operations gpio_fileops = {
1052 .release = gpio_chrdev_release,
1053 .open = gpio_chrdev_open,
1054 .owner = THIS_MODULE,
1055 .llseek = no_llseek,
1056 .unlocked_ioctl = gpio_ioctl,
1057 #ifdef CONFIG_COMPAT
1058 .compat_ioctl = gpio_ioctl_compat,
1062 static void gpiodevice_release(struct device *dev)
1064 struct gpio_device *gdev = dev_get_drvdata(dev);
1066 list_del(&gdev->list);
1067 ida_simple_remove(&gpio_ida, gdev->id);
1073 static int gpiochip_setup_dev(struct gpio_device *gdev)
1077 cdev_init(&gdev->chrdev, &gpio_fileops);
1078 gdev->chrdev.owner = THIS_MODULE;
1079 gdev->dev.devt = MKDEV(MAJOR(gpio_devt), gdev->id);
1081 status = cdev_device_add(&gdev->chrdev, &gdev->dev);
1085 chip_dbg(gdev->chip, "added GPIO chardev (%d:%d)\n",
1086 MAJOR(gpio_devt), gdev->id);
1088 status = gpiochip_sysfs_register(gdev);
1090 goto err_remove_device;
1092 /* From this point, the .release() function cleans up gpio_device */
1093 gdev->dev.release = gpiodevice_release;
1094 pr_debug("%s: registered GPIOs %d to %d on device: %s (%s)\n",
1095 __func__, gdev->base, gdev->base + gdev->ngpio - 1,
1096 dev_name(&gdev->dev), gdev->chip->label ? : "generic");
1101 cdev_device_del(&gdev->chrdev, &gdev->dev);
1105 static void gpiochip_setup_devs(void)
1107 struct gpio_device *gdev;
1110 list_for_each_entry(gdev, &gpio_devices, list) {
1111 err = gpiochip_setup_dev(gdev);
1113 pr_err("%s: Failed to initialize gpio device (%d)\n",
1114 dev_name(&gdev->dev), err);
1119 * gpiochip_add_data() - register a gpio_chip
1120 * @chip: the chip to register, with chip->base initialized
1121 * @data: driver-private data associated with this chip
1123 * Context: potentially before irqs will work
1125 * When gpiochip_add_data() is called very early during boot, so that GPIOs
1126 * can be freely used, the chip->parent device must be registered before
1127 * the gpio framework's arch_initcall(). Otherwise sysfs initialization
1128 * for GPIOs will fail rudely.
1130 * gpiochip_add_data() must only be called after gpiolib initialization,
1131 * ie after core_initcall().
1133 * If chip->base is negative, this requests dynamic assignment of
1134 * a range of valid GPIOs.
1137 * A negative errno if the chip can't be registered, such as because the
1138 * chip->base is invalid or already associated with a different chip.
1139 * Otherwise it returns zero as a success code.
1141 int gpiochip_add_data(struct gpio_chip *chip, void *data)
1143 unsigned long flags;
1146 int base = chip->base;
1147 struct gpio_device *gdev;
1150 * First: allocate and populate the internal stat container, and
1151 * set up the struct device.
1153 gdev = kzalloc(sizeof(*gdev), GFP_KERNEL);
1156 gdev->dev.bus = &gpio_bus_type;
1158 chip->gpiodev = gdev;
1160 gdev->dev.parent = chip->parent;
1161 gdev->dev.of_node = chip->parent->of_node;
1164 #ifdef CONFIG_OF_GPIO
1165 /* If the gpiochip has an assigned OF node this takes precedence */
1167 gdev->dev.of_node = chip->of_node;
1170 gdev->id = ida_simple_get(&gpio_ida, 0, 0, GFP_KERNEL);
1175 dev_set_name(&gdev->dev, "gpiochip%d", gdev->id);
1176 device_initialize(&gdev->dev);
1177 dev_set_drvdata(&gdev->dev, gdev);
1178 if (chip->parent && chip->parent->driver)
1179 gdev->owner = chip->parent->driver->owner;
1180 else if (chip->owner)
1181 /* TODO: remove chip->owner */
1182 gdev->owner = chip->owner;
1184 gdev->owner = THIS_MODULE;
1186 gdev->descs = kcalloc(chip->ngpio, sizeof(gdev->descs[0]), GFP_KERNEL);
1192 if (chip->ngpio == 0) {
1193 chip_err(chip, "tried to insert a GPIO chip with zero lines\n");
1195 goto err_free_descs;
1199 gdev->label = kstrdup(chip->label, GFP_KERNEL);
1201 gdev->label = kstrdup("unknown", GFP_KERNEL);
1204 goto err_free_descs;
1207 gdev->ngpio = chip->ngpio;
1210 spin_lock_irqsave(&gpio_lock, flags);
1213 * TODO: this allocates a Linux GPIO number base in the global
1214 * GPIO numberspace for this chip. In the long run we want to
1215 * get *rid* of this numberspace and use only descriptors, but
1216 * it may be a pipe dream. It will not happen before we get rid
1217 * of the sysfs interface anyways.
1220 base = gpiochip_find_base(chip->ngpio);
1223 spin_unlock_irqrestore(&gpio_lock, flags);
1224 goto err_free_label;
1227 * TODO: it should not be necessary to reflect the assigned
1228 * base outside of the GPIO subsystem. Go over drivers and
1229 * see if anyone makes use of this, else drop this and assign
1236 status = gpiodev_add_to_list(gdev);
1238 spin_unlock_irqrestore(&gpio_lock, flags);
1239 goto err_free_label;
1242 spin_unlock_irqrestore(&gpio_lock, flags);
1244 for (i = 0; i < chip->ngpio; i++) {
1245 struct gpio_desc *desc = &gdev->descs[i];
1249 /* REVISIT: most hardware initializes GPIOs as inputs (often
1250 * with pullups enabled) so power usage is minimized. Linux
1251 * code should set the gpio direction first thing; but until
1252 * it does, and in case chip->get_direction is not set, we may
1253 * expose the wrong direction in sysfs.
1255 desc->flags = !chip->direction_input ? (1 << FLAG_IS_OUT) : 0;
1258 #ifdef CONFIG_PINCTRL
1259 INIT_LIST_HEAD(&gdev->pin_ranges);
1262 status = gpiochip_set_desc_names(chip);
1264 goto err_remove_from_list;
1266 status = gpiochip_irqchip_init_valid_mask(chip);
1268 goto err_remove_from_list;
1270 status = of_gpiochip_add(chip);
1272 goto err_remove_chip;
1274 acpi_gpiochip_add(chip);
1277 * By first adding the chardev, and then adding the device,
1278 * we get a device node entry in sysfs under
1279 * /sys/bus/gpio/devices/gpiochipN/dev that can be used for
1280 * coldplug of device nodes and other udev business.
1281 * We can do this only if gpiolib has been initialized.
1282 * Otherwise, defer until later.
1284 if (gpiolib_initialized) {
1285 status = gpiochip_setup_dev(gdev);
1287 goto err_remove_chip;
1292 acpi_gpiochip_remove(chip);
1293 gpiochip_free_hogs(chip);
1294 of_gpiochip_remove(chip);
1295 gpiochip_irqchip_free_valid_mask(chip);
1296 err_remove_from_list:
1297 spin_lock_irqsave(&gpio_lock, flags);
1298 list_del(&gdev->list);
1299 spin_unlock_irqrestore(&gpio_lock, flags);
1305 ida_simple_remove(&gpio_ida, gdev->id);
1307 /* failures here can mean systems won't boot... */
1308 pr_err("%s: GPIOs %d..%d (%s) failed to register\n", __func__,
1309 gdev->base, gdev->base + gdev->ngpio - 1,
1310 chip->label ? : "generic");
1314 EXPORT_SYMBOL_GPL(gpiochip_add_data);
1317 * gpiochip_get_data() - get per-subdriver data for the chip
1321 * The per-subdriver data for the chip.
1323 void *gpiochip_get_data(struct gpio_chip *chip)
1325 return chip->gpiodev->data;
1327 EXPORT_SYMBOL_GPL(gpiochip_get_data);
1330 * gpiochip_remove() - unregister a gpio_chip
1331 * @chip: the chip to unregister
1333 * A gpio_chip with any GPIOs still requested may not be removed.
1335 void gpiochip_remove(struct gpio_chip *chip)
1337 struct gpio_device *gdev = chip->gpiodev;
1338 struct gpio_desc *desc;
1339 unsigned long flags;
1341 bool requested = false;
1343 /* FIXME: should the legacy sysfs handling be moved to gpio_device? */
1344 gpiochip_sysfs_unregister(gdev);
1345 gpiochip_free_hogs(chip);
1346 /* Numb the device, cancelling all outstanding operations */
1348 gpiochip_irqchip_remove(chip);
1349 acpi_gpiochip_remove(chip);
1350 gpiochip_remove_pin_ranges(chip);
1351 of_gpiochip_remove(chip);
1353 * We accept no more calls into the driver from this point, so
1354 * NULL the driver data pointer
1358 spin_lock_irqsave(&gpio_lock, flags);
1359 for (i = 0; i < gdev->ngpio; i++) {
1360 desc = &gdev->descs[i];
1361 if (test_bit(FLAG_REQUESTED, &desc->flags))
1364 spin_unlock_irqrestore(&gpio_lock, flags);
1367 dev_crit(&gdev->dev,
1368 "REMOVING GPIOCHIP WITH GPIOS STILL REQUESTED\n");
1371 * The gpiochip side puts its use of the device to rest here:
1372 * if there are no userspace clients, the chardev and device will
1373 * be removed, else it will be dangling until the last user is
1376 cdev_device_del(&gdev->chrdev, &gdev->dev);
1377 put_device(&gdev->dev);
1379 EXPORT_SYMBOL_GPL(gpiochip_remove);
1381 static void devm_gpio_chip_release(struct device *dev, void *res)
1383 struct gpio_chip *chip = *(struct gpio_chip **)res;
1385 gpiochip_remove(chip);
1388 static int devm_gpio_chip_match(struct device *dev, void *res, void *data)
1391 struct gpio_chip **r = res;
1402 * devm_gpiochip_add_data() - Resource manager piochip_add_data()
1403 * @dev: the device pointer on which irq_chip belongs to.
1404 * @chip: the chip to register, with chip->base initialized
1405 * @data: driver-private data associated with this chip
1407 * Context: potentially before irqs will work
1409 * The gpio chip automatically be released when the device is unbound.
1412 * A negative errno if the chip can't be registered, such as because the
1413 * chip->base is invalid or already associated with a different chip.
1414 * Otherwise it returns zero as a success code.
1416 int devm_gpiochip_add_data(struct device *dev, struct gpio_chip *chip,
1419 struct gpio_chip **ptr;
1422 ptr = devres_alloc(devm_gpio_chip_release, sizeof(*ptr),
1427 ret = gpiochip_add_data(chip, data);
1434 devres_add(dev, ptr);
1438 EXPORT_SYMBOL_GPL(devm_gpiochip_add_data);
1441 * devm_gpiochip_remove() - Resource manager of gpiochip_remove()
1442 * @dev: device for which which resource was allocated
1443 * @chip: the chip to remove
1445 * A gpio_chip with any GPIOs still requested may not be removed.
1447 void devm_gpiochip_remove(struct device *dev, struct gpio_chip *chip)
1451 ret = devres_release(dev, devm_gpio_chip_release,
1452 devm_gpio_chip_match, chip);
1455 EXPORT_SYMBOL_GPL(devm_gpiochip_remove);
1458 * gpiochip_find() - iterator for locating a specific gpio_chip
1459 * @data: data to pass to match function
1460 * @match: Callback function to check gpio_chip
1462 * Similar to bus_find_device. It returns a reference to a gpio_chip as
1463 * determined by a user supplied @match callback. The callback should return
1464 * 0 if the device doesn't match and non-zero if it does. If the callback is
1465 * non-zero, this function will return to the caller and not iterate over any
1468 struct gpio_chip *gpiochip_find(void *data,
1469 int (*match)(struct gpio_chip *chip,
1472 struct gpio_device *gdev;
1473 struct gpio_chip *chip = NULL;
1474 unsigned long flags;
1476 spin_lock_irqsave(&gpio_lock, flags);
1477 list_for_each_entry(gdev, &gpio_devices, list)
1478 if (gdev->chip && match(gdev->chip, data)) {
1483 spin_unlock_irqrestore(&gpio_lock, flags);
1487 EXPORT_SYMBOL_GPL(gpiochip_find);
1489 static int gpiochip_match_name(struct gpio_chip *chip, void *data)
1491 const char *name = data;
1493 return !strcmp(chip->label, name);
1496 static struct gpio_chip *find_chip_by_name(const char *name)
1498 return gpiochip_find((void *)name, gpiochip_match_name);
1501 #ifdef CONFIG_GPIOLIB_IRQCHIP
1504 * The following is irqchip helper code for gpiochips.
1507 static int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gpiochip)
1509 if (!gpiochip->irq_need_valid_mask)
1512 gpiochip->irq_valid_mask = kcalloc(BITS_TO_LONGS(gpiochip->ngpio),
1513 sizeof(long), GFP_KERNEL);
1514 if (!gpiochip->irq_valid_mask)
1517 /* Assume by default all GPIOs are valid */
1518 bitmap_fill(gpiochip->irq_valid_mask, gpiochip->ngpio);
1523 static void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gpiochip)
1525 kfree(gpiochip->irq_valid_mask);
1526 gpiochip->irq_valid_mask = NULL;
1529 static bool gpiochip_irqchip_irq_valid(const struct gpio_chip *gpiochip,
1530 unsigned int offset)
1532 /* No mask means all valid */
1533 if (likely(!gpiochip->irq_valid_mask))
1535 return test_bit(offset, gpiochip->irq_valid_mask);
1539 * gpiochip_set_cascaded_irqchip() - connects a cascaded irqchip to a gpiochip
1540 * @gpiochip: the gpiochip to set the irqchip chain to
1541 * @irqchip: the irqchip to chain to the gpiochip
1542 * @parent_irq: the irq number corresponding to the parent IRQ for this
1544 * @parent_handler: the parent interrupt handler for the accumulated IRQ
1545 * coming out of the gpiochip. If the interrupt is nested rather than
1546 * cascaded, pass NULL in this handler argument
1548 static void gpiochip_set_cascaded_irqchip(struct gpio_chip *gpiochip,
1549 struct irq_chip *irqchip,
1550 unsigned int parent_irq,
1551 irq_flow_handler_t parent_handler)
1553 unsigned int offset;
1555 if (!gpiochip->irqdomain) {
1556 chip_err(gpiochip, "called %s before setting up irqchip\n",
1561 if (parent_handler) {
1562 if (gpiochip->can_sleep) {
1564 "you cannot have chained interrupts on a "
1565 "chip that may sleep\n");
1569 * The parent irqchip is already using the chip_data for this
1570 * irqchip, so our callbacks simply use the handler_data.
1572 irq_set_chained_handler_and_data(parent_irq, parent_handler,
1575 gpiochip->irq_chained_parent = parent_irq;
1578 /* Set the parent IRQ for all affected IRQs */
1579 for (offset = 0; offset < gpiochip->ngpio; offset++) {
1580 if (!gpiochip_irqchip_irq_valid(gpiochip, offset))
1582 irq_set_parent(irq_find_mapping(gpiochip->irqdomain, offset),
1588 * gpiochip_set_chained_irqchip() - connects a chained irqchip to a gpiochip
1589 * @gpiochip: the gpiochip to set the irqchip chain to
1590 * @irqchip: the irqchip to chain to the gpiochip
1591 * @parent_irq: the irq number corresponding to the parent IRQ for this
1593 * @parent_handler: the parent interrupt handler for the accumulated IRQ
1594 * coming out of the gpiochip. If the interrupt is nested rather than
1595 * cascaded, pass NULL in this handler argument
1597 void gpiochip_set_chained_irqchip(struct gpio_chip *gpiochip,
1598 struct irq_chip *irqchip,
1599 unsigned int parent_irq,
1600 irq_flow_handler_t parent_handler)
1602 gpiochip_set_cascaded_irqchip(gpiochip, irqchip, parent_irq,
1605 EXPORT_SYMBOL_GPL(gpiochip_set_chained_irqchip);
1608 * gpiochip_set_nested_irqchip() - connects a nested irqchip to a gpiochip
1609 * @gpiochip: the gpiochip to set the irqchip nested handler to
1610 * @irqchip: the irqchip to nest to the gpiochip
1611 * @parent_irq: the irq number corresponding to the parent IRQ for this
1614 void gpiochip_set_nested_irqchip(struct gpio_chip *gpiochip,
1615 struct irq_chip *irqchip,
1616 unsigned int parent_irq)
1618 if (!gpiochip->irq_nested) {
1619 chip_err(gpiochip, "tried to nest a chained gpiochip\n");
1622 gpiochip_set_cascaded_irqchip(gpiochip, irqchip, parent_irq,
1625 EXPORT_SYMBOL_GPL(gpiochip_set_nested_irqchip);
1628 * gpiochip_irq_map() - maps an IRQ into a GPIO irqchip
1629 * @d: the irqdomain used by this irqchip
1630 * @irq: the global irq number used by this GPIO irqchip irq
1631 * @hwirq: the local IRQ/GPIO line offset on this gpiochip
1633 * This function will set up the mapping for a certain IRQ line on a
1634 * gpiochip by assigning the gpiochip as chip data, and using the irqchip
1635 * stored inside the gpiochip.
1637 static int gpiochip_irq_map(struct irq_domain *d, unsigned int irq,
1638 irq_hw_number_t hwirq)
1640 struct gpio_chip *chip = d->host_data;
1642 if (!gpiochip_irqchip_irq_valid(chip, hwirq))
1645 irq_set_chip_data(irq, chip);
1647 * This lock class tells lockdep that GPIO irqs are in a different
1648 * category than their parents, so it won't report false recursion.
1650 irq_set_lockdep_class(irq, chip->lock_key);
1651 irq_set_chip_and_handler(irq, chip->irqchip, chip->irq_handler);
1652 /* Chips that use nested thread handlers have them marked */
1653 if (chip->irq_nested)
1654 irq_set_nested_thread(irq, 1);
1655 irq_set_noprobe(irq);
1658 * No set-up of the hardware will happen if IRQ_TYPE_NONE
1659 * is passed as default type.
1661 if (chip->irq_default_type != IRQ_TYPE_NONE)
1662 irq_set_irq_type(irq, chip->irq_default_type);
1667 static void gpiochip_irq_unmap(struct irq_domain *d, unsigned int irq)
1669 struct gpio_chip *chip = d->host_data;
1671 if (chip->irq_nested)
1672 irq_set_nested_thread(irq, 0);
1673 irq_set_chip_and_handler(irq, NULL, NULL);
1674 irq_set_chip_data(irq, NULL);
1677 static const struct irq_domain_ops gpiochip_domain_ops = {
1678 .map = gpiochip_irq_map,
1679 .unmap = gpiochip_irq_unmap,
1680 /* Virtually all GPIO irqchips are twocell:ed */
1681 .xlate = irq_domain_xlate_twocell,
1684 static int gpiochip_irq_reqres(struct irq_data *d)
1686 struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
1688 if (!try_module_get(chip->gpiodev->owner))
1691 if (gpiochip_lock_as_irq(chip, d->hwirq)) {
1693 "unable to lock HW IRQ %lu for IRQ\n",
1695 module_put(chip->gpiodev->owner);
1701 static void gpiochip_irq_relres(struct irq_data *d)
1703 struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
1705 gpiochip_unlock_as_irq(chip, d->hwirq);
1706 module_put(chip->gpiodev->owner);
1709 static int gpiochip_to_irq(struct gpio_chip *chip, unsigned offset)
1711 if (!gpiochip_irqchip_irq_valid(chip, offset))
1713 return irq_create_mapping(chip->irqdomain, offset);
1717 * gpiochip_irqchip_remove() - removes an irqchip added to a gpiochip
1718 * @gpiochip: the gpiochip to remove the irqchip from
1720 * This is called only from gpiochip_remove()
1722 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip)
1724 unsigned int offset;
1726 acpi_gpiochip_free_interrupts(gpiochip);
1728 if (gpiochip->irq_chained_parent) {
1729 irq_set_chained_handler(gpiochip->irq_chained_parent, NULL);
1730 irq_set_handler_data(gpiochip->irq_chained_parent, NULL);
1733 /* Remove all IRQ mappings and delete the domain */
1734 if (gpiochip->irqdomain) {
1735 for (offset = 0; offset < gpiochip->ngpio; offset++) {
1736 if (!gpiochip_irqchip_irq_valid(gpiochip, offset))
1738 irq_dispose_mapping(
1739 irq_find_mapping(gpiochip->irqdomain, offset));
1741 irq_domain_remove(gpiochip->irqdomain);
1744 if (gpiochip->irqchip) {
1745 gpiochip->irqchip->irq_request_resources = NULL;
1746 gpiochip->irqchip->irq_release_resources = NULL;
1747 gpiochip->irqchip = NULL;
1750 gpiochip_irqchip_free_valid_mask(gpiochip);
1754 * gpiochip_irqchip_add_key() - adds an irqchip to a gpiochip
1755 * @gpiochip: the gpiochip to add the irqchip to
1756 * @irqchip: the irqchip to add to the gpiochip
1757 * @first_irq: if not dynamically assigned, the base (first) IRQ to
1758 * allocate gpiochip irqs from
1759 * @handler: the irq handler to use (often a predefined irq core function)
1760 * @type: the default type for IRQs on this irqchip, pass IRQ_TYPE_NONE
1761 * to have the core avoid setting up any default type in the hardware.
1762 * @nested: whether this is a nested irqchip calling handle_nested_irq()
1763 * in its IRQ handler
1764 * @lock_key: lockdep class
1766 * This function closely associates a certain irqchip with a certain
1767 * gpiochip, providing an irq domain to translate the local IRQs to
1768 * global irqs in the gpiolib core, and making sure that the gpiochip
1769 * is passed as chip data to all related functions. Driver callbacks
1770 * need to use gpiochip_get_data() to get their local state containers back
1771 * from the gpiochip passed as chip data. An irqdomain will be stored
1772 * in the gpiochip that shall be used by the driver to handle IRQ number
1773 * translation. The gpiochip will need to be initialized and registered
1774 * before calling this function.
1776 * This function will handle two cell:ed simple IRQs and assumes all
1777 * the pins on the gpiochip can generate a unique IRQ. Everything else
1778 * need to be open coded.
1780 int gpiochip_irqchip_add_key(struct gpio_chip *gpiochip,
1781 struct irq_chip *irqchip,
1782 unsigned int first_irq,
1783 irq_flow_handler_t handler,
1786 struct lock_class_key *lock_key)
1788 struct device_node *of_node;
1790 if (!gpiochip || !irqchip)
1793 if (!gpiochip->parent) {
1794 pr_err("missing gpiochip .dev parent pointer\n");
1797 gpiochip->irq_nested = nested;
1798 of_node = gpiochip->parent->of_node;
1799 #ifdef CONFIG_OF_GPIO
1801 * If the gpiochip has an assigned OF node this takes precedence
1802 * FIXME: get rid of this and use gpiochip->parent->of_node
1805 if (gpiochip->of_node)
1806 of_node = gpiochip->of_node;
1809 * Specifying a default trigger is a terrible idea if DT or ACPI is
1810 * used to configure the interrupts, as you may end-up with
1811 * conflicting triggers. Tell the user, and reset to NONE.
1813 if (WARN(of_node && type != IRQ_TYPE_NONE,
1814 "%pOF: Ignoring %d default trigger\n", of_node, type))
1815 type = IRQ_TYPE_NONE;
1816 if (has_acpi_companion(gpiochip->parent) && type != IRQ_TYPE_NONE) {
1817 acpi_handle_warn(ACPI_HANDLE(gpiochip->parent),
1818 "Ignoring %d default trigger\n", type);
1819 type = IRQ_TYPE_NONE;
1822 gpiochip->irqchip = irqchip;
1823 gpiochip->irq_handler = handler;
1824 gpiochip->irq_default_type = type;
1825 gpiochip->to_irq = gpiochip_to_irq;
1826 gpiochip->lock_key = lock_key;
1827 gpiochip->irqdomain = irq_domain_add_simple(of_node,
1828 gpiochip->ngpio, first_irq,
1829 &gpiochip_domain_ops, gpiochip);
1830 if (!gpiochip->irqdomain) {
1831 gpiochip->irqchip = NULL;
1836 * It is possible for a driver to override this, but only if the
1837 * alternative functions are both implemented.
1839 if (!irqchip->irq_request_resources &&
1840 !irqchip->irq_release_resources) {
1841 irqchip->irq_request_resources = gpiochip_irq_reqres;
1842 irqchip->irq_release_resources = gpiochip_irq_relres;
1845 acpi_gpiochip_request_interrupts(gpiochip);
1849 EXPORT_SYMBOL_GPL(gpiochip_irqchip_add_key);
1851 #else /* CONFIG_GPIOLIB_IRQCHIP */
1853 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip) {}
1854 static inline int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gpiochip)
1858 static inline void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gpiochip)
1861 #endif /* CONFIG_GPIOLIB_IRQCHIP */
1864 * gpiochip_generic_request() - request the gpio function for a pin
1865 * @chip: the gpiochip owning the GPIO
1866 * @offset: the offset of the GPIO to request for GPIO function
1868 int gpiochip_generic_request(struct gpio_chip *chip, unsigned offset)
1870 return pinctrl_request_gpio(chip->gpiodev->base + offset);
1872 EXPORT_SYMBOL_GPL(gpiochip_generic_request);
1875 * gpiochip_generic_free() - free the gpio function from a pin
1876 * @chip: the gpiochip to request the gpio function for
1877 * @offset: the offset of the GPIO to free from GPIO function
1879 void gpiochip_generic_free(struct gpio_chip *chip, unsigned offset)
1881 pinctrl_free_gpio(chip->gpiodev->base + offset);
1883 EXPORT_SYMBOL_GPL(gpiochip_generic_free);
1886 * gpiochip_generic_config() - apply configuration for a pin
1887 * @chip: the gpiochip owning the GPIO
1888 * @offset: the offset of the GPIO to apply the configuration
1889 * @config: the configuration to be applied
1891 int gpiochip_generic_config(struct gpio_chip *chip, unsigned offset,
1892 unsigned long config)
1894 return pinctrl_gpio_set_config(chip->gpiodev->base + offset, config);
1896 EXPORT_SYMBOL_GPL(gpiochip_generic_config);
1898 #ifdef CONFIG_PINCTRL
1901 * gpiochip_add_pingroup_range() - add a range for GPIO <-> pin mapping
1902 * @chip: the gpiochip to add the range for
1903 * @pctldev: the pin controller to map to
1904 * @gpio_offset: the start offset in the current gpio_chip number space
1905 * @pin_group: name of the pin group inside the pin controller
1907 int gpiochip_add_pingroup_range(struct gpio_chip *chip,
1908 struct pinctrl_dev *pctldev,
1909 unsigned int gpio_offset, const char *pin_group)
1911 struct gpio_pin_range *pin_range;
1912 struct gpio_device *gdev = chip->gpiodev;
1915 pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
1917 chip_err(chip, "failed to allocate pin ranges\n");
1921 /* Use local offset as range ID */
1922 pin_range->range.id = gpio_offset;
1923 pin_range->range.gc = chip;
1924 pin_range->range.name = chip->label;
1925 pin_range->range.base = gdev->base + gpio_offset;
1926 pin_range->pctldev = pctldev;
1928 ret = pinctrl_get_group_pins(pctldev, pin_group,
1929 &pin_range->range.pins,
1930 &pin_range->range.npins);
1936 pinctrl_add_gpio_range(pctldev, &pin_range->range);
1938 chip_dbg(chip, "created GPIO range %d->%d ==> %s PINGRP %s\n",
1939 gpio_offset, gpio_offset + pin_range->range.npins - 1,
1940 pinctrl_dev_get_devname(pctldev), pin_group);
1942 list_add_tail(&pin_range->node, &gdev->pin_ranges);
1946 EXPORT_SYMBOL_GPL(gpiochip_add_pingroup_range);
1949 * gpiochip_add_pin_range() - add a range for GPIO <-> pin mapping
1950 * @chip: the gpiochip to add the range for
1951 * @pinctl_name: the dev_name() of the pin controller to map to
1952 * @gpio_offset: the start offset in the current gpio_chip number space
1953 * @pin_offset: the start offset in the pin controller number space
1954 * @npins: the number of pins from the offset of each pin space (GPIO and
1955 * pin controller) to accumulate in this range
1958 * 0 on success, or a negative error-code on failure.
1960 int gpiochip_add_pin_range(struct gpio_chip *chip, const char *pinctl_name,
1961 unsigned int gpio_offset, unsigned int pin_offset,
1964 struct gpio_pin_range *pin_range;
1965 struct gpio_device *gdev = chip->gpiodev;
1968 pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
1970 chip_err(chip, "failed to allocate pin ranges\n");
1974 /* Use local offset as range ID */
1975 pin_range->range.id = gpio_offset;
1976 pin_range->range.gc = chip;
1977 pin_range->range.name = chip->label;
1978 pin_range->range.base = gdev->base + gpio_offset;
1979 pin_range->range.pin_base = pin_offset;
1980 pin_range->range.npins = npins;
1981 pin_range->pctldev = pinctrl_find_and_add_gpio_range(pinctl_name,
1983 if (IS_ERR(pin_range->pctldev)) {
1984 ret = PTR_ERR(pin_range->pctldev);
1985 chip_err(chip, "could not create pin range\n");
1989 chip_dbg(chip, "created GPIO range %d->%d ==> %s PIN %d->%d\n",
1990 gpio_offset, gpio_offset + npins - 1,
1992 pin_offset, pin_offset + npins - 1);
1994 list_add_tail(&pin_range->node, &gdev->pin_ranges);
1998 EXPORT_SYMBOL_GPL(gpiochip_add_pin_range);
2001 * gpiochip_remove_pin_ranges() - remove all the GPIO <-> pin mappings
2002 * @chip: the chip to remove all the mappings for
2004 void gpiochip_remove_pin_ranges(struct gpio_chip *chip)
2006 struct gpio_pin_range *pin_range, *tmp;
2007 struct gpio_device *gdev = chip->gpiodev;
2009 list_for_each_entry_safe(pin_range, tmp, &gdev->pin_ranges, node) {
2010 list_del(&pin_range->node);
2011 pinctrl_remove_gpio_range(pin_range->pctldev,
2016 EXPORT_SYMBOL_GPL(gpiochip_remove_pin_ranges);
2018 #endif /* CONFIG_PINCTRL */
2020 /* These "optional" allocation calls help prevent drivers from stomping
2021 * on each other, and help provide better diagnostics in debugfs.
2022 * They're called even less than the "set direction" calls.
2024 static int __gpiod_request(struct gpio_desc *desc, const char *label)
2026 struct gpio_chip *chip = desc->gdev->chip;
2028 unsigned long flags;
2030 spin_lock_irqsave(&gpio_lock, flags);
2032 /* NOTE: gpio_request() can be called in early boot,
2033 * before IRQs are enabled, for non-sleeping (SOC) GPIOs.
2036 if (test_and_set_bit(FLAG_REQUESTED, &desc->flags) == 0) {
2037 desc_set_label(desc, label ? : "?");
2044 if (chip->request) {
2045 /* chip->request may sleep */
2046 spin_unlock_irqrestore(&gpio_lock, flags);
2047 status = chip->request(chip, gpio_chip_hwgpio(desc));
2048 spin_lock_irqsave(&gpio_lock, flags);
2051 desc_set_label(desc, NULL);
2052 clear_bit(FLAG_REQUESTED, &desc->flags);
2056 if (chip->get_direction) {
2057 /* chip->get_direction may sleep */
2058 spin_unlock_irqrestore(&gpio_lock, flags);
2059 gpiod_get_direction(desc);
2060 spin_lock_irqsave(&gpio_lock, flags);
2063 spin_unlock_irqrestore(&gpio_lock, flags);
2068 * This descriptor validation needs to be inserted verbatim into each
2069 * function taking a descriptor, so we need to use a preprocessor
2070 * macro to avoid endless duplication. If the desc is NULL it is an
2071 * optional GPIO and calls should just bail out.
2073 #define VALIDATE_DESC(desc) do { \
2076 if (IS_ERR(desc)) { \
2077 pr_warn("%s: invalid GPIO (errorpointer)\n", __func__); \
2078 return PTR_ERR(desc); \
2080 if (!desc->gdev) { \
2081 pr_warn("%s: invalid GPIO (no device)\n", __func__); \
2084 if ( !desc->gdev->chip ) { \
2085 dev_warn(&desc->gdev->dev, \
2086 "%s: backing chip is gone\n", __func__); \
2090 #define VALIDATE_DESC_VOID(desc) do { \
2093 if (IS_ERR(desc)) { \
2094 pr_warn("%s: invalid GPIO (errorpointer)\n", __func__); \
2097 if (!desc->gdev) { \
2098 pr_warn("%s: invalid GPIO (no device)\n", __func__); \
2101 if (!desc->gdev->chip) { \
2102 dev_warn(&desc->gdev->dev, \
2103 "%s: backing chip is gone\n", __func__); \
2108 int gpiod_request(struct gpio_desc *desc, const char *label)
2110 int status = -EPROBE_DEFER;
2111 struct gpio_device *gdev;
2113 VALIDATE_DESC(desc);
2116 if (try_module_get(gdev->owner)) {
2117 status = __gpiod_request(desc, label);
2119 module_put(gdev->owner);
2121 get_device(&gdev->dev);
2125 gpiod_dbg(desc, "%s: status %d\n", __func__, status);
2130 static bool __gpiod_free(struct gpio_desc *desc)
2133 unsigned long flags;
2134 struct gpio_chip *chip;
2138 gpiod_unexport(desc);
2140 spin_lock_irqsave(&gpio_lock, flags);
2142 chip = desc->gdev->chip;
2143 if (chip && test_bit(FLAG_REQUESTED, &desc->flags)) {
2145 spin_unlock_irqrestore(&gpio_lock, flags);
2146 might_sleep_if(chip->can_sleep);
2147 chip->free(chip, gpio_chip_hwgpio(desc));
2148 spin_lock_irqsave(&gpio_lock, flags);
2150 desc_set_label(desc, NULL);
2151 clear_bit(FLAG_ACTIVE_LOW, &desc->flags);
2152 clear_bit(FLAG_REQUESTED, &desc->flags);
2153 clear_bit(FLAG_OPEN_DRAIN, &desc->flags);
2154 clear_bit(FLAG_OPEN_SOURCE, &desc->flags);
2155 clear_bit(FLAG_IS_HOGGED, &desc->flags);
2159 spin_unlock_irqrestore(&gpio_lock, flags);
2163 void gpiod_free(struct gpio_desc *desc)
2165 if (desc && desc->gdev && __gpiod_free(desc)) {
2166 module_put(desc->gdev->owner);
2167 put_device(&desc->gdev->dev);
2169 WARN_ON(extra_checks);
2174 * gpiochip_is_requested - return string iff signal was requested
2175 * @chip: controller managing the signal
2176 * @offset: of signal within controller's 0..(ngpio - 1) range
2178 * Returns NULL if the GPIO is not currently requested, else a string.
2179 * The string returned is the label passed to gpio_request(); if none has been
2180 * passed it is a meaningless, non-NULL constant.
2182 * This function is for use by GPIO controller drivers. The label can
2183 * help with diagnostics, and knowing that the signal is used as a GPIO
2184 * can help avoid accidentally multiplexing it to another controller.
2186 const char *gpiochip_is_requested(struct gpio_chip *chip, unsigned offset)
2188 struct gpio_desc *desc;
2190 if (offset >= chip->ngpio)
2193 desc = &chip->gpiodev->descs[offset];
2195 if (test_bit(FLAG_REQUESTED, &desc->flags) == 0)
2199 EXPORT_SYMBOL_GPL(gpiochip_is_requested);
2202 * gpiochip_request_own_desc - Allow GPIO chip to request its own descriptor
2204 * @hwnum: hardware number of the GPIO for which to request the descriptor
2205 * @label: label for the GPIO
2207 * Function allows GPIO chip drivers to request and use their own GPIO
2208 * descriptors via gpiolib API. Difference to gpiod_request() is that this
2209 * function will not increase reference count of the GPIO chip module. This
2210 * allows the GPIO chip module to be unloaded as needed (we assume that the
2211 * GPIO chip driver handles freeing the GPIOs it has requested).
2214 * A pointer to the GPIO descriptor, or an ERR_PTR()-encoded negative error
2217 struct gpio_desc *gpiochip_request_own_desc(struct gpio_chip *chip, u16 hwnum,
2220 struct gpio_desc *desc = gpiochip_get_desc(chip, hwnum);
2224 chip_err(chip, "failed to get GPIO descriptor\n");
2228 err = __gpiod_request(desc, label);
2230 return ERR_PTR(err);
2234 EXPORT_SYMBOL_GPL(gpiochip_request_own_desc);
2237 * gpiochip_free_own_desc - Free GPIO requested by the chip driver
2238 * @desc: GPIO descriptor to free
2240 * Function frees the given GPIO requested previously with
2241 * gpiochip_request_own_desc().
2243 void gpiochip_free_own_desc(struct gpio_desc *desc)
2248 EXPORT_SYMBOL_GPL(gpiochip_free_own_desc);
2251 * Drivers MUST set GPIO direction before making get/set calls. In
2252 * some cases this is done in early boot, before IRQs are enabled.
2254 * As a rule these aren't called more than once (except for drivers
2255 * using the open-drain emulation idiom) so these are natural places
2256 * to accumulate extra debugging checks. Note that we can't (yet)
2257 * rely on gpio_request() having been called beforehand.
2261 * gpiod_direction_input - set the GPIO direction to input
2262 * @desc: GPIO to set to input
2264 * Set the direction of the passed GPIO to input, such as gpiod_get_value() can
2265 * be called safely on it.
2267 * Return 0 in case of success, else an error code.
2269 int gpiod_direction_input(struct gpio_desc *desc)
2271 struct gpio_chip *chip;
2272 int status = -EINVAL;
2274 VALIDATE_DESC(desc);
2275 chip = desc->gdev->chip;
2277 if (!chip->get || !chip->direction_input) {
2279 "%s: missing get() or direction_input() operations\n",
2284 status = chip->direction_input(chip, gpio_chip_hwgpio(desc));
2286 clear_bit(FLAG_IS_OUT, &desc->flags);
2288 trace_gpio_direction(desc_to_gpio(desc), 1, status);
2292 EXPORT_SYMBOL_GPL(gpiod_direction_input);
2294 static int gpio_set_drive_single_ended(struct gpio_chip *gc, unsigned offset,
2295 enum pin_config_param mode)
2297 unsigned long config = { PIN_CONF_PACKED(mode, 0) };
2299 return gc->set_config ? gc->set_config(gc, offset, config) : -ENOTSUPP;
2302 static int _gpiod_direction_output_raw(struct gpio_desc *desc, int value)
2304 struct gpio_chip *gc = desc->gdev->chip;
2308 /* GPIOs used for IRQs shall not be set as output */
2309 if (test_bit(FLAG_USED_AS_IRQ, &desc->flags)) {
2311 "%s: tried to set a GPIO tied to an IRQ as output\n",
2316 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags)) {
2317 /* First see if we can enable open drain in hardware */
2318 ret = gpio_set_drive_single_ended(gc, gpio_chip_hwgpio(desc),
2319 PIN_CONFIG_DRIVE_OPEN_DRAIN);
2321 goto set_output_value;
2322 /* Emulate open drain by not actively driving the line high */
2324 ret = gpiod_direction_input(desc);
2325 goto set_output_flag;
2328 else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags)) {
2329 ret = gpio_set_drive_single_ended(gc, gpio_chip_hwgpio(desc),
2330 PIN_CONFIG_DRIVE_OPEN_SOURCE);
2332 goto set_output_value;
2333 /* Emulate open source by not actively driving the line low */
2335 ret = gpiod_direction_input(desc);
2336 goto set_output_flag;
2339 gpio_set_drive_single_ended(gc, gpio_chip_hwgpio(desc),
2340 PIN_CONFIG_DRIVE_PUSH_PULL);
2344 if (!gc->set || !gc->direction_output) {
2346 "%s: missing set() or direction_output() operations\n",
2351 ret = gc->direction_output(gc, gpio_chip_hwgpio(desc), val);
2353 set_bit(FLAG_IS_OUT, &desc->flags);
2354 trace_gpio_value(desc_to_gpio(desc), 0, val);
2355 trace_gpio_direction(desc_to_gpio(desc), 0, ret);
2360 * When emulating open-source or open-drain functionalities by not
2361 * actively driving the line (setting mode to input) we still need to
2362 * set the IS_OUT flag or otherwise we won't be able to set the line
2366 set_bit(FLAG_IS_OUT, &desc->flags);
2371 * gpiod_direction_output_raw - set the GPIO direction to output
2372 * @desc: GPIO to set to output
2373 * @value: initial output value of the GPIO
2375 * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
2376 * be called safely on it. The initial value of the output must be specified
2377 * as raw value on the physical line without regard for the ACTIVE_LOW status.
2379 * Return 0 in case of success, else an error code.
2381 int gpiod_direction_output_raw(struct gpio_desc *desc, int value)
2383 VALIDATE_DESC(desc);
2384 return _gpiod_direction_output_raw(desc, value);
2386 EXPORT_SYMBOL_GPL(gpiod_direction_output_raw);
2389 * gpiod_direction_output - set the GPIO direction to output
2390 * @desc: GPIO to set to output
2391 * @value: initial output value of the GPIO
2393 * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
2394 * be called safely on it. The initial value of the output must be specified
2395 * as the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
2398 * Return 0 in case of success, else an error code.
2400 int gpiod_direction_output(struct gpio_desc *desc, int value)
2402 VALIDATE_DESC(desc);
2403 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2407 return _gpiod_direction_output_raw(desc, value);
2409 EXPORT_SYMBOL_GPL(gpiod_direction_output);
2412 * gpiod_set_debounce - sets @debounce time for a GPIO
2413 * @desc: descriptor of the GPIO for which to set debounce time
2414 * @debounce: debounce time in microseconds
2417 * 0 on success, %-ENOTSUPP if the controller doesn't support setting the
2420 int gpiod_set_debounce(struct gpio_desc *desc, unsigned debounce)
2422 struct gpio_chip *chip;
2423 unsigned long config;
2425 VALIDATE_DESC(desc);
2426 chip = desc->gdev->chip;
2427 if (!chip->set || !chip->set_config) {
2429 "%s: missing set() or set_config() operations\n",
2434 config = pinconf_to_config_packed(PIN_CONFIG_INPUT_DEBOUNCE, debounce);
2435 return chip->set_config(chip, gpio_chip_hwgpio(desc), config);
2437 EXPORT_SYMBOL_GPL(gpiod_set_debounce);
2440 * gpiod_is_active_low - test whether a GPIO is active-low or not
2441 * @desc: the gpio descriptor to test
2443 * Returns 1 if the GPIO is active-low, 0 otherwise.
2445 int gpiod_is_active_low(const struct gpio_desc *desc)
2447 VALIDATE_DESC(desc);
2448 return test_bit(FLAG_ACTIVE_LOW, &desc->flags);
2450 EXPORT_SYMBOL_GPL(gpiod_is_active_low);
2452 /* I/O calls are only valid after configuration completed; the relevant
2453 * "is this a valid GPIO" error checks should already have been done.
2455 * "Get" operations are often inlinable as reading a pin value register,
2456 * and masking the relevant bit in that register.
2458 * When "set" operations are inlinable, they involve writing that mask to
2459 * one register to set a low value, or a different register to set it high.
2460 * Otherwise locking is needed, so there may be little value to inlining.
2462 *------------------------------------------------------------------------
2464 * IMPORTANT!!! The hot paths -- get/set value -- assume that callers
2465 * have requested the GPIO. That can include implicit requesting by
2466 * a direction setting call. Marking a gpio as requested locks its chip
2467 * in memory, guaranteeing that these table lookups need no more locking
2468 * and that gpiochip_remove() will fail.
2470 * REVISIT when debugging, consider adding some instrumentation to ensure
2471 * that the GPIO was actually requested.
2474 static int _gpiod_get_raw_value(const struct gpio_desc *desc)
2476 struct gpio_chip *chip;
2480 chip = desc->gdev->chip;
2481 offset = gpio_chip_hwgpio(desc);
2482 value = chip->get ? chip->get(chip, offset) : -EIO;
2483 value = value < 0 ? value : !!value;
2484 trace_gpio_value(desc_to_gpio(desc), 1, value);
2489 * gpiod_get_raw_value() - return a gpio's raw value
2490 * @desc: gpio whose value will be returned
2492 * Return the GPIO's raw value, i.e. the value of the physical line disregarding
2493 * its ACTIVE_LOW status, or negative errno on failure.
2495 * This function should be called from contexts where we cannot sleep, and will
2496 * complain if the GPIO chip functions potentially sleep.
2498 int gpiod_get_raw_value(const struct gpio_desc *desc)
2500 VALIDATE_DESC(desc);
2501 /* Should be using gpiod_get_raw_value_cansleep() */
2502 WARN_ON(desc->gdev->chip->can_sleep);
2503 return _gpiod_get_raw_value(desc);
2505 EXPORT_SYMBOL_GPL(gpiod_get_raw_value);
2508 * gpiod_get_value() - return a gpio's value
2509 * @desc: gpio whose value will be returned
2511 * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
2512 * account, or negative errno on failure.
2514 * This function should be called from contexts where we cannot sleep, and will
2515 * complain if the GPIO chip functions potentially sleep.
2517 int gpiod_get_value(const struct gpio_desc *desc)
2521 VALIDATE_DESC(desc);
2522 /* Should be using gpiod_get_value_cansleep() */
2523 WARN_ON(desc->gdev->chip->can_sleep);
2525 value = _gpiod_get_raw_value(desc);
2529 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2534 EXPORT_SYMBOL_GPL(gpiod_get_value);
2537 * _gpio_set_open_drain_value() - Set the open drain gpio's value.
2538 * @desc: gpio descriptor whose state need to be set.
2539 * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
2541 static void _gpio_set_open_drain_value(struct gpio_desc *desc, bool value)
2544 struct gpio_chip *chip = desc->gdev->chip;
2545 int offset = gpio_chip_hwgpio(desc);
2548 err = chip->direction_input(chip, offset);
2550 err = chip->direction_output(chip, offset, 0);
2552 set_bit(FLAG_IS_OUT, &desc->flags);
2554 trace_gpio_direction(desc_to_gpio(desc), value, err);
2557 "%s: Error in set_value for open drain err %d\n",
2562 * _gpio_set_open_source_value() - Set the open source gpio's value.
2563 * @desc: gpio descriptor whose state need to be set.
2564 * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
2566 static void _gpio_set_open_source_value(struct gpio_desc *desc, bool value)
2569 struct gpio_chip *chip = desc->gdev->chip;
2570 int offset = gpio_chip_hwgpio(desc);
2573 err = chip->direction_output(chip, offset, 1);
2575 set_bit(FLAG_IS_OUT, &desc->flags);
2577 err = chip->direction_input(chip, offset);
2579 trace_gpio_direction(desc_to_gpio(desc), !value, err);
2582 "%s: Error in set_value for open source err %d\n",
2586 static void _gpiod_set_raw_value(struct gpio_desc *desc, bool value)
2588 struct gpio_chip *chip;
2590 chip = desc->gdev->chip;
2591 trace_gpio_value(desc_to_gpio(desc), 0, value);
2592 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
2593 _gpio_set_open_drain_value(desc, value);
2594 else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
2595 _gpio_set_open_source_value(desc, value);
2597 chip->set(chip, gpio_chip_hwgpio(desc), value);
2601 * set multiple outputs on the same chip;
2602 * use the chip's set_multiple function if available;
2603 * otherwise set the outputs sequentially;
2604 * @mask: bit mask array; one bit per output; BITS_PER_LONG bits per word
2605 * defines which outputs are to be changed
2606 * @bits: bit value array; one bit per output; BITS_PER_LONG bits per word
2607 * defines the values the outputs specified by mask are to be set to
2609 static void gpio_chip_set_multiple(struct gpio_chip *chip,
2610 unsigned long *mask, unsigned long *bits)
2612 if (chip->set_multiple) {
2613 chip->set_multiple(chip, mask, bits);
2617 /* set outputs if the corresponding mask bit is set */
2618 for_each_set_bit(i, mask, chip->ngpio)
2619 chip->set(chip, i, test_bit(i, bits));
2623 void gpiod_set_array_value_complex(bool raw, bool can_sleep,
2624 unsigned int array_size,
2625 struct gpio_desc **desc_array,
2630 while (i < array_size) {
2631 struct gpio_chip *chip = desc_array[i]->gdev->chip;
2632 unsigned long mask[BITS_TO_LONGS(chip->ngpio)];
2633 unsigned long bits[BITS_TO_LONGS(chip->ngpio)];
2637 WARN_ON(chip->can_sleep);
2639 memset(mask, 0, sizeof(mask));
2641 struct gpio_desc *desc = desc_array[i];
2642 int hwgpio = gpio_chip_hwgpio(desc);
2643 int value = value_array[i];
2645 if (!raw && test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2647 trace_gpio_value(desc_to_gpio(desc), 0, value);
2649 * collect all normal outputs belonging to the same chip
2650 * open drain and open source outputs are set individually
2652 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags)) {
2653 _gpio_set_open_drain_value(desc, value);
2654 } else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags)) {
2655 _gpio_set_open_source_value(desc, value);
2657 __set_bit(hwgpio, mask);
2659 __set_bit(hwgpio, bits);
2661 __clear_bit(hwgpio, bits);
2665 } while ((i < array_size) &&
2666 (desc_array[i]->gdev->chip == chip));
2667 /* push collected bits to outputs */
2669 gpio_chip_set_multiple(chip, mask, bits);
2674 * gpiod_set_raw_value() - assign a gpio's raw value
2675 * @desc: gpio whose value will be assigned
2676 * @value: value to assign
2678 * Set the raw value of the GPIO, i.e. the value of its physical line without
2679 * regard for its ACTIVE_LOW status.
2681 * This function should be called from contexts where we cannot sleep, and will
2682 * complain if the GPIO chip functions potentially sleep.
2684 void gpiod_set_raw_value(struct gpio_desc *desc, int value)
2686 VALIDATE_DESC_VOID(desc);
2687 /* Should be using gpiod_set_raw_value_cansleep() */
2688 WARN_ON(desc->gdev->chip->can_sleep);
2689 _gpiod_set_raw_value(desc, value);
2691 EXPORT_SYMBOL_GPL(gpiod_set_raw_value);
2694 * gpiod_set_value() - assign a gpio's value
2695 * @desc: gpio whose value will be assigned
2696 * @value: value to assign
2698 * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
2701 * This function should be called from contexts where we cannot sleep, and will
2702 * complain if the GPIO chip functions potentially sleep.
2704 void gpiod_set_value(struct gpio_desc *desc, int value)
2706 VALIDATE_DESC_VOID(desc);
2707 /* Should be using gpiod_set_value_cansleep() */
2708 WARN_ON(desc->gdev->chip->can_sleep);
2709 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2711 _gpiod_set_raw_value(desc, value);
2713 EXPORT_SYMBOL_GPL(gpiod_set_value);
2716 * gpiod_set_raw_array_value() - assign values to an array of GPIOs
2717 * @array_size: number of elements in the descriptor / value arrays
2718 * @desc_array: array of GPIO descriptors whose values will be assigned
2719 * @value_array: array of values to assign
2721 * Set the raw values of the GPIOs, i.e. the values of the physical lines
2722 * without regard for their ACTIVE_LOW status.
2724 * This function should be called from contexts where we cannot sleep, and will
2725 * complain if the GPIO chip functions potentially sleep.
2727 void gpiod_set_raw_array_value(unsigned int array_size,
2728 struct gpio_desc **desc_array, int *value_array)
2732 gpiod_set_array_value_complex(true, false, array_size, desc_array,
2735 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value);
2738 * gpiod_set_array_value() - assign values to an array of GPIOs
2739 * @array_size: number of elements in the descriptor / value arrays
2740 * @desc_array: array of GPIO descriptors whose values will be assigned
2741 * @value_array: array of values to assign
2743 * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
2746 * This function should be called from contexts where we cannot sleep, and will
2747 * complain if the GPIO chip functions potentially sleep.
2749 void gpiod_set_array_value(unsigned int array_size,
2750 struct gpio_desc **desc_array, int *value_array)
2754 gpiod_set_array_value_complex(false, false, array_size, desc_array,
2757 EXPORT_SYMBOL_GPL(gpiod_set_array_value);
2760 * gpiod_cansleep() - report whether gpio value access may sleep
2761 * @desc: gpio to check
2764 int gpiod_cansleep(const struct gpio_desc *desc)
2766 VALIDATE_DESC(desc);
2767 return desc->gdev->chip->can_sleep;
2769 EXPORT_SYMBOL_GPL(gpiod_cansleep);
2772 * gpiod_to_irq() - return the IRQ corresponding to a GPIO
2773 * @desc: gpio whose IRQ will be returned (already requested)
2775 * Return the IRQ corresponding to the passed GPIO, or an error code in case of
2778 int gpiod_to_irq(const struct gpio_desc *desc)
2780 struct gpio_chip *chip;
2784 * Cannot VALIDATE_DESC() here as gpiod_to_irq() consumer semantics
2785 * requires this function to not return zero on an invalid descriptor
2786 * but rather a negative error number.
2788 if (!desc || IS_ERR(desc) || !desc->gdev || !desc->gdev->chip)
2791 chip = desc->gdev->chip;
2792 offset = gpio_chip_hwgpio(desc);
2794 int retirq = chip->to_irq(chip, offset);
2796 /* Zero means NO_IRQ */
2804 EXPORT_SYMBOL_GPL(gpiod_to_irq);
2807 * gpiochip_lock_as_irq() - lock a GPIO to be used as IRQ
2808 * @chip: the chip the GPIO to lock belongs to
2809 * @offset: the offset of the GPIO to lock as IRQ
2811 * This is used directly by GPIO drivers that want to lock down
2812 * a certain GPIO line to be used for IRQs.
2814 int gpiochip_lock_as_irq(struct gpio_chip *chip, unsigned int offset)
2816 struct gpio_desc *desc;
2818 desc = gpiochip_get_desc(chip, offset);
2820 return PTR_ERR(desc);
2823 * If it's fast: flush the direction setting if something changed
2826 if (!chip->can_sleep && chip->get_direction) {
2827 int dir = chip->get_direction(chip, offset);
2830 clear_bit(FLAG_IS_OUT, &desc->flags);
2832 set_bit(FLAG_IS_OUT, &desc->flags);
2835 if (test_bit(FLAG_IS_OUT, &desc->flags)) {
2837 "%s: tried to flag a GPIO set as output for IRQ\n",
2842 set_bit(FLAG_USED_AS_IRQ, &desc->flags);
2845 * If the consumer has not set up a label (such as when the
2846 * IRQ is referenced from .to_irq()) we set up a label here
2847 * so it is clear this is used as an interrupt.
2850 desc_set_label(desc, "interrupt");
2854 EXPORT_SYMBOL_GPL(gpiochip_lock_as_irq);
2857 * gpiochip_unlock_as_irq() - unlock a GPIO used as IRQ
2858 * @chip: the chip the GPIO to lock belongs to
2859 * @offset: the offset of the GPIO to lock as IRQ
2861 * This is used directly by GPIO drivers that want to indicate
2862 * that a certain GPIO is no longer used exclusively for IRQ.
2864 void gpiochip_unlock_as_irq(struct gpio_chip *chip, unsigned int offset)
2866 struct gpio_desc *desc;
2868 desc = gpiochip_get_desc(chip, offset);
2872 clear_bit(FLAG_USED_AS_IRQ, &desc->flags);
2874 /* If we only had this marking, erase it */
2875 if (desc->label && !strcmp(desc->label, "interrupt"))
2876 desc_set_label(desc, NULL);
2878 EXPORT_SYMBOL_GPL(gpiochip_unlock_as_irq);
2880 bool gpiochip_line_is_irq(struct gpio_chip *chip, unsigned int offset)
2882 if (offset >= chip->ngpio)
2885 return test_bit(FLAG_USED_AS_IRQ, &chip->gpiodev->descs[offset].flags);
2887 EXPORT_SYMBOL_GPL(gpiochip_line_is_irq);
2889 bool gpiochip_line_is_open_drain(struct gpio_chip *chip, unsigned int offset)
2891 if (offset >= chip->ngpio)
2894 return test_bit(FLAG_OPEN_DRAIN, &chip->gpiodev->descs[offset].flags);
2896 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_drain);
2898 bool gpiochip_line_is_open_source(struct gpio_chip *chip, unsigned int offset)
2900 if (offset >= chip->ngpio)
2903 return test_bit(FLAG_OPEN_SOURCE, &chip->gpiodev->descs[offset].flags);
2905 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_source);
2907 bool gpiochip_line_is_persistent(struct gpio_chip *chip, unsigned int offset)
2909 if (offset >= chip->ngpio)
2912 return !test_bit(FLAG_SLEEP_MAY_LOOSE_VALUE,
2913 &chip->gpiodev->descs[offset].flags);
2915 EXPORT_SYMBOL_GPL(gpiochip_line_is_persistent);
2918 * gpiod_get_raw_value_cansleep() - return a gpio's raw value
2919 * @desc: gpio whose value will be returned
2921 * Return the GPIO's raw value, i.e. the value of the physical line disregarding
2922 * its ACTIVE_LOW status, or negative errno on failure.
2924 * This function is to be called from contexts that can sleep.
2926 int gpiod_get_raw_value_cansleep(const struct gpio_desc *desc)
2928 might_sleep_if(extra_checks);
2929 VALIDATE_DESC(desc);
2930 return _gpiod_get_raw_value(desc);
2932 EXPORT_SYMBOL_GPL(gpiod_get_raw_value_cansleep);
2935 * gpiod_get_value_cansleep() - return a gpio's value
2936 * @desc: gpio whose value will be returned
2938 * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
2939 * account, or negative errno on failure.
2941 * This function is to be called from contexts that can sleep.
2943 int gpiod_get_value_cansleep(const struct gpio_desc *desc)
2947 might_sleep_if(extra_checks);
2948 VALIDATE_DESC(desc);
2949 value = _gpiod_get_raw_value(desc);
2953 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2958 EXPORT_SYMBOL_GPL(gpiod_get_value_cansleep);
2961 * gpiod_set_raw_value_cansleep() - assign a gpio's raw value
2962 * @desc: gpio whose value will be assigned
2963 * @value: value to assign
2965 * Set the raw value of the GPIO, i.e. the value of its physical line without
2966 * regard for its ACTIVE_LOW status.
2968 * This function is to be called from contexts that can sleep.
2970 void gpiod_set_raw_value_cansleep(struct gpio_desc *desc, int value)
2972 might_sleep_if(extra_checks);
2973 VALIDATE_DESC_VOID(desc);
2974 _gpiod_set_raw_value(desc, value);
2976 EXPORT_SYMBOL_GPL(gpiod_set_raw_value_cansleep);
2979 * gpiod_set_value_cansleep() - assign a gpio's value
2980 * @desc: gpio whose value will be assigned
2981 * @value: value to assign
2983 * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
2986 * This function is to be called from contexts that can sleep.
2988 void gpiod_set_value_cansleep(struct gpio_desc *desc, int value)
2990 might_sleep_if(extra_checks);
2991 VALIDATE_DESC_VOID(desc);
2992 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2994 _gpiod_set_raw_value(desc, value);
2996 EXPORT_SYMBOL_GPL(gpiod_set_value_cansleep);
2999 * gpiod_set_raw_array_value_cansleep() - assign values to an array of GPIOs
3000 * @array_size: number of elements in the descriptor / value arrays
3001 * @desc_array: array of GPIO descriptors whose values will be assigned
3002 * @value_array: array of values to assign
3004 * Set the raw values of the GPIOs, i.e. the values of the physical lines
3005 * without regard for their ACTIVE_LOW status.
3007 * This function is to be called from contexts that can sleep.
3009 void gpiod_set_raw_array_value_cansleep(unsigned int array_size,
3010 struct gpio_desc **desc_array,
3013 might_sleep_if(extra_checks);
3016 gpiod_set_array_value_complex(true, true, array_size, desc_array,
3019 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value_cansleep);
3022 * gpiod_add_lookup_tables() - register GPIO device consumers
3023 * @tables: list of tables of consumers to register
3024 * @n: number of tables in the list
3026 void gpiod_add_lookup_tables(struct gpiod_lookup_table **tables, size_t n)
3030 mutex_lock(&gpio_lookup_lock);
3032 for (i = 0; i < n; i++)
3033 list_add_tail(&tables[i]->list, &gpio_lookup_list);
3035 mutex_unlock(&gpio_lookup_lock);
3039 * gpiod_set_array_value_cansleep() - assign values to an array of GPIOs
3040 * @array_size: number of elements in the descriptor / value arrays
3041 * @desc_array: array of GPIO descriptors whose values will be assigned
3042 * @value_array: array of values to assign
3044 * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3047 * This function is to be called from contexts that can sleep.
3049 void gpiod_set_array_value_cansleep(unsigned int array_size,
3050 struct gpio_desc **desc_array,
3053 might_sleep_if(extra_checks);
3056 gpiod_set_array_value_complex(false, true, array_size, desc_array,
3059 EXPORT_SYMBOL_GPL(gpiod_set_array_value_cansleep);
3062 * gpiod_add_lookup_table() - register GPIO device consumers
3063 * @table: table of consumers to register
3065 void gpiod_add_lookup_table(struct gpiod_lookup_table *table)
3067 mutex_lock(&gpio_lookup_lock);
3069 list_add_tail(&table->list, &gpio_lookup_list);
3071 mutex_unlock(&gpio_lookup_lock);
3073 EXPORT_SYMBOL_GPL(gpiod_add_lookup_table);
3076 * gpiod_remove_lookup_table() - unregister GPIO device consumers
3077 * @table: table of consumers to unregister
3079 void gpiod_remove_lookup_table(struct gpiod_lookup_table *table)
3081 mutex_lock(&gpio_lookup_lock);
3083 list_del(&table->list);
3085 mutex_unlock(&gpio_lookup_lock);
3087 EXPORT_SYMBOL_GPL(gpiod_remove_lookup_table);
3089 static struct gpiod_lookup_table *gpiod_find_lookup_table(struct device *dev)
3091 const char *dev_id = dev ? dev_name(dev) : NULL;
3092 struct gpiod_lookup_table *table;
3094 mutex_lock(&gpio_lookup_lock);
3096 list_for_each_entry(table, &gpio_lookup_list, list) {
3097 if (table->dev_id && dev_id) {
3099 * Valid strings on both ends, must be identical to have
3102 if (!strcmp(table->dev_id, dev_id))
3106 * One of the pointers is NULL, so both must be to have
3109 if (dev_id == table->dev_id)
3116 mutex_unlock(&gpio_lookup_lock);
3120 static struct gpio_desc *gpiod_find(struct device *dev, const char *con_id,
3122 enum gpio_lookup_flags *flags)
3124 struct gpio_desc *desc = ERR_PTR(-ENOENT);
3125 struct gpiod_lookup_table *table;
3126 struct gpiod_lookup *p;
3128 table = gpiod_find_lookup_table(dev);
3132 for (p = &table->table[0]; p->chip_label; p++) {
3133 struct gpio_chip *chip;
3135 /* idx must always match exactly */
3139 /* If the lookup entry has a con_id, require exact match */
3140 if (p->con_id && (!con_id || strcmp(p->con_id, con_id)))
3143 chip = find_chip_by_name(p->chip_label);
3146 dev_err(dev, "cannot find GPIO chip %s\n",
3148 return ERR_PTR(-ENODEV);
3151 if (chip->ngpio <= p->chip_hwnum) {
3153 "requested GPIO %u (%u) is out of range [0..%u] for chip %s\n",
3154 idx, p->chip_hwnum, chip->ngpio - 1,
3156 return ERR_PTR(-EINVAL);
3159 desc = gpiochip_get_desc(chip, p->chip_hwnum);
3168 static int dt_gpio_count(struct device *dev, const char *con_id)
3174 for (i = 0; i < ARRAY_SIZE(gpio_suffixes); i++) {
3176 snprintf(propname, sizeof(propname), "%s-%s",
3177 con_id, gpio_suffixes[i]);
3179 snprintf(propname, sizeof(propname), "%s",
3182 ret = of_gpio_named_count(dev->of_node, propname);
3186 return ret ? ret : -ENOENT;
3189 static int platform_gpio_count(struct device *dev, const char *con_id)
3191 struct gpiod_lookup_table *table;
3192 struct gpiod_lookup *p;
3193 unsigned int count = 0;
3195 table = gpiod_find_lookup_table(dev);
3199 for (p = &table->table[0]; p->chip_label; p++) {
3200 if ((con_id && p->con_id && !strcmp(con_id, p->con_id)) ||
3201 (!con_id && !p->con_id))
3211 * gpiod_count - return the number of GPIOs associated with a device / function
3212 * or -ENOENT if no GPIO has been assigned to the requested function
3213 * @dev: GPIO consumer, can be NULL for system-global GPIOs
3214 * @con_id: function within the GPIO consumer
3216 int gpiod_count(struct device *dev, const char *con_id)
3218 int count = -ENOENT;
3220 if (IS_ENABLED(CONFIG_OF) && dev && dev->of_node)
3221 count = dt_gpio_count(dev, con_id);
3222 else if (IS_ENABLED(CONFIG_ACPI) && dev && ACPI_HANDLE(dev))
3223 count = acpi_gpio_count(dev, con_id);
3226 count = platform_gpio_count(dev, con_id);
3230 EXPORT_SYMBOL_GPL(gpiod_count);
3233 * gpiod_get - obtain a GPIO for a given GPIO function
3234 * @dev: GPIO consumer, can be NULL for system-global GPIOs
3235 * @con_id: function within the GPIO consumer
3236 * @flags: optional GPIO initialization flags
3238 * Return the GPIO descriptor corresponding to the function con_id of device
3239 * dev, -ENOENT if no GPIO has been assigned to the requested function, or
3240 * another IS_ERR() code if an error occurred while trying to acquire the GPIO.
3242 struct gpio_desc *__must_check gpiod_get(struct device *dev, const char *con_id,
3243 enum gpiod_flags flags)
3245 return gpiod_get_index(dev, con_id, 0, flags);
3247 EXPORT_SYMBOL_GPL(gpiod_get);
3250 * gpiod_get_optional - obtain an optional GPIO for a given GPIO function
3251 * @dev: GPIO consumer, can be NULL for system-global GPIOs
3252 * @con_id: function within the GPIO consumer
3253 * @flags: optional GPIO initialization flags
3255 * This is equivalent to gpiod_get(), except that when no GPIO was assigned to
3256 * the requested function it will return NULL. This is convenient for drivers
3257 * that need to handle optional GPIOs.
3259 struct gpio_desc *__must_check gpiod_get_optional(struct device *dev,
3261 enum gpiod_flags flags)
3263 return gpiod_get_index_optional(dev, con_id, 0, flags);
3265 EXPORT_SYMBOL_GPL(gpiod_get_optional);
3269 * gpiod_configure_flags - helper function to configure a given GPIO
3270 * @desc: gpio whose value will be assigned
3271 * @con_id: function within the GPIO consumer
3272 * @lflags: gpio_lookup_flags - returned from of_find_gpio() or
3274 * @dflags: gpiod_flags - optional GPIO initialization flags
3276 * Return 0 on success, -ENOENT if no GPIO has been assigned to the
3277 * requested function and/or index, or another IS_ERR() code if an error
3278 * occurred while trying to acquire the GPIO.
3280 int gpiod_configure_flags(struct gpio_desc *desc, const char *con_id,
3281 unsigned long lflags, enum gpiod_flags dflags)
3285 if (lflags & GPIO_ACTIVE_LOW)
3286 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
3287 if (lflags & GPIO_OPEN_DRAIN)
3288 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
3289 if (lflags & GPIO_OPEN_SOURCE)
3290 set_bit(FLAG_OPEN_SOURCE, &desc->flags);
3291 if (lflags & GPIO_SLEEP_MAY_LOOSE_VALUE)
3292 set_bit(FLAG_SLEEP_MAY_LOOSE_VALUE, &desc->flags);
3294 /* No particular flag request, return here... */
3295 if (!(dflags & GPIOD_FLAGS_BIT_DIR_SET)) {
3296 pr_debug("no flags found for %s\n", con_id);
3301 if (dflags & GPIOD_FLAGS_BIT_DIR_OUT)
3302 status = gpiod_direction_output(desc,
3303 !!(dflags & GPIOD_FLAGS_BIT_DIR_VAL));
3305 status = gpiod_direction_input(desc);
3311 * gpiod_get_index - obtain a GPIO from a multi-index GPIO function
3312 * @dev: GPIO consumer, can be NULL for system-global GPIOs
3313 * @con_id: function within the GPIO consumer
3314 * @idx: index of the GPIO to obtain in the consumer
3315 * @flags: optional GPIO initialization flags
3317 * This variant of gpiod_get() allows to access GPIOs other than the first
3318 * defined one for functions that define several GPIOs.
3320 * Return a valid GPIO descriptor, -ENOENT if no GPIO has been assigned to the
3321 * requested function and/or index, or another IS_ERR() code if an error
3322 * occurred while trying to acquire the GPIO.
3324 struct gpio_desc *__must_check gpiod_get_index(struct device *dev,
3327 enum gpiod_flags flags)
3329 struct gpio_desc *desc = NULL;
3331 enum gpio_lookup_flags lookupflags = 0;
3332 /* Maybe we have a device name, maybe not */
3333 const char *devname = dev ? dev_name(dev) : "?";
3335 dev_dbg(dev, "GPIO lookup for consumer %s\n", con_id);
3338 /* Using device tree? */
3339 if (IS_ENABLED(CONFIG_OF) && dev->of_node) {
3340 dev_dbg(dev, "using device tree for GPIO lookup\n");
3341 desc = of_find_gpio(dev, con_id, idx, &lookupflags);
3342 } else if (ACPI_COMPANION(dev)) {
3343 dev_dbg(dev, "using ACPI for GPIO lookup\n");
3344 desc = acpi_find_gpio(dev, con_id, idx, &flags, &lookupflags);
3349 * Either we are not using DT or ACPI, or their lookup did not return
3350 * a result. In that case, use platform lookup as a fallback.
3352 if (!desc || desc == ERR_PTR(-ENOENT)) {
3353 dev_dbg(dev, "using lookup tables for GPIO lookup\n");
3354 desc = gpiod_find(dev, con_id, idx, &lookupflags);
3358 dev_dbg(dev, "lookup for GPIO %s failed\n", con_id);
3363 * If a connection label was passed use that, else attempt to use
3364 * the device name as label
3366 status = gpiod_request(desc, con_id ? con_id : devname);
3368 return ERR_PTR(status);
3370 status = gpiod_configure_flags(desc, con_id, lookupflags, flags);
3372 dev_dbg(dev, "setup of GPIO %s failed\n", con_id);
3374 return ERR_PTR(status);
3379 EXPORT_SYMBOL_GPL(gpiod_get_index);
3382 * fwnode_get_named_gpiod - obtain a GPIO from firmware node
3383 * @fwnode: handle of the firmware node
3384 * @propname: name of the firmware property representing the GPIO
3385 * @index: index of the GPIO to obtain in the consumer
3386 * @dflags: GPIO initialization flags
3387 * @label: label to attach to the requested GPIO
3389 * This function can be used for drivers that get their configuration
3392 * Function properly finds the corresponding GPIO using whatever is the
3393 * underlying firmware interface and then makes sure that the GPIO
3394 * descriptor is requested before it is returned to the caller.
3397 * On successful request the GPIO pin is configured in accordance with
3400 * In case of error an ERR_PTR() is returned.
3402 struct gpio_desc *fwnode_get_named_gpiod(struct fwnode_handle *fwnode,
3403 const char *propname, int index,
3404 enum gpiod_flags dflags,
3407 struct gpio_desc *desc = ERR_PTR(-ENODEV);
3408 unsigned long lflags = 0;
3409 bool active_low = false;
3410 bool single_ended = false;
3411 bool open_drain = false;
3415 return ERR_PTR(-EINVAL);
3417 if (is_of_node(fwnode)) {
3418 enum of_gpio_flags flags;
3420 desc = of_get_named_gpiod_flags(to_of_node(fwnode), propname,
3422 if (!IS_ERR(desc)) {
3423 active_low = flags & OF_GPIO_ACTIVE_LOW;
3424 single_ended = flags & OF_GPIO_SINGLE_ENDED;
3425 open_drain = flags & OF_GPIO_OPEN_DRAIN;
3427 } else if (is_acpi_node(fwnode)) {
3428 struct acpi_gpio_info info;
3430 desc = acpi_node_get_gpiod(fwnode, propname, index, &info);
3431 if (!IS_ERR(desc)) {
3432 active_low = info.polarity == GPIO_ACTIVE_LOW;
3433 ret = acpi_gpio_update_gpiod_flags(&dflags, info.flags);
3435 pr_debug("Override GPIO initialization flags\n");
3442 ret = gpiod_request(desc, label);
3444 return ERR_PTR(ret);
3447 lflags |= GPIO_ACTIVE_LOW;
3451 lflags |= GPIO_OPEN_DRAIN;
3453 lflags |= GPIO_OPEN_SOURCE;
3456 ret = gpiod_configure_flags(desc, propname, lflags, dflags);
3459 return ERR_PTR(ret);
3464 EXPORT_SYMBOL_GPL(fwnode_get_named_gpiod);
3467 * gpiod_get_index_optional - obtain an optional GPIO from a multi-index GPIO
3469 * @dev: GPIO consumer, can be NULL for system-global GPIOs
3470 * @con_id: function within the GPIO consumer
3471 * @index: index of the GPIO to obtain in the consumer
3472 * @flags: optional GPIO initialization flags
3474 * This is equivalent to gpiod_get_index(), except that when no GPIO with the
3475 * specified index was assigned to the requested function it will return NULL.
3476 * This is convenient for drivers that need to handle optional GPIOs.
3478 struct gpio_desc *__must_check gpiod_get_index_optional(struct device *dev,
3481 enum gpiod_flags flags)
3483 struct gpio_desc *desc;
3485 desc = gpiod_get_index(dev, con_id, index, flags);
3487 if (PTR_ERR(desc) == -ENOENT)
3493 EXPORT_SYMBOL_GPL(gpiod_get_index_optional);
3496 * gpiod_hog - Hog the specified GPIO desc given the provided flags
3497 * @desc: gpio whose value will be assigned
3498 * @name: gpio line name
3499 * @lflags: gpio_lookup_flags - returned from of_find_gpio() or
3501 * @dflags: gpiod_flags - optional GPIO initialization flags
3503 int gpiod_hog(struct gpio_desc *desc, const char *name,
3504 unsigned long lflags, enum gpiod_flags dflags)
3506 struct gpio_chip *chip;
3507 struct gpio_desc *local_desc;
3511 chip = gpiod_to_chip(desc);
3512 hwnum = gpio_chip_hwgpio(desc);
3514 local_desc = gpiochip_request_own_desc(chip, hwnum, name);
3515 if (IS_ERR(local_desc)) {
3516 status = PTR_ERR(local_desc);
3517 pr_err("requesting hog GPIO %s (chip %s, offset %d) failed, %d\n",
3518 name, chip->label, hwnum, status);
3522 status = gpiod_configure_flags(desc, name, lflags, dflags);
3524 pr_err("setup of hog GPIO %s (chip %s, offset %d) failed, %d\n",
3525 name, chip->label, hwnum, status);
3526 gpiochip_free_own_desc(desc);
3530 /* Mark GPIO as hogged so it can be identified and removed later */
3531 set_bit(FLAG_IS_HOGGED, &desc->flags);
3533 pr_info("GPIO line %d (%s) hogged as %s%s\n",
3534 desc_to_gpio(desc), name,
3535 (dflags&GPIOD_FLAGS_BIT_DIR_OUT) ? "output" : "input",
3536 (dflags&GPIOD_FLAGS_BIT_DIR_OUT) ?
3537 (dflags&GPIOD_FLAGS_BIT_DIR_VAL) ? "/high" : "/low":"");
3543 * gpiochip_free_hogs - Scan gpio-controller chip and release GPIO hog
3544 * @chip: gpio chip to act on
3546 * This is only used by of_gpiochip_remove to free hogged gpios
3548 static void gpiochip_free_hogs(struct gpio_chip *chip)
3552 for (id = 0; id < chip->ngpio; id++) {
3553 if (test_bit(FLAG_IS_HOGGED, &chip->gpiodev->descs[id].flags))
3554 gpiochip_free_own_desc(&chip->gpiodev->descs[id]);
3559 * gpiod_get_array - obtain multiple GPIOs from a multi-index GPIO function
3560 * @dev: GPIO consumer, can be NULL for system-global GPIOs
3561 * @con_id: function within the GPIO consumer
3562 * @flags: optional GPIO initialization flags
3564 * This function acquires all the GPIOs defined under a given function.
3566 * Return a struct gpio_descs containing an array of descriptors, -ENOENT if
3567 * no GPIO has been assigned to the requested function, or another IS_ERR()
3568 * code if an error occurred while trying to acquire the GPIOs.
3570 struct gpio_descs *__must_check gpiod_get_array(struct device *dev,
3572 enum gpiod_flags flags)
3574 struct gpio_desc *desc;
3575 struct gpio_descs *descs;
3578 count = gpiod_count(dev, con_id);
3580 return ERR_PTR(count);
3582 descs = kzalloc(sizeof(*descs) + sizeof(descs->desc[0]) * count,
3585 return ERR_PTR(-ENOMEM);
3587 for (descs->ndescs = 0; descs->ndescs < count; ) {
3588 desc = gpiod_get_index(dev, con_id, descs->ndescs, flags);
3590 gpiod_put_array(descs);
3591 return ERR_CAST(desc);
3593 descs->desc[descs->ndescs] = desc;
3598 EXPORT_SYMBOL_GPL(gpiod_get_array);
3601 * gpiod_get_array_optional - obtain multiple GPIOs from a multi-index GPIO
3603 * @dev: GPIO consumer, can be NULL for system-global GPIOs
3604 * @con_id: function within the GPIO consumer
3605 * @flags: optional GPIO initialization flags
3607 * This is equivalent to gpiod_get_array(), except that when no GPIO was
3608 * assigned to the requested function it will return NULL.
3610 struct gpio_descs *__must_check gpiod_get_array_optional(struct device *dev,
3612 enum gpiod_flags flags)
3614 struct gpio_descs *descs;
3616 descs = gpiod_get_array(dev, con_id, flags);
3617 if (IS_ERR(descs) && (PTR_ERR(descs) == -ENOENT))
3622 EXPORT_SYMBOL_GPL(gpiod_get_array_optional);
3625 * gpiod_put - dispose of a GPIO descriptor
3626 * @desc: GPIO descriptor to dispose of
3628 * No descriptor can be used after gpiod_put() has been called on it.
3630 void gpiod_put(struct gpio_desc *desc)
3634 EXPORT_SYMBOL_GPL(gpiod_put);
3637 * gpiod_put_array - dispose of multiple GPIO descriptors
3638 * @descs: struct gpio_descs containing an array of descriptors
3640 void gpiod_put_array(struct gpio_descs *descs)
3644 for (i = 0; i < descs->ndescs; i++)
3645 gpiod_put(descs->desc[i]);
3649 EXPORT_SYMBOL_GPL(gpiod_put_array);
3651 static int __init gpiolib_dev_init(void)
3655 /* Register GPIO sysfs bus */
3656 ret = bus_register(&gpio_bus_type);
3658 pr_err("gpiolib: could not register GPIO bus type\n");
3662 ret = alloc_chrdev_region(&gpio_devt, 0, GPIO_DEV_MAX, "gpiochip");
3664 pr_err("gpiolib: failed to allocate char dev region\n");
3665 bus_unregister(&gpio_bus_type);
3667 gpiolib_initialized = true;
3668 gpiochip_setup_devs();
3672 core_initcall(gpiolib_dev_init);
3674 #ifdef CONFIG_DEBUG_FS
3676 static void gpiolib_dbg_show(struct seq_file *s, struct gpio_device *gdev)
3679 struct gpio_chip *chip = gdev->chip;
3680 unsigned gpio = gdev->base;
3681 struct gpio_desc *gdesc = &gdev->descs[0];
3685 for (i = 0; i < gdev->ngpio; i++, gpio++, gdesc++) {
3686 if (!test_bit(FLAG_REQUESTED, &gdesc->flags)) {
3688 seq_printf(s, " gpio-%-3d (%-20.20s)\n",
3694 gpiod_get_direction(gdesc);
3695 is_out = test_bit(FLAG_IS_OUT, &gdesc->flags);
3696 is_irq = test_bit(FLAG_USED_AS_IRQ, &gdesc->flags);
3697 seq_printf(s, " gpio-%-3d (%-20.20s|%-20.20s) %s %s %s",
3698 gpio, gdesc->name ? gdesc->name : "", gdesc->label,
3699 is_out ? "out" : "in ",
3701 ? (chip->get(chip, i) ? "hi" : "lo")
3703 is_irq ? "IRQ" : " ");
3704 seq_printf(s, "\n");
3708 static void *gpiolib_seq_start(struct seq_file *s, loff_t *pos)
3710 unsigned long flags;
3711 struct gpio_device *gdev = NULL;
3712 loff_t index = *pos;
3716 spin_lock_irqsave(&gpio_lock, flags);
3717 list_for_each_entry(gdev, &gpio_devices, list)
3719 spin_unlock_irqrestore(&gpio_lock, flags);
3722 spin_unlock_irqrestore(&gpio_lock, flags);
3727 static void *gpiolib_seq_next(struct seq_file *s, void *v, loff_t *pos)
3729 unsigned long flags;
3730 struct gpio_device *gdev = v;
3733 spin_lock_irqsave(&gpio_lock, flags);
3734 if (list_is_last(&gdev->list, &gpio_devices))
3737 ret = list_entry(gdev->list.next, struct gpio_device, list);
3738 spin_unlock_irqrestore(&gpio_lock, flags);
3746 static void gpiolib_seq_stop(struct seq_file *s, void *v)
3750 static int gpiolib_seq_show(struct seq_file *s, void *v)
3752 struct gpio_device *gdev = v;
3753 struct gpio_chip *chip = gdev->chip;
3754 struct device *parent;
3757 seq_printf(s, "%s%s: (dangling chip)", (char *)s->private,
3758 dev_name(&gdev->dev));
3762 seq_printf(s, "%s%s: GPIOs %d-%d", (char *)s->private,
3763 dev_name(&gdev->dev),
3764 gdev->base, gdev->base + gdev->ngpio - 1);
3765 parent = chip->parent;
3767 seq_printf(s, ", parent: %s/%s",
3768 parent->bus ? parent->bus->name : "no-bus",
3771 seq_printf(s, ", %s", chip->label);
3772 if (chip->can_sleep)
3773 seq_printf(s, ", can sleep");
3774 seq_printf(s, ":\n");
3777 chip->dbg_show(s, chip);
3779 gpiolib_dbg_show(s, gdev);
3784 static const struct seq_operations gpiolib_seq_ops = {
3785 .start = gpiolib_seq_start,
3786 .next = gpiolib_seq_next,
3787 .stop = gpiolib_seq_stop,
3788 .show = gpiolib_seq_show,
3791 static int gpiolib_open(struct inode *inode, struct file *file)
3793 return seq_open(file, &gpiolib_seq_ops);
3796 static const struct file_operations gpiolib_operations = {
3797 .owner = THIS_MODULE,
3798 .open = gpiolib_open,
3800 .llseek = seq_lseek,
3801 .release = seq_release,
3804 static int __init gpiolib_debugfs_init(void)
3806 /* /sys/kernel/debug/gpio */
3807 (void) debugfs_create_file("gpio", S_IFREG | S_IRUGO,
3808 NULL, NULL, &gpiolib_operations);
3811 subsys_initcall(gpiolib_debugfs_init);
3813 #endif /* DEBUG_FS */