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 int gpiochip_add_irqchip(struct gpio_chip *gpiochip,
76 struct lock_class_key *key);
77 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip);
78 static int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gpiochip);
79 static void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gpiochip);
81 static bool gpiolib_initialized;
83 static inline void desc_set_label(struct gpio_desc *d, const char *label)
89 * gpio_to_desc - Convert a GPIO number to its descriptor
90 * @gpio: global GPIO number
93 * The GPIO descriptor associated with the given GPIO, or %NULL if no GPIO
94 * with the given number exists in the system.
96 struct gpio_desc *gpio_to_desc(unsigned gpio)
98 struct gpio_device *gdev;
101 spin_lock_irqsave(&gpio_lock, flags);
103 list_for_each_entry(gdev, &gpio_devices, list) {
104 if (gdev->base <= gpio &&
105 gdev->base + gdev->ngpio > gpio) {
106 spin_unlock_irqrestore(&gpio_lock, flags);
107 return &gdev->descs[gpio - gdev->base];
111 spin_unlock_irqrestore(&gpio_lock, flags);
113 if (!gpio_is_valid(gpio))
114 WARN(1, "invalid GPIO %d\n", gpio);
118 EXPORT_SYMBOL_GPL(gpio_to_desc);
121 * gpiochip_get_desc - get the GPIO descriptor corresponding to the given
122 * hardware number for this chip
124 * @hwnum: hardware number of the GPIO for this chip
127 * A pointer to the GPIO descriptor or %ERR_PTR(-EINVAL) if no GPIO exists
128 * in the given chip for the specified hardware number.
130 struct gpio_desc *gpiochip_get_desc(struct gpio_chip *chip,
133 struct gpio_device *gdev = chip->gpiodev;
135 if (hwnum >= gdev->ngpio)
136 return ERR_PTR(-EINVAL);
138 return &gdev->descs[hwnum];
142 * desc_to_gpio - convert a GPIO descriptor to the integer namespace
143 * @desc: GPIO descriptor
145 * This should disappear in the future but is needed since we still
146 * use GPIO numbers for error messages and sysfs nodes.
149 * The global GPIO number for the GPIO specified by its descriptor.
151 int desc_to_gpio(const struct gpio_desc *desc)
153 return desc->gdev->base + (desc - &desc->gdev->descs[0]);
155 EXPORT_SYMBOL_GPL(desc_to_gpio);
159 * gpiod_to_chip - Return the GPIO chip to which a GPIO descriptor belongs
160 * @desc: descriptor to return the chip of
162 struct gpio_chip *gpiod_to_chip(const struct gpio_desc *desc)
164 if (!desc || !desc->gdev || !desc->gdev->chip)
166 return desc->gdev->chip;
168 EXPORT_SYMBOL_GPL(gpiod_to_chip);
170 /* dynamic allocation of GPIOs, e.g. on a hotplugged device */
171 static int gpiochip_find_base(int ngpio)
173 struct gpio_device *gdev;
174 int base = ARCH_NR_GPIOS - ngpio;
176 list_for_each_entry_reverse(gdev, &gpio_devices, list) {
177 /* found a free space? */
178 if (gdev->base + gdev->ngpio <= base)
181 /* nope, check the space right before the chip */
182 base = gdev->base - ngpio;
185 if (gpio_is_valid(base)) {
186 pr_debug("%s: found new base at %d\n", __func__, base);
189 pr_err("%s: cannot find free range\n", __func__);
195 * gpiod_get_direction - return the current direction of a GPIO
196 * @desc: GPIO to get the direction of
198 * Return GPIOF_DIR_IN or GPIOF_DIR_OUT, or an error code in case of error.
200 * This function may sleep if gpiod_cansleep() is true.
202 int gpiod_get_direction(struct gpio_desc *desc)
204 struct gpio_chip *chip;
206 int status = -EINVAL;
208 chip = gpiod_to_chip(desc);
209 offset = gpio_chip_hwgpio(desc);
211 if (!chip->get_direction)
214 status = chip->get_direction(chip, offset);
216 /* GPIOF_DIR_IN, or other positive */
218 clear_bit(FLAG_IS_OUT, &desc->flags);
222 set_bit(FLAG_IS_OUT, &desc->flags);
226 EXPORT_SYMBOL_GPL(gpiod_get_direction);
229 * Add a new chip to the global chips list, keeping the list of chips sorted
230 * by range(means [base, base + ngpio - 1]) order.
232 * Return -EBUSY if the new chip overlaps with some other chip's integer
235 static int gpiodev_add_to_list(struct gpio_device *gdev)
237 struct gpio_device *prev, *next;
239 if (list_empty(&gpio_devices)) {
240 /* initial entry in list */
241 list_add_tail(&gdev->list, &gpio_devices);
245 next = list_entry(gpio_devices.next, struct gpio_device, list);
246 if (gdev->base + gdev->ngpio <= next->base) {
247 /* add before first entry */
248 list_add(&gdev->list, &gpio_devices);
252 prev = list_entry(gpio_devices.prev, struct gpio_device, list);
253 if (prev->base + prev->ngpio <= gdev->base) {
254 /* add behind last entry */
255 list_add_tail(&gdev->list, &gpio_devices);
259 list_for_each_entry_safe(prev, next, &gpio_devices, list) {
260 /* at the end of the list */
261 if (&next->list == &gpio_devices)
264 /* add between prev and next */
265 if (prev->base + prev->ngpio <= gdev->base
266 && gdev->base + gdev->ngpio <= next->base) {
267 list_add(&gdev->list, &prev->list);
272 dev_err(&gdev->dev, "GPIO integer space overlap, cannot add chip\n");
277 * Convert a GPIO name to its descriptor
279 static struct gpio_desc *gpio_name_to_desc(const char * const name)
281 struct gpio_device *gdev;
284 spin_lock_irqsave(&gpio_lock, flags);
286 list_for_each_entry(gdev, &gpio_devices, list) {
289 for (i = 0; i != gdev->ngpio; ++i) {
290 struct gpio_desc *desc = &gdev->descs[i];
292 if (!desc->name || !name)
295 if (!strcmp(desc->name, name)) {
296 spin_unlock_irqrestore(&gpio_lock, flags);
302 spin_unlock_irqrestore(&gpio_lock, flags);
308 * Takes the names from gc->names and checks if they are all unique. If they
309 * are, they are assigned to their gpio descriptors.
311 * Warning if one of the names is already used for a different GPIO.
313 static int gpiochip_set_desc_names(struct gpio_chip *gc)
315 struct gpio_device *gdev = gc->gpiodev;
321 /* First check all names if they are unique */
322 for (i = 0; i != gc->ngpio; ++i) {
323 struct gpio_desc *gpio;
325 gpio = gpio_name_to_desc(gc->names[i]);
328 "Detected name collision for GPIO name '%s'\n",
332 /* Then add all names to the GPIO descriptors */
333 for (i = 0; i != gc->ngpio; ++i)
334 gdev->descs[i].name = gc->names[i];
340 * GPIO line handle management
344 * struct linehandle_state - contains the state of a userspace handle
345 * @gdev: the GPIO device the handle pertains to
346 * @label: consumer label used to tag descriptors
347 * @descs: the GPIO descriptors held by this handle
348 * @numdescs: the number of descriptors held in the descs array
350 struct linehandle_state {
351 struct gpio_device *gdev;
353 struct gpio_desc *descs[GPIOHANDLES_MAX];
357 #define GPIOHANDLE_REQUEST_VALID_FLAGS \
358 (GPIOHANDLE_REQUEST_INPUT | \
359 GPIOHANDLE_REQUEST_OUTPUT | \
360 GPIOHANDLE_REQUEST_ACTIVE_LOW | \
361 GPIOHANDLE_REQUEST_OPEN_DRAIN | \
362 GPIOHANDLE_REQUEST_OPEN_SOURCE)
364 static long linehandle_ioctl(struct file *filep, unsigned int cmd,
367 struct linehandle_state *lh = filep->private_data;
368 void __user *ip = (void __user *)arg;
369 struct gpiohandle_data ghd;
370 int vals[GPIOHANDLES_MAX];
373 if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
374 /* TODO: check if descriptors are really input */
375 int ret = gpiod_get_array_value_complex(false,
383 memset(&ghd, 0, sizeof(ghd));
384 for (i = 0; i < lh->numdescs; i++)
385 ghd.values[i] = vals[i];
387 if (copy_to_user(ip, &ghd, sizeof(ghd)))
391 } else if (cmd == GPIOHANDLE_SET_LINE_VALUES_IOCTL) {
392 /* TODO: check if descriptors are really output */
393 if (copy_from_user(&ghd, ip, sizeof(ghd)))
396 /* Clamp all values to [0,1] */
397 for (i = 0; i < lh->numdescs; i++)
398 vals[i] = !!ghd.values[i];
400 /* Reuse the array setting function */
401 gpiod_set_array_value_complex(false,
412 static long linehandle_ioctl_compat(struct file *filep, unsigned int cmd,
415 return linehandle_ioctl(filep, cmd, (unsigned long)compat_ptr(arg));
419 static int linehandle_release(struct inode *inode, struct file *filep)
421 struct linehandle_state *lh = filep->private_data;
422 struct gpio_device *gdev = lh->gdev;
425 for (i = 0; i < lh->numdescs; i++)
426 gpiod_free(lh->descs[i]);
429 put_device(&gdev->dev);
433 static const struct file_operations linehandle_fileops = {
434 .release = linehandle_release,
435 .owner = THIS_MODULE,
436 .llseek = noop_llseek,
437 .unlocked_ioctl = linehandle_ioctl,
439 .compat_ioctl = linehandle_ioctl_compat,
443 static int linehandle_create(struct gpio_device *gdev, void __user *ip)
445 struct gpiohandle_request handlereq;
446 struct linehandle_state *lh;
451 if (copy_from_user(&handlereq, ip, sizeof(handlereq)))
453 if ((handlereq.lines == 0) || (handlereq.lines > GPIOHANDLES_MAX))
456 lflags = handlereq.flags;
458 /* Return an error if an unknown flag is set */
459 if (lflags & ~GPIOHANDLE_REQUEST_VALID_FLAGS)
462 /* OPEN_DRAIN and OPEN_SOURCE flags only make sense for output mode. */
463 if (!(lflags & GPIOHANDLE_REQUEST_OUTPUT) &&
464 ((lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN) ||
465 (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE)))
468 lh = kzalloc(sizeof(*lh), GFP_KERNEL);
472 get_device(&gdev->dev);
474 /* Make sure this is terminated */
475 handlereq.consumer_label[sizeof(handlereq.consumer_label)-1] = '\0';
476 if (strlen(handlereq.consumer_label)) {
477 lh->label = kstrdup(handlereq.consumer_label,
485 /* Request each GPIO */
486 for (i = 0; i < handlereq.lines; i++) {
487 u32 offset = handlereq.lineoffsets[i];
488 struct gpio_desc *desc;
490 if (offset >= gdev->ngpio) {
495 desc = &gdev->descs[offset];
496 ret = gpiod_request(desc, lh->label);
501 if (lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW)
502 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
503 if (lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN)
504 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
505 if (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE)
506 set_bit(FLAG_OPEN_SOURCE, &desc->flags);
509 * Lines have to be requested explicitly for input
510 * or output, else the line will be treated "as is".
512 if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
513 int val = !!handlereq.default_values[i];
515 ret = gpiod_direction_output(desc, val);
518 } else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
519 ret = gpiod_direction_input(desc);
523 dev_dbg(&gdev->dev, "registered chardev handle for line %d\n",
526 /* Let i point at the last handle */
528 lh->numdescs = handlereq.lines;
530 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
536 file = anon_inode_getfile("gpio-linehandle",
539 O_RDONLY | O_CLOEXEC);
542 goto out_put_unused_fd;
546 if (copy_to_user(ip, &handlereq, sizeof(handlereq))) {
548 * fput() will trigger the release() callback, so do not go onto
549 * the regular error cleanup path here.
556 fd_install(fd, file);
558 dev_dbg(&gdev->dev, "registered chardev handle for %d lines\n",
567 gpiod_free(lh->descs[i]);
571 put_device(&gdev->dev);
576 * GPIO line event management
580 * struct lineevent_state - contains the state of a userspace event
581 * @gdev: the GPIO device the event pertains to
582 * @label: consumer label used to tag descriptors
583 * @desc: the GPIO descriptor held by this event
584 * @eflags: the event flags this line was requested with
585 * @irq: the interrupt that trigger in response to events on this GPIO
586 * @wait: wait queue that handles blocking reads of events
587 * @events: KFIFO for the GPIO events
588 * @read_lock: mutex lock to protect reads from colliding with adding
589 * new events to the FIFO
591 struct lineevent_state {
592 struct gpio_device *gdev;
594 struct gpio_desc *desc;
597 wait_queue_head_t wait;
598 DECLARE_KFIFO(events, struct gpioevent_data, 16);
599 struct mutex read_lock;
602 #define GPIOEVENT_REQUEST_VALID_FLAGS \
603 (GPIOEVENT_REQUEST_RISING_EDGE | \
604 GPIOEVENT_REQUEST_FALLING_EDGE)
606 static unsigned int lineevent_poll(struct file *filep,
607 struct poll_table_struct *wait)
609 struct lineevent_state *le = filep->private_data;
610 unsigned int events = 0;
612 poll_wait(filep, &le->wait, wait);
614 if (!kfifo_is_empty(&le->events))
615 events = POLLIN | POLLRDNORM;
621 static ssize_t lineevent_read(struct file *filep,
626 struct lineevent_state *le = filep->private_data;
630 if (count < sizeof(struct gpioevent_data))
634 if (kfifo_is_empty(&le->events)) {
635 if (filep->f_flags & O_NONBLOCK)
638 ret = wait_event_interruptible(le->wait,
639 !kfifo_is_empty(&le->events));
644 if (mutex_lock_interruptible(&le->read_lock))
646 ret = kfifo_to_user(&le->events, buf, count, &copied);
647 mutex_unlock(&le->read_lock);
653 * If we couldn't read anything from the fifo (a different
654 * thread might have been faster) we either return -EAGAIN if
655 * the file descriptor is non-blocking, otherwise we go back to
656 * sleep and wait for more data to arrive.
658 if (copied == 0 && (filep->f_flags & O_NONBLOCK))
661 } while (copied == 0);
666 static int lineevent_release(struct inode *inode, struct file *filep)
668 struct lineevent_state *le = filep->private_data;
669 struct gpio_device *gdev = le->gdev;
671 free_irq(le->irq, le);
672 gpiod_free(le->desc);
675 put_device(&gdev->dev);
679 static long lineevent_ioctl(struct file *filep, unsigned int cmd,
682 struct lineevent_state *le = filep->private_data;
683 void __user *ip = (void __user *)arg;
684 struct gpiohandle_data ghd;
687 * We can get the value for an event line but not set it,
688 * because it is input by definition.
690 if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
693 memset(&ghd, 0, sizeof(ghd));
695 val = gpiod_get_value_cansleep(le->desc);
700 if (copy_to_user(ip, &ghd, sizeof(ghd)))
709 static long lineevent_ioctl_compat(struct file *filep, unsigned int cmd,
712 return lineevent_ioctl(filep, cmd, (unsigned long)compat_ptr(arg));
716 static const struct file_operations lineevent_fileops = {
717 .release = lineevent_release,
718 .read = lineevent_read,
719 .poll = lineevent_poll,
720 .owner = THIS_MODULE,
721 .llseek = noop_llseek,
722 .unlocked_ioctl = lineevent_ioctl,
724 .compat_ioctl = lineevent_ioctl_compat,
728 static irqreturn_t lineevent_irq_thread(int irq, void *p)
730 struct lineevent_state *le = p;
731 struct gpioevent_data ge;
734 ge.timestamp = ktime_get_real_ns();
735 level = gpiod_get_value_cansleep(le->desc);
737 if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE
738 && le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
740 /* Emit low-to-high event */
741 ge.id = GPIOEVENT_EVENT_RISING_EDGE;
743 /* Emit high-to-low event */
744 ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
745 } else if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE && level) {
746 /* Emit low-to-high event */
747 ge.id = GPIOEVENT_EVENT_RISING_EDGE;
748 } else if (le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE && !level) {
749 /* Emit high-to-low event */
750 ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
755 ret = kfifo_put(&le->events, ge);
757 wake_up_poll(&le->wait, POLLIN);
762 static int lineevent_create(struct gpio_device *gdev, void __user *ip)
764 struct gpioevent_request eventreq;
765 struct lineevent_state *le;
766 struct gpio_desc *desc;
775 if (copy_from_user(&eventreq, ip, sizeof(eventreq)))
778 le = kzalloc(sizeof(*le), GFP_KERNEL);
782 get_device(&gdev->dev);
784 /* Make sure this is terminated */
785 eventreq.consumer_label[sizeof(eventreq.consumer_label)-1] = '\0';
786 if (strlen(eventreq.consumer_label)) {
787 le->label = kstrdup(eventreq.consumer_label,
795 offset = eventreq.lineoffset;
796 lflags = eventreq.handleflags;
797 eflags = eventreq.eventflags;
799 if (offset >= gdev->ngpio) {
804 /* Return an error if a unknown flag is set */
805 if ((lflags & ~GPIOHANDLE_REQUEST_VALID_FLAGS) ||
806 (eflags & ~GPIOEVENT_REQUEST_VALID_FLAGS)) {
811 /* This is just wrong: we don't look for events on output lines */
812 if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
817 desc = &gdev->descs[offset];
818 ret = gpiod_request(desc, le->label);
824 if (lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW)
825 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
826 if (lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN)
827 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
828 if (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE)
829 set_bit(FLAG_OPEN_SOURCE, &desc->flags);
831 ret = gpiod_direction_input(desc);
835 le->irq = gpiod_to_irq(desc);
841 if (eflags & GPIOEVENT_REQUEST_RISING_EDGE)
842 irqflags |= IRQF_TRIGGER_RISING;
843 if (eflags & GPIOEVENT_REQUEST_FALLING_EDGE)
844 irqflags |= IRQF_TRIGGER_FALLING;
845 irqflags |= IRQF_ONESHOT;
846 irqflags |= IRQF_SHARED;
848 INIT_KFIFO(le->events);
849 init_waitqueue_head(&le->wait);
850 mutex_init(&le->read_lock);
852 /* Request a thread to read the events */
853 ret = request_threaded_irq(le->irq,
855 lineevent_irq_thread,
862 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
868 file = anon_inode_getfile("gpio-event",
871 O_RDONLY | O_CLOEXEC);
874 goto out_put_unused_fd;
878 if (copy_to_user(ip, &eventreq, sizeof(eventreq))) {
880 * fput() will trigger the release() callback, so do not go onto
881 * the regular error cleanup path here.
888 fd_install(fd, file);
895 free_irq(le->irq, le);
897 gpiod_free(le->desc);
902 put_device(&gdev->dev);
907 * gpio_ioctl() - ioctl handler for the GPIO chardev
909 static long gpio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
911 struct gpio_device *gdev = filp->private_data;
912 struct gpio_chip *chip = gdev->chip;
913 void __user *ip = (void __user *)arg;
915 /* We fail any subsequent ioctl():s when the chip is gone */
919 /* Fill in the struct and pass to userspace */
920 if (cmd == GPIO_GET_CHIPINFO_IOCTL) {
921 struct gpiochip_info chipinfo;
923 memset(&chipinfo, 0, sizeof(chipinfo));
925 strncpy(chipinfo.name, dev_name(&gdev->dev),
926 sizeof(chipinfo.name));
927 chipinfo.name[sizeof(chipinfo.name)-1] = '\0';
928 strncpy(chipinfo.label, gdev->label,
929 sizeof(chipinfo.label));
930 chipinfo.label[sizeof(chipinfo.label)-1] = '\0';
931 chipinfo.lines = gdev->ngpio;
932 if (copy_to_user(ip, &chipinfo, sizeof(chipinfo)))
935 } else if (cmd == GPIO_GET_LINEINFO_IOCTL) {
936 struct gpioline_info lineinfo;
937 struct gpio_desc *desc;
939 if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
941 if (lineinfo.line_offset >= gdev->ngpio)
944 desc = &gdev->descs[lineinfo.line_offset];
946 strncpy(lineinfo.name, desc->name,
947 sizeof(lineinfo.name));
948 lineinfo.name[sizeof(lineinfo.name)-1] = '\0';
950 lineinfo.name[0] = '\0';
953 strncpy(lineinfo.consumer, desc->label,
954 sizeof(lineinfo.consumer));
955 lineinfo.consumer[sizeof(lineinfo.consumer)-1] = '\0';
957 lineinfo.consumer[0] = '\0';
961 * Userspace only need to know that the kernel is using
962 * this GPIO so it can't use it.
965 if (test_bit(FLAG_REQUESTED, &desc->flags) ||
966 test_bit(FLAG_IS_HOGGED, &desc->flags) ||
967 test_bit(FLAG_USED_AS_IRQ, &desc->flags) ||
968 test_bit(FLAG_EXPORT, &desc->flags) ||
969 test_bit(FLAG_SYSFS, &desc->flags))
970 lineinfo.flags |= GPIOLINE_FLAG_KERNEL;
971 if (test_bit(FLAG_IS_OUT, &desc->flags))
972 lineinfo.flags |= GPIOLINE_FLAG_IS_OUT;
973 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
974 lineinfo.flags |= GPIOLINE_FLAG_ACTIVE_LOW;
975 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
976 lineinfo.flags |= GPIOLINE_FLAG_OPEN_DRAIN;
977 if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
978 lineinfo.flags |= GPIOLINE_FLAG_OPEN_SOURCE;
980 if (copy_to_user(ip, &lineinfo, sizeof(lineinfo)))
983 } else if (cmd == GPIO_GET_LINEHANDLE_IOCTL) {
984 return linehandle_create(gdev, ip);
985 } else if (cmd == GPIO_GET_LINEEVENT_IOCTL) {
986 return lineevent_create(gdev, ip);
992 static long gpio_ioctl_compat(struct file *filp, unsigned int cmd,
995 return gpio_ioctl(filp, cmd, (unsigned long)compat_ptr(arg));
1000 * gpio_chrdev_open() - open the chardev for ioctl operations
1001 * @inode: inode for this chardev
1002 * @filp: file struct for storing private data
1003 * Returns 0 on success
1005 static int gpio_chrdev_open(struct inode *inode, struct file *filp)
1007 struct gpio_device *gdev = container_of(inode->i_cdev,
1008 struct gpio_device, chrdev);
1010 /* Fail on open if the backing gpiochip is gone */
1013 get_device(&gdev->dev);
1014 filp->private_data = gdev;
1016 return nonseekable_open(inode, filp);
1020 * gpio_chrdev_release() - close chardev after ioctl operations
1021 * @inode: inode for this chardev
1022 * @filp: file struct for storing private data
1023 * Returns 0 on success
1025 static int gpio_chrdev_release(struct inode *inode, struct file *filp)
1027 struct gpio_device *gdev = container_of(inode->i_cdev,
1028 struct gpio_device, chrdev);
1030 put_device(&gdev->dev);
1035 static const struct file_operations gpio_fileops = {
1036 .release = gpio_chrdev_release,
1037 .open = gpio_chrdev_open,
1038 .owner = THIS_MODULE,
1039 .llseek = no_llseek,
1040 .unlocked_ioctl = gpio_ioctl,
1041 #ifdef CONFIG_COMPAT
1042 .compat_ioctl = gpio_ioctl_compat,
1046 static void gpiodevice_release(struct device *dev)
1048 struct gpio_device *gdev = dev_get_drvdata(dev);
1050 list_del(&gdev->list);
1051 ida_simple_remove(&gpio_ida, gdev->id);
1057 static int gpiochip_setup_dev(struct gpio_device *gdev)
1061 cdev_init(&gdev->chrdev, &gpio_fileops);
1062 gdev->chrdev.owner = THIS_MODULE;
1063 gdev->dev.devt = MKDEV(MAJOR(gpio_devt), gdev->id);
1065 status = cdev_device_add(&gdev->chrdev, &gdev->dev);
1069 chip_dbg(gdev->chip, "added GPIO chardev (%d:%d)\n",
1070 MAJOR(gpio_devt), gdev->id);
1072 status = gpiochip_sysfs_register(gdev);
1074 goto err_remove_device;
1076 /* From this point, the .release() function cleans up gpio_device */
1077 gdev->dev.release = gpiodevice_release;
1078 pr_debug("%s: registered GPIOs %d to %d on device: %s (%s)\n",
1079 __func__, gdev->base, gdev->base + gdev->ngpio - 1,
1080 dev_name(&gdev->dev), gdev->chip->label ? : "generic");
1085 cdev_device_del(&gdev->chrdev, &gdev->dev);
1089 static void gpiochip_setup_devs(void)
1091 struct gpio_device *gdev;
1094 list_for_each_entry(gdev, &gpio_devices, list) {
1095 err = gpiochip_setup_dev(gdev);
1097 pr_err("%s: Failed to initialize gpio device (%d)\n",
1098 dev_name(&gdev->dev), err);
1102 int gpiochip_add_data_with_key(struct gpio_chip *chip, void *data,
1103 struct lock_class_key *key)
1105 unsigned long flags;
1108 int base = chip->base;
1109 struct gpio_device *gdev;
1112 * First: allocate and populate the internal stat container, and
1113 * set up the struct device.
1115 gdev = kzalloc(sizeof(*gdev), GFP_KERNEL);
1118 gdev->dev.bus = &gpio_bus_type;
1120 chip->gpiodev = gdev;
1122 gdev->dev.parent = chip->parent;
1123 gdev->dev.of_node = chip->parent->of_node;
1126 #ifdef CONFIG_OF_GPIO
1127 /* If the gpiochip has an assigned OF node this takes precedence */
1129 gdev->dev.of_node = chip->of_node;
1132 gdev->id = ida_simple_get(&gpio_ida, 0, 0, GFP_KERNEL);
1137 dev_set_name(&gdev->dev, "gpiochip%d", gdev->id);
1138 device_initialize(&gdev->dev);
1139 dev_set_drvdata(&gdev->dev, gdev);
1140 if (chip->parent && chip->parent->driver)
1141 gdev->owner = chip->parent->driver->owner;
1142 else if (chip->owner)
1143 /* TODO: remove chip->owner */
1144 gdev->owner = chip->owner;
1146 gdev->owner = THIS_MODULE;
1148 gdev->descs = kcalloc(chip->ngpio, sizeof(gdev->descs[0]), GFP_KERNEL);
1154 if (chip->ngpio == 0) {
1155 chip_err(chip, "tried to insert a GPIO chip with zero lines\n");
1157 goto err_free_descs;
1161 gdev->label = kstrdup(chip->label, GFP_KERNEL);
1163 gdev->label = kstrdup("unknown", GFP_KERNEL);
1166 goto err_free_descs;
1169 gdev->ngpio = chip->ngpio;
1172 spin_lock_irqsave(&gpio_lock, flags);
1175 * TODO: this allocates a Linux GPIO number base in the global
1176 * GPIO numberspace for this chip. In the long run we want to
1177 * get *rid* of this numberspace and use only descriptors, but
1178 * it may be a pipe dream. It will not happen before we get rid
1179 * of the sysfs interface anyways.
1182 base = gpiochip_find_base(chip->ngpio);
1185 spin_unlock_irqrestore(&gpio_lock, flags);
1186 goto err_free_label;
1189 * TODO: it should not be necessary to reflect the assigned
1190 * base outside of the GPIO subsystem. Go over drivers and
1191 * see if anyone makes use of this, else drop this and assign
1198 status = gpiodev_add_to_list(gdev);
1200 spin_unlock_irqrestore(&gpio_lock, flags);
1201 goto err_free_label;
1204 spin_unlock_irqrestore(&gpio_lock, flags);
1206 for (i = 0; i < chip->ngpio; i++) {
1207 struct gpio_desc *desc = &gdev->descs[i];
1211 * REVISIT: most hardware initializes GPIOs as inputs
1212 * (often with pullups enabled) so power usage is
1213 * minimized. Linux code should set the gpio direction
1214 * first thing; but until it does, and in case
1215 * chip->get_direction is not set, we may expose the
1216 * wrong direction in sysfs.
1219 if (chip->get_direction) {
1221 * If we have .get_direction, set up the initial
1222 * direction flag from the hardware.
1224 int dir = chip->get_direction(chip, i);
1227 set_bit(FLAG_IS_OUT, &desc->flags);
1228 } else if (!chip->direction_input) {
1230 * If the chip lacks the .direction_input callback
1231 * we logically assume all lines are outputs.
1233 set_bit(FLAG_IS_OUT, &desc->flags);
1237 #ifdef CONFIG_PINCTRL
1238 INIT_LIST_HEAD(&gdev->pin_ranges);
1241 status = gpiochip_set_desc_names(chip);
1243 goto err_remove_from_list;
1245 status = gpiochip_irqchip_init_valid_mask(chip);
1247 goto err_remove_from_list;
1249 status = gpiochip_add_irqchip(chip, key);
1251 goto err_remove_chip;
1253 status = of_gpiochip_add(chip);
1255 goto err_remove_chip;
1257 acpi_gpiochip_add(chip);
1260 * By first adding the chardev, and then adding the device,
1261 * we get a device node entry in sysfs under
1262 * /sys/bus/gpio/devices/gpiochipN/dev that can be used for
1263 * coldplug of device nodes and other udev business.
1264 * We can do this only if gpiolib has been initialized.
1265 * Otherwise, defer until later.
1267 if (gpiolib_initialized) {
1268 status = gpiochip_setup_dev(gdev);
1270 goto err_remove_chip;
1275 acpi_gpiochip_remove(chip);
1276 gpiochip_free_hogs(chip);
1277 of_gpiochip_remove(chip);
1278 gpiochip_irqchip_free_valid_mask(chip);
1279 err_remove_from_list:
1280 spin_lock_irqsave(&gpio_lock, flags);
1281 list_del(&gdev->list);
1282 spin_unlock_irqrestore(&gpio_lock, flags);
1288 ida_simple_remove(&gpio_ida, gdev->id);
1289 /* failures here can mean systems won't boot... */
1290 pr_err("%s: GPIOs %d..%d (%s) failed to register\n", __func__,
1291 gdev->base, gdev->base + gdev->ngpio - 1,
1292 chip->label ? : "generic");
1296 EXPORT_SYMBOL_GPL(gpiochip_add_data_with_key);
1299 * gpiochip_get_data() - get per-subdriver data for the chip
1303 * The per-subdriver data for the chip.
1305 void *gpiochip_get_data(struct gpio_chip *chip)
1307 return chip->gpiodev->data;
1309 EXPORT_SYMBOL_GPL(gpiochip_get_data);
1312 * gpiochip_remove() - unregister a gpio_chip
1313 * @chip: the chip to unregister
1315 * A gpio_chip with any GPIOs still requested may not be removed.
1317 void gpiochip_remove(struct gpio_chip *chip)
1319 struct gpio_device *gdev = chip->gpiodev;
1320 struct gpio_desc *desc;
1321 unsigned long flags;
1323 bool requested = false;
1325 /* FIXME: should the legacy sysfs handling be moved to gpio_device? */
1326 gpiochip_sysfs_unregister(gdev);
1327 gpiochip_free_hogs(chip);
1328 /* Numb the device, cancelling all outstanding operations */
1330 gpiochip_irqchip_remove(chip);
1331 acpi_gpiochip_remove(chip);
1332 gpiochip_remove_pin_ranges(chip);
1333 of_gpiochip_remove(chip);
1335 * We accept no more calls into the driver from this point, so
1336 * NULL the driver data pointer
1340 spin_lock_irqsave(&gpio_lock, flags);
1341 for (i = 0; i < gdev->ngpio; i++) {
1342 desc = &gdev->descs[i];
1343 if (test_bit(FLAG_REQUESTED, &desc->flags))
1346 spin_unlock_irqrestore(&gpio_lock, flags);
1349 dev_crit(&gdev->dev,
1350 "REMOVING GPIOCHIP WITH GPIOS STILL REQUESTED\n");
1353 * The gpiochip side puts its use of the device to rest here:
1354 * if there are no userspace clients, the chardev and device will
1355 * be removed, else it will be dangling until the last user is
1358 cdev_device_del(&gdev->chrdev, &gdev->dev);
1359 put_device(&gdev->dev);
1361 EXPORT_SYMBOL_GPL(gpiochip_remove);
1363 static void devm_gpio_chip_release(struct device *dev, void *res)
1365 struct gpio_chip *chip = *(struct gpio_chip **)res;
1367 gpiochip_remove(chip);
1370 static int devm_gpio_chip_match(struct device *dev, void *res, void *data)
1373 struct gpio_chip **r = res;
1384 * devm_gpiochip_add_data() - Resource manager piochip_add_data()
1385 * @dev: the device pointer on which irq_chip belongs to.
1386 * @chip: the chip to register, with chip->base initialized
1387 * @data: driver-private data associated with this chip
1389 * Context: potentially before irqs will work
1391 * The gpio chip automatically be released when the device is unbound.
1394 * A negative errno if the chip can't be registered, such as because the
1395 * chip->base is invalid or already associated with a different chip.
1396 * Otherwise it returns zero as a success code.
1398 int devm_gpiochip_add_data(struct device *dev, struct gpio_chip *chip,
1401 struct gpio_chip **ptr;
1404 ptr = devres_alloc(devm_gpio_chip_release, sizeof(*ptr),
1409 ret = gpiochip_add_data(chip, data);
1416 devres_add(dev, ptr);
1420 EXPORT_SYMBOL_GPL(devm_gpiochip_add_data);
1423 * devm_gpiochip_remove() - Resource manager of gpiochip_remove()
1424 * @dev: device for which which resource was allocated
1425 * @chip: the chip to remove
1427 * A gpio_chip with any GPIOs still requested may not be removed.
1429 void devm_gpiochip_remove(struct device *dev, struct gpio_chip *chip)
1433 ret = devres_release(dev, devm_gpio_chip_release,
1434 devm_gpio_chip_match, chip);
1437 EXPORT_SYMBOL_GPL(devm_gpiochip_remove);
1440 * gpiochip_find() - iterator for locating a specific gpio_chip
1441 * @data: data to pass to match function
1442 * @match: Callback function to check gpio_chip
1444 * Similar to bus_find_device. It returns a reference to a gpio_chip as
1445 * determined by a user supplied @match callback. The callback should return
1446 * 0 if the device doesn't match and non-zero if it does. If the callback is
1447 * non-zero, this function will return to the caller and not iterate over any
1450 struct gpio_chip *gpiochip_find(void *data,
1451 int (*match)(struct gpio_chip *chip,
1454 struct gpio_device *gdev;
1455 struct gpio_chip *chip = NULL;
1456 unsigned long flags;
1458 spin_lock_irqsave(&gpio_lock, flags);
1459 list_for_each_entry(gdev, &gpio_devices, list)
1460 if (gdev->chip && match(gdev->chip, data)) {
1465 spin_unlock_irqrestore(&gpio_lock, flags);
1469 EXPORT_SYMBOL_GPL(gpiochip_find);
1471 static int gpiochip_match_name(struct gpio_chip *chip, void *data)
1473 const char *name = data;
1475 return !strcmp(chip->label, name);
1478 static struct gpio_chip *find_chip_by_name(const char *name)
1480 return gpiochip_find((void *)name, gpiochip_match_name);
1483 #ifdef CONFIG_GPIOLIB_IRQCHIP
1486 * The following is irqchip helper code for gpiochips.
1489 static int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gpiochip)
1491 if (!gpiochip->irq.need_valid_mask)
1494 gpiochip->irq.valid_mask = kcalloc(BITS_TO_LONGS(gpiochip->ngpio),
1495 sizeof(long), GFP_KERNEL);
1496 if (!gpiochip->irq.valid_mask)
1499 /* Assume by default all GPIOs are valid */
1500 bitmap_fill(gpiochip->irq.valid_mask, gpiochip->ngpio);
1505 static void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gpiochip)
1507 kfree(gpiochip->irq.valid_mask);
1508 gpiochip->irq.valid_mask = NULL;
1511 static bool gpiochip_irqchip_irq_valid(const struct gpio_chip *gpiochip,
1512 unsigned int offset)
1514 /* No mask means all valid */
1515 if (likely(!gpiochip->irq.valid_mask))
1517 return test_bit(offset, gpiochip->irq.valid_mask);
1521 * gpiochip_set_cascaded_irqchip() - connects a cascaded irqchip to a gpiochip
1522 * @gpiochip: the gpiochip to set the irqchip chain to
1523 * @irqchip: the irqchip to chain to the gpiochip
1524 * @parent_irq: the irq number corresponding to the parent IRQ for this
1526 * @parent_handler: the parent interrupt handler for the accumulated IRQ
1527 * coming out of the gpiochip. If the interrupt is nested rather than
1528 * cascaded, pass NULL in this handler argument
1530 static void gpiochip_set_cascaded_irqchip(struct gpio_chip *gpiochip,
1531 struct irq_chip *irqchip,
1532 unsigned int parent_irq,
1533 irq_flow_handler_t parent_handler)
1535 unsigned int offset;
1537 if (!gpiochip->irq.domain) {
1538 chip_err(gpiochip, "called %s before setting up irqchip\n",
1543 if (parent_handler) {
1544 if (gpiochip->can_sleep) {
1546 "you cannot have chained interrupts on a "
1547 "chip that may sleep\n");
1551 * The parent irqchip is already using the chip_data for this
1552 * irqchip, so our callbacks simply use the handler_data.
1554 irq_set_chained_handler_and_data(parent_irq, parent_handler,
1557 gpiochip->irq.parents = &parent_irq;
1558 gpiochip->irq.num_parents = 1;
1561 /* Set the parent IRQ for all affected IRQs */
1562 for (offset = 0; offset < gpiochip->ngpio; offset++) {
1563 if (!gpiochip_irqchip_irq_valid(gpiochip, offset))
1565 irq_set_parent(irq_find_mapping(gpiochip->irq.domain, offset),
1571 * gpiochip_set_chained_irqchip() - connects a chained irqchip to a gpiochip
1572 * @gpiochip: the gpiochip to set the irqchip chain to
1573 * @irqchip: the irqchip to chain to the gpiochip
1574 * @parent_irq: the irq number corresponding to the parent IRQ for this
1576 * @parent_handler: the parent interrupt handler for the accumulated IRQ
1577 * coming out of the gpiochip. If the interrupt is nested rather than
1578 * cascaded, pass NULL in this handler argument
1580 void gpiochip_set_chained_irqchip(struct gpio_chip *gpiochip,
1581 struct irq_chip *irqchip,
1582 unsigned int parent_irq,
1583 irq_flow_handler_t parent_handler)
1585 if (gpiochip->irq.threaded) {
1586 chip_err(gpiochip, "tried to chain a threaded gpiochip\n");
1590 gpiochip_set_cascaded_irqchip(gpiochip, irqchip, parent_irq,
1593 EXPORT_SYMBOL_GPL(gpiochip_set_chained_irqchip);
1596 * gpiochip_set_nested_irqchip() - connects a nested irqchip to a gpiochip
1597 * @gpiochip: the gpiochip to set the irqchip nested handler to
1598 * @irqchip: the irqchip to nest to the gpiochip
1599 * @parent_irq: the irq number corresponding to the parent IRQ for this
1602 void gpiochip_set_nested_irqchip(struct gpio_chip *gpiochip,
1603 struct irq_chip *irqchip,
1604 unsigned int parent_irq)
1606 gpiochip_set_cascaded_irqchip(gpiochip, irqchip, parent_irq,
1609 EXPORT_SYMBOL_GPL(gpiochip_set_nested_irqchip);
1612 * gpiochip_irq_map() - maps an IRQ into a GPIO irqchip
1613 * @d: the irqdomain used by this irqchip
1614 * @irq: the global irq number used by this GPIO irqchip irq
1615 * @hwirq: the local IRQ/GPIO line offset on this gpiochip
1617 * This function will set up the mapping for a certain IRQ line on a
1618 * gpiochip by assigning the gpiochip as chip data, and using the irqchip
1619 * stored inside the gpiochip.
1621 int gpiochip_irq_map(struct irq_domain *d, unsigned int irq,
1622 irq_hw_number_t hwirq)
1624 struct gpio_chip *chip = d->host_data;
1627 if (!gpiochip_irqchip_irq_valid(chip, hwirq))
1630 irq_set_chip_data(irq, chip);
1632 * This lock class tells lockdep that GPIO irqs are in a different
1633 * category than their parents, so it won't report false recursion.
1635 irq_set_lockdep_class(irq, chip->irq.lock_key);
1636 irq_set_chip_and_handler(irq, chip->irq.chip, chip->irq.handler);
1637 /* Chips that use nested thread handlers have them marked */
1638 if (chip->irq.threaded)
1639 irq_set_nested_thread(irq, 1);
1640 irq_set_noprobe(irq);
1642 if (chip->irq.num_parents == 1)
1643 err = irq_set_parent(irq, chip->irq.parents[0]);
1644 else if (chip->irq.map)
1645 err = irq_set_parent(irq, chip->irq.map[hwirq]);
1651 * No set-up of the hardware will happen if IRQ_TYPE_NONE
1652 * is passed as default type.
1654 if (chip->irq.default_type != IRQ_TYPE_NONE)
1655 irq_set_irq_type(irq, chip->irq.default_type);
1659 EXPORT_SYMBOL_GPL(gpiochip_irq_map);
1661 void gpiochip_irq_unmap(struct irq_domain *d, unsigned int irq)
1663 struct gpio_chip *chip = d->host_data;
1665 if (chip->irq.threaded)
1666 irq_set_nested_thread(irq, 0);
1667 irq_set_chip_and_handler(irq, NULL, NULL);
1668 irq_set_chip_data(irq, NULL);
1670 EXPORT_SYMBOL_GPL(gpiochip_irq_unmap);
1672 static const struct irq_domain_ops gpiochip_domain_ops = {
1673 .map = gpiochip_irq_map,
1674 .unmap = gpiochip_irq_unmap,
1675 /* Virtually all GPIO irqchips are twocell:ed */
1676 .xlate = irq_domain_xlate_twocell,
1679 static int gpiochip_irq_reqres(struct irq_data *d)
1681 struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
1683 if (!try_module_get(chip->gpiodev->owner))
1686 if (gpiochip_lock_as_irq(chip, d->hwirq)) {
1688 "unable to lock HW IRQ %lu for IRQ\n",
1690 module_put(chip->gpiodev->owner);
1696 static void gpiochip_irq_relres(struct irq_data *d)
1698 struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
1700 gpiochip_unlock_as_irq(chip, d->hwirq);
1701 module_put(chip->gpiodev->owner);
1704 static int gpiochip_to_irq(struct gpio_chip *chip, unsigned offset)
1706 if (!gpiochip_irqchip_irq_valid(chip, offset))
1709 return irq_create_mapping(chip->irq.domain, offset);
1713 * gpiochip_add_irqchip() - adds an IRQ chip to a GPIO chip
1714 * @gpiochip: the GPIO chip to add the IRQ chip to
1715 * @lock_key: lockdep class
1717 static int gpiochip_add_irqchip(struct gpio_chip *gpiochip,
1718 struct lock_class_key *lock_key)
1720 struct irq_chip *irqchip = gpiochip->irq.chip;
1721 const struct irq_domain_ops *ops;
1722 struct device_node *np;
1729 if (gpiochip->irq.parent_handler && gpiochip->can_sleep) {
1730 chip_err(gpiochip, "you cannot have chained interrupts on a "
1731 "chip that may sleep\n");
1735 np = gpiochip->gpiodev->dev.of_node;
1736 type = gpiochip->irq.default_type;
1739 * Specifying a default trigger is a terrible idea if DT or ACPI is
1740 * used to configure the interrupts, as you may end up with
1741 * conflicting triggers. Tell the user, and reset to NONE.
1743 if (WARN(np && type != IRQ_TYPE_NONE,
1744 "%s: Ignoring %u default trigger\n", np->full_name, type))
1745 type = IRQ_TYPE_NONE;
1747 if (has_acpi_companion(gpiochip->parent) && type != IRQ_TYPE_NONE) {
1748 acpi_handle_warn(ACPI_HANDLE(gpiochip->parent),
1749 "Ignoring %u default trigger\n", type);
1750 type = IRQ_TYPE_NONE;
1753 gpiochip->to_irq = gpiochip_to_irq;
1754 gpiochip->irq.default_type = type;
1755 gpiochip->irq.lock_key = lock_key;
1757 if (gpiochip->irq.domain_ops)
1758 ops = gpiochip->irq.domain_ops;
1760 ops = &gpiochip_domain_ops;
1762 gpiochip->irq.domain = irq_domain_add_simple(np, gpiochip->ngpio,
1763 gpiochip->irq.first,
1765 if (!gpiochip->irq.domain)
1769 * It is possible for a driver to override this, but only if the
1770 * alternative functions are both implemented.
1772 if (!irqchip->irq_request_resources &&
1773 !irqchip->irq_release_resources) {
1774 irqchip->irq_request_resources = gpiochip_irq_reqres;
1775 irqchip->irq_release_resources = gpiochip_irq_relres;
1778 if (gpiochip->irq.parent_handler) {
1779 void *data = gpiochip->irq.parent_handler_data ?: gpiochip;
1781 for (i = 0; i < gpiochip->irq.num_parents; i++) {
1783 * The parent IRQ chip is already using the chip_data
1784 * for this IRQ chip, so our callbacks simply use the
1787 irq_set_chained_handler_and_data(gpiochip->irq.parents[i],
1788 gpiochip->irq.parent_handler,
1793 acpi_gpiochip_request_interrupts(gpiochip);
1799 * gpiochip_irqchip_remove() - removes an irqchip added to a gpiochip
1800 * @gpiochip: the gpiochip to remove the irqchip from
1802 * This is called only from gpiochip_remove()
1804 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip)
1806 unsigned int offset;
1808 acpi_gpiochip_free_interrupts(gpiochip);
1810 if (gpiochip->irq.chip && gpiochip->irq.parent_handler) {
1811 struct gpio_irq_chip *irq = &gpiochip->irq;
1814 for (i = 0; i < irq->num_parents; i++)
1815 irq_set_chained_handler_and_data(irq->parents[i],
1819 /* Remove all IRQ mappings and delete the domain */
1820 if (gpiochip->irq.domain) {
1823 for (offset = 0; offset < gpiochip->ngpio; offset++) {
1824 if (!gpiochip_irqchip_irq_valid(gpiochip, offset))
1827 irq = irq_find_mapping(gpiochip->irq.domain, offset);
1828 irq_dispose_mapping(irq);
1831 irq_domain_remove(gpiochip->irq.domain);
1834 if (gpiochip->irq.chip) {
1835 gpiochip->irq.chip->irq_request_resources = NULL;
1836 gpiochip->irq.chip->irq_release_resources = NULL;
1837 gpiochip->irq.chip = NULL;
1840 gpiochip_irqchip_free_valid_mask(gpiochip);
1844 * gpiochip_irqchip_add_key() - adds an irqchip to a gpiochip
1845 * @gpiochip: the gpiochip to add the irqchip to
1846 * @irqchip: the irqchip to add to the gpiochip
1847 * @first_irq: if not dynamically assigned, the base (first) IRQ to
1848 * allocate gpiochip irqs from
1849 * @handler: the irq handler to use (often a predefined irq core function)
1850 * @type: the default type for IRQs on this irqchip, pass IRQ_TYPE_NONE
1851 * to have the core avoid setting up any default type in the hardware.
1852 * @threaded: whether this irqchip uses a nested thread handler
1853 * @lock_key: lockdep class
1855 * This function closely associates a certain irqchip with a certain
1856 * gpiochip, providing an irq domain to translate the local IRQs to
1857 * global irqs in the gpiolib core, and making sure that the gpiochip
1858 * is passed as chip data to all related functions. Driver callbacks
1859 * need to use gpiochip_get_data() to get their local state containers back
1860 * from the gpiochip passed as chip data. An irqdomain will be stored
1861 * in the gpiochip that shall be used by the driver to handle IRQ number
1862 * translation. The gpiochip will need to be initialized and registered
1863 * before calling this function.
1865 * This function will handle two cell:ed simple IRQs and assumes all
1866 * the pins on the gpiochip can generate a unique IRQ. Everything else
1867 * need to be open coded.
1869 int gpiochip_irqchip_add_key(struct gpio_chip *gpiochip,
1870 struct irq_chip *irqchip,
1871 unsigned int first_irq,
1872 irq_flow_handler_t handler,
1875 struct lock_class_key *lock_key)
1877 struct device_node *of_node;
1879 if (!gpiochip || !irqchip)
1882 if (!gpiochip->parent) {
1883 pr_err("missing gpiochip .dev parent pointer\n");
1886 gpiochip->irq.threaded = threaded;
1887 of_node = gpiochip->parent->of_node;
1888 #ifdef CONFIG_OF_GPIO
1890 * If the gpiochip has an assigned OF node this takes precedence
1891 * FIXME: get rid of this and use gpiochip->parent->of_node
1894 if (gpiochip->of_node)
1895 of_node = gpiochip->of_node;
1898 * Specifying a default trigger is a terrible idea if DT or ACPI is
1899 * used to configure the interrupts, as you may end-up with
1900 * conflicting triggers. Tell the user, and reset to NONE.
1902 if (WARN(of_node && type != IRQ_TYPE_NONE,
1903 "%pOF: Ignoring %d default trigger\n", of_node, type))
1904 type = IRQ_TYPE_NONE;
1905 if (has_acpi_companion(gpiochip->parent) && type != IRQ_TYPE_NONE) {
1906 acpi_handle_warn(ACPI_HANDLE(gpiochip->parent),
1907 "Ignoring %d default trigger\n", type);
1908 type = IRQ_TYPE_NONE;
1911 gpiochip->irq.chip = irqchip;
1912 gpiochip->irq.handler = handler;
1913 gpiochip->irq.default_type = type;
1914 gpiochip->to_irq = gpiochip_to_irq;
1915 gpiochip->irq.lock_key = lock_key;
1916 gpiochip->irq.domain = irq_domain_add_simple(of_node,
1917 gpiochip->ngpio, first_irq,
1918 &gpiochip_domain_ops, gpiochip);
1919 if (!gpiochip->irq.domain) {
1920 gpiochip->irq.chip = NULL;
1925 * It is possible for a driver to override this, but only if the
1926 * alternative functions are both implemented.
1928 if (!irqchip->irq_request_resources &&
1929 !irqchip->irq_release_resources) {
1930 irqchip->irq_request_resources = gpiochip_irq_reqres;
1931 irqchip->irq_release_resources = gpiochip_irq_relres;
1934 acpi_gpiochip_request_interrupts(gpiochip);
1938 EXPORT_SYMBOL_GPL(gpiochip_irqchip_add_key);
1940 #else /* CONFIG_GPIOLIB_IRQCHIP */
1942 static inline int gpiochip_add_irqchip(struct gpio_chip *gpiochip,
1943 struct lock_class_key *key)
1948 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip) {}
1949 static inline int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gpiochip)
1953 static inline void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gpiochip)
1956 #endif /* CONFIG_GPIOLIB_IRQCHIP */
1959 * gpiochip_generic_request() - request the gpio function for a pin
1960 * @chip: the gpiochip owning the GPIO
1961 * @offset: the offset of the GPIO to request for GPIO function
1963 int gpiochip_generic_request(struct gpio_chip *chip, unsigned offset)
1965 return pinctrl_request_gpio(chip->gpiodev->base + offset);
1967 EXPORT_SYMBOL_GPL(gpiochip_generic_request);
1970 * gpiochip_generic_free() - free the gpio function from a pin
1971 * @chip: the gpiochip to request the gpio function for
1972 * @offset: the offset of the GPIO to free from GPIO function
1974 void gpiochip_generic_free(struct gpio_chip *chip, unsigned offset)
1976 pinctrl_free_gpio(chip->gpiodev->base + offset);
1978 EXPORT_SYMBOL_GPL(gpiochip_generic_free);
1981 * gpiochip_generic_config() - apply configuration for a pin
1982 * @chip: the gpiochip owning the GPIO
1983 * @offset: the offset of the GPIO to apply the configuration
1984 * @config: the configuration to be applied
1986 int gpiochip_generic_config(struct gpio_chip *chip, unsigned offset,
1987 unsigned long config)
1989 return pinctrl_gpio_set_config(chip->gpiodev->base + offset, config);
1991 EXPORT_SYMBOL_GPL(gpiochip_generic_config);
1993 #ifdef CONFIG_PINCTRL
1996 * gpiochip_add_pingroup_range() - add a range for GPIO <-> pin mapping
1997 * @chip: the gpiochip to add the range for
1998 * @pctldev: the pin controller to map to
1999 * @gpio_offset: the start offset in the current gpio_chip number space
2000 * @pin_group: name of the pin group inside the pin controller
2002 int gpiochip_add_pingroup_range(struct gpio_chip *chip,
2003 struct pinctrl_dev *pctldev,
2004 unsigned int gpio_offset, const char *pin_group)
2006 struct gpio_pin_range *pin_range;
2007 struct gpio_device *gdev = chip->gpiodev;
2010 pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
2012 chip_err(chip, "failed to allocate pin ranges\n");
2016 /* Use local offset as range ID */
2017 pin_range->range.id = gpio_offset;
2018 pin_range->range.gc = chip;
2019 pin_range->range.name = chip->label;
2020 pin_range->range.base = gdev->base + gpio_offset;
2021 pin_range->pctldev = pctldev;
2023 ret = pinctrl_get_group_pins(pctldev, pin_group,
2024 &pin_range->range.pins,
2025 &pin_range->range.npins);
2031 pinctrl_add_gpio_range(pctldev, &pin_range->range);
2033 chip_dbg(chip, "created GPIO range %d->%d ==> %s PINGRP %s\n",
2034 gpio_offset, gpio_offset + pin_range->range.npins - 1,
2035 pinctrl_dev_get_devname(pctldev), pin_group);
2037 list_add_tail(&pin_range->node, &gdev->pin_ranges);
2041 EXPORT_SYMBOL_GPL(gpiochip_add_pingroup_range);
2044 * gpiochip_add_pin_range() - add a range for GPIO <-> pin mapping
2045 * @chip: the gpiochip to add the range for
2046 * @pinctl_name: the dev_name() of the pin controller to map to
2047 * @gpio_offset: the start offset in the current gpio_chip number space
2048 * @pin_offset: the start offset in the pin controller number space
2049 * @npins: the number of pins from the offset of each pin space (GPIO and
2050 * pin controller) to accumulate in this range
2053 * 0 on success, or a negative error-code on failure.
2055 int gpiochip_add_pin_range(struct gpio_chip *chip, const char *pinctl_name,
2056 unsigned int gpio_offset, unsigned int pin_offset,
2059 struct gpio_pin_range *pin_range;
2060 struct gpio_device *gdev = chip->gpiodev;
2063 pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
2065 chip_err(chip, "failed to allocate pin ranges\n");
2069 /* Use local offset as range ID */
2070 pin_range->range.id = gpio_offset;
2071 pin_range->range.gc = chip;
2072 pin_range->range.name = chip->label;
2073 pin_range->range.base = gdev->base + gpio_offset;
2074 pin_range->range.pin_base = pin_offset;
2075 pin_range->range.npins = npins;
2076 pin_range->pctldev = pinctrl_find_and_add_gpio_range(pinctl_name,
2078 if (IS_ERR(pin_range->pctldev)) {
2079 ret = PTR_ERR(pin_range->pctldev);
2080 chip_err(chip, "could not create pin range\n");
2084 chip_dbg(chip, "created GPIO range %d->%d ==> %s PIN %d->%d\n",
2085 gpio_offset, gpio_offset + npins - 1,
2087 pin_offset, pin_offset + npins - 1);
2089 list_add_tail(&pin_range->node, &gdev->pin_ranges);
2093 EXPORT_SYMBOL_GPL(gpiochip_add_pin_range);
2096 * gpiochip_remove_pin_ranges() - remove all the GPIO <-> pin mappings
2097 * @chip: the chip to remove all the mappings for
2099 void gpiochip_remove_pin_ranges(struct gpio_chip *chip)
2101 struct gpio_pin_range *pin_range, *tmp;
2102 struct gpio_device *gdev = chip->gpiodev;
2104 list_for_each_entry_safe(pin_range, tmp, &gdev->pin_ranges, node) {
2105 list_del(&pin_range->node);
2106 pinctrl_remove_gpio_range(pin_range->pctldev,
2111 EXPORT_SYMBOL_GPL(gpiochip_remove_pin_ranges);
2113 #endif /* CONFIG_PINCTRL */
2115 /* These "optional" allocation calls help prevent drivers from stomping
2116 * on each other, and help provide better diagnostics in debugfs.
2117 * They're called even less than the "set direction" calls.
2119 static int gpiod_request_commit(struct gpio_desc *desc, const char *label)
2121 struct gpio_chip *chip = desc->gdev->chip;
2123 unsigned long flags;
2125 spin_lock_irqsave(&gpio_lock, flags);
2127 /* NOTE: gpio_request() can be called in early boot,
2128 * before IRQs are enabled, for non-sleeping (SOC) GPIOs.
2131 if (test_and_set_bit(FLAG_REQUESTED, &desc->flags) == 0) {
2132 desc_set_label(desc, label ? : "?");
2139 if (chip->request) {
2140 /* chip->request may sleep */
2141 spin_unlock_irqrestore(&gpio_lock, flags);
2142 status = chip->request(chip, gpio_chip_hwgpio(desc));
2143 spin_lock_irqsave(&gpio_lock, flags);
2146 desc_set_label(desc, NULL);
2147 clear_bit(FLAG_REQUESTED, &desc->flags);
2151 if (chip->get_direction) {
2152 /* chip->get_direction may sleep */
2153 spin_unlock_irqrestore(&gpio_lock, flags);
2154 gpiod_get_direction(desc);
2155 spin_lock_irqsave(&gpio_lock, flags);
2158 spin_unlock_irqrestore(&gpio_lock, flags);
2163 * This descriptor validation needs to be inserted verbatim into each
2164 * function taking a descriptor, so we need to use a preprocessor
2165 * macro to avoid endless duplication. If the desc is NULL it is an
2166 * optional GPIO and calls should just bail out.
2168 #define VALIDATE_DESC(desc) do { \
2171 if (IS_ERR(desc)) { \
2172 pr_warn("%s: invalid GPIO (errorpointer)\n", __func__); \
2173 return PTR_ERR(desc); \
2175 if (!desc->gdev) { \
2176 pr_warn("%s: invalid GPIO (no device)\n", __func__); \
2179 if ( !desc->gdev->chip ) { \
2180 dev_warn(&desc->gdev->dev, \
2181 "%s: backing chip is gone\n", __func__); \
2185 #define VALIDATE_DESC_VOID(desc) do { \
2188 if (IS_ERR(desc)) { \
2189 pr_warn("%s: invalid GPIO (errorpointer)\n", __func__); \
2192 if (!desc->gdev) { \
2193 pr_warn("%s: invalid GPIO (no device)\n", __func__); \
2196 if (!desc->gdev->chip) { \
2197 dev_warn(&desc->gdev->dev, \
2198 "%s: backing chip is gone\n", __func__); \
2203 int gpiod_request(struct gpio_desc *desc, const char *label)
2205 int status = -EPROBE_DEFER;
2206 struct gpio_device *gdev;
2208 VALIDATE_DESC(desc);
2211 if (try_module_get(gdev->owner)) {
2212 status = gpiod_request_commit(desc, label);
2214 module_put(gdev->owner);
2216 get_device(&gdev->dev);
2220 gpiod_dbg(desc, "%s: status %d\n", __func__, status);
2225 static bool gpiod_free_commit(struct gpio_desc *desc)
2228 unsigned long flags;
2229 struct gpio_chip *chip;
2233 gpiod_unexport(desc);
2235 spin_lock_irqsave(&gpio_lock, flags);
2237 chip = desc->gdev->chip;
2238 if (chip && test_bit(FLAG_REQUESTED, &desc->flags)) {
2240 spin_unlock_irqrestore(&gpio_lock, flags);
2241 might_sleep_if(chip->can_sleep);
2242 chip->free(chip, gpio_chip_hwgpio(desc));
2243 spin_lock_irqsave(&gpio_lock, flags);
2245 desc_set_label(desc, NULL);
2246 clear_bit(FLAG_ACTIVE_LOW, &desc->flags);
2247 clear_bit(FLAG_REQUESTED, &desc->flags);
2248 clear_bit(FLAG_OPEN_DRAIN, &desc->flags);
2249 clear_bit(FLAG_OPEN_SOURCE, &desc->flags);
2250 clear_bit(FLAG_IS_HOGGED, &desc->flags);
2254 spin_unlock_irqrestore(&gpio_lock, flags);
2258 void gpiod_free(struct gpio_desc *desc)
2260 if (desc && desc->gdev && gpiod_free_commit(desc)) {
2261 module_put(desc->gdev->owner);
2262 put_device(&desc->gdev->dev);
2264 WARN_ON(extra_checks);
2269 * gpiochip_is_requested - return string iff signal was requested
2270 * @chip: controller managing the signal
2271 * @offset: of signal within controller's 0..(ngpio - 1) range
2273 * Returns NULL if the GPIO is not currently requested, else a string.
2274 * The string returned is the label passed to gpio_request(); if none has been
2275 * passed it is a meaningless, non-NULL constant.
2277 * This function is for use by GPIO controller drivers. The label can
2278 * help with diagnostics, and knowing that the signal is used as a GPIO
2279 * can help avoid accidentally multiplexing it to another controller.
2281 const char *gpiochip_is_requested(struct gpio_chip *chip, unsigned offset)
2283 struct gpio_desc *desc;
2285 if (offset >= chip->ngpio)
2288 desc = &chip->gpiodev->descs[offset];
2290 if (test_bit(FLAG_REQUESTED, &desc->flags) == 0)
2294 EXPORT_SYMBOL_GPL(gpiochip_is_requested);
2297 * gpiochip_request_own_desc - Allow GPIO chip to request its own descriptor
2299 * @hwnum: hardware number of the GPIO for which to request the descriptor
2300 * @label: label for the GPIO
2302 * Function allows GPIO chip drivers to request and use their own GPIO
2303 * descriptors via gpiolib API. Difference to gpiod_request() is that this
2304 * function will not increase reference count of the GPIO chip module. This
2305 * allows the GPIO chip module to be unloaded as needed (we assume that the
2306 * GPIO chip driver handles freeing the GPIOs it has requested).
2309 * A pointer to the GPIO descriptor, or an ERR_PTR()-encoded negative error
2312 struct gpio_desc *gpiochip_request_own_desc(struct gpio_chip *chip, u16 hwnum,
2315 struct gpio_desc *desc = gpiochip_get_desc(chip, hwnum);
2319 chip_err(chip, "failed to get GPIO descriptor\n");
2323 err = gpiod_request_commit(desc, label);
2325 return ERR_PTR(err);
2329 EXPORT_SYMBOL_GPL(gpiochip_request_own_desc);
2332 * gpiochip_free_own_desc - Free GPIO requested by the chip driver
2333 * @desc: GPIO descriptor to free
2335 * Function frees the given GPIO requested previously with
2336 * gpiochip_request_own_desc().
2338 void gpiochip_free_own_desc(struct gpio_desc *desc)
2341 gpiod_free_commit(desc);
2343 EXPORT_SYMBOL_GPL(gpiochip_free_own_desc);
2346 * Drivers MUST set GPIO direction before making get/set calls. In
2347 * some cases this is done in early boot, before IRQs are enabled.
2349 * As a rule these aren't called more than once (except for drivers
2350 * using the open-drain emulation idiom) so these are natural places
2351 * to accumulate extra debugging checks. Note that we can't (yet)
2352 * rely on gpio_request() having been called beforehand.
2356 * gpiod_direction_input - set the GPIO direction to input
2357 * @desc: GPIO to set to input
2359 * Set the direction of the passed GPIO to input, such as gpiod_get_value() can
2360 * be called safely on it.
2362 * Return 0 in case of success, else an error code.
2364 int gpiod_direction_input(struct gpio_desc *desc)
2366 struct gpio_chip *chip;
2367 int status = -EINVAL;
2369 VALIDATE_DESC(desc);
2370 chip = desc->gdev->chip;
2372 if (!chip->get || !chip->direction_input) {
2374 "%s: missing get() or direction_input() operations\n",
2379 status = chip->direction_input(chip, gpio_chip_hwgpio(desc));
2381 clear_bit(FLAG_IS_OUT, &desc->flags);
2383 trace_gpio_direction(desc_to_gpio(desc), 1, status);
2387 EXPORT_SYMBOL_GPL(gpiod_direction_input);
2389 static int gpio_set_drive_single_ended(struct gpio_chip *gc, unsigned offset,
2390 enum pin_config_param mode)
2392 unsigned long config = { PIN_CONF_PACKED(mode, 0) };
2394 return gc->set_config ? gc->set_config(gc, offset, config) : -ENOTSUPP;
2397 static int gpiod_direction_output_raw_commit(struct gpio_desc *desc, int value)
2399 struct gpio_chip *gc = desc->gdev->chip;
2403 if (!gc->set || !gc->direction_output) {
2405 "%s: missing set() or direction_output() operations\n",
2410 ret = gc->direction_output(gc, gpio_chip_hwgpio(desc), val);
2412 set_bit(FLAG_IS_OUT, &desc->flags);
2413 trace_gpio_value(desc_to_gpio(desc), 0, val);
2414 trace_gpio_direction(desc_to_gpio(desc), 0, ret);
2419 * gpiod_direction_output_raw - set the GPIO direction to output
2420 * @desc: GPIO to set to output
2421 * @value: initial output value of the GPIO
2423 * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
2424 * be called safely on it. The initial value of the output must be specified
2425 * as raw value on the physical line without regard for the ACTIVE_LOW status.
2427 * Return 0 in case of success, else an error code.
2429 int gpiod_direction_output_raw(struct gpio_desc *desc, int value)
2431 VALIDATE_DESC(desc);
2432 return gpiod_direction_output_raw_commit(desc, value);
2434 EXPORT_SYMBOL_GPL(gpiod_direction_output_raw);
2437 * gpiod_direction_output - set the GPIO direction to output
2438 * @desc: GPIO to set to output
2439 * @value: initial output value of the GPIO
2441 * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
2442 * be called safely on it. The initial value of the output must be specified
2443 * as the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
2446 * Return 0 in case of success, else an error code.
2448 int gpiod_direction_output(struct gpio_desc *desc, int value)
2450 struct gpio_chip *gc = desc->gdev->chip;
2453 VALIDATE_DESC(desc);
2454 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2459 /* GPIOs used for IRQs shall not be set as output */
2460 if (test_bit(FLAG_USED_AS_IRQ, &desc->flags)) {
2462 "%s: tried to set a GPIO tied to an IRQ as output\n",
2467 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags)) {
2468 /* First see if we can enable open drain in hardware */
2469 ret = gpio_set_drive_single_ended(gc, gpio_chip_hwgpio(desc),
2470 PIN_CONFIG_DRIVE_OPEN_DRAIN);
2472 goto set_output_value;
2473 /* Emulate open drain by not actively driving the line high */
2475 return gpiod_direction_input(desc);
2477 else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags)) {
2478 ret = gpio_set_drive_single_ended(gc, gpio_chip_hwgpio(desc),
2479 PIN_CONFIG_DRIVE_OPEN_SOURCE);
2481 goto set_output_value;
2482 /* Emulate open source by not actively driving the line low */
2484 return gpiod_direction_input(desc);
2486 gpio_set_drive_single_ended(gc, gpio_chip_hwgpio(desc),
2487 PIN_CONFIG_DRIVE_PUSH_PULL);
2491 return gpiod_direction_output_raw_commit(desc, value);
2493 EXPORT_SYMBOL_GPL(gpiod_direction_output);
2496 * gpiod_set_debounce - sets @debounce time for a GPIO
2497 * @desc: descriptor of the GPIO for which to set debounce time
2498 * @debounce: debounce time in microseconds
2501 * 0 on success, %-ENOTSUPP if the controller doesn't support setting the
2504 int gpiod_set_debounce(struct gpio_desc *desc, unsigned debounce)
2506 struct gpio_chip *chip;
2507 unsigned long config;
2509 VALIDATE_DESC(desc);
2510 chip = desc->gdev->chip;
2511 if (!chip->set || !chip->set_config) {
2513 "%s: missing set() or set_config() operations\n",
2518 config = pinconf_to_config_packed(PIN_CONFIG_INPUT_DEBOUNCE, debounce);
2519 return chip->set_config(chip, gpio_chip_hwgpio(desc), config);
2521 EXPORT_SYMBOL_GPL(gpiod_set_debounce);
2524 * gpiod_is_active_low - test whether a GPIO is active-low or not
2525 * @desc: the gpio descriptor to test
2527 * Returns 1 if the GPIO is active-low, 0 otherwise.
2529 int gpiod_is_active_low(const struct gpio_desc *desc)
2531 VALIDATE_DESC(desc);
2532 return test_bit(FLAG_ACTIVE_LOW, &desc->flags);
2534 EXPORT_SYMBOL_GPL(gpiod_is_active_low);
2536 /* I/O calls are only valid after configuration completed; the relevant
2537 * "is this a valid GPIO" error checks should already have been done.
2539 * "Get" operations are often inlinable as reading a pin value register,
2540 * and masking the relevant bit in that register.
2542 * When "set" operations are inlinable, they involve writing that mask to
2543 * one register to set a low value, or a different register to set it high.
2544 * Otherwise locking is needed, so there may be little value to inlining.
2546 *------------------------------------------------------------------------
2548 * IMPORTANT!!! The hot paths -- get/set value -- assume that callers
2549 * have requested the GPIO. That can include implicit requesting by
2550 * a direction setting call. Marking a gpio as requested locks its chip
2551 * in memory, guaranteeing that these table lookups need no more locking
2552 * and that gpiochip_remove() will fail.
2554 * REVISIT when debugging, consider adding some instrumentation to ensure
2555 * that the GPIO was actually requested.
2558 static int gpiod_get_raw_value_commit(const struct gpio_desc *desc)
2560 struct gpio_chip *chip;
2564 chip = desc->gdev->chip;
2565 offset = gpio_chip_hwgpio(desc);
2566 value = chip->get ? chip->get(chip, offset) : -EIO;
2567 value = value < 0 ? value : !!value;
2568 trace_gpio_value(desc_to_gpio(desc), 1, value);
2572 static int gpio_chip_get_multiple(struct gpio_chip *chip,
2573 unsigned long *mask, unsigned long *bits)
2575 if (chip->get_multiple) {
2576 return chip->get_multiple(chip, mask, bits);
2577 } else if (chip->get) {
2580 for_each_set_bit(i, mask, chip->ngpio) {
2581 value = chip->get(chip, i);
2584 __assign_bit(i, bits, value);
2591 int gpiod_get_array_value_complex(bool raw, bool can_sleep,
2592 unsigned int array_size,
2593 struct gpio_desc **desc_array,
2598 while (i < array_size) {
2599 struct gpio_chip *chip = desc_array[i]->gdev->chip;
2600 unsigned long mask[BITS_TO_LONGS(chip->ngpio)];
2601 unsigned long bits[BITS_TO_LONGS(chip->ngpio)];
2605 WARN_ON(chip->can_sleep);
2607 /* collect all inputs belonging to the same chip */
2609 memset(mask, 0, sizeof(mask));
2611 const struct gpio_desc *desc = desc_array[i];
2612 int hwgpio = gpio_chip_hwgpio(desc);
2614 __set_bit(hwgpio, mask);
2616 } while ((i < array_size) &&
2617 (desc_array[i]->gdev->chip == chip));
2619 ret = gpio_chip_get_multiple(chip, mask, bits);
2623 for (j = first; j < i; j++) {
2624 const struct gpio_desc *desc = desc_array[j];
2625 int hwgpio = gpio_chip_hwgpio(desc);
2626 int value = test_bit(hwgpio, bits);
2628 if (!raw && test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2630 value_array[j] = value;
2631 trace_gpio_value(desc_to_gpio(desc), 1, value);
2638 * gpiod_get_raw_value() - return a gpio's raw value
2639 * @desc: gpio whose value will be returned
2641 * Return the GPIO's raw value, i.e. the value of the physical line disregarding
2642 * its ACTIVE_LOW status, or negative errno on failure.
2644 * This function should be called from contexts where we cannot sleep, and will
2645 * complain if the GPIO chip functions potentially sleep.
2647 int gpiod_get_raw_value(const struct gpio_desc *desc)
2649 VALIDATE_DESC(desc);
2650 /* Should be using gpio_get_value_cansleep() */
2651 WARN_ON(desc->gdev->chip->can_sleep);
2652 return gpiod_get_raw_value_commit(desc);
2654 EXPORT_SYMBOL_GPL(gpiod_get_raw_value);
2657 * gpiod_get_value() - return a gpio's value
2658 * @desc: gpio whose value will be returned
2660 * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
2661 * account, or negative errno on failure.
2663 * This function should be called from contexts where we cannot sleep, and will
2664 * complain if the GPIO chip functions potentially sleep.
2666 int gpiod_get_value(const struct gpio_desc *desc)
2670 VALIDATE_DESC(desc);
2671 /* Should be using gpio_get_value_cansleep() */
2672 WARN_ON(desc->gdev->chip->can_sleep);
2674 value = gpiod_get_raw_value_commit(desc);
2678 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2683 EXPORT_SYMBOL_GPL(gpiod_get_value);
2686 * gpiod_get_raw_array_value() - read raw values from an array of GPIOs
2687 * @array_size: number of elements in the descriptor / value arrays
2688 * @desc_array: array of GPIO descriptors whose values will be read
2689 * @value_array: array to store the read values
2691 * Read the raw values of the GPIOs, i.e. the values of the physical lines
2692 * without regard for their ACTIVE_LOW status. Return 0 in case of success,
2693 * else an error code.
2695 * This function should be called from contexts where we cannot sleep,
2696 * and it will complain if the GPIO chip functions potentially sleep.
2698 int gpiod_get_raw_array_value(unsigned int array_size,
2699 struct gpio_desc **desc_array, int *value_array)
2703 return gpiod_get_array_value_complex(true, false, array_size,
2704 desc_array, value_array);
2706 EXPORT_SYMBOL_GPL(gpiod_get_raw_array_value);
2709 * gpiod_get_array_value() - read values from an array of GPIOs
2710 * @array_size: number of elements in the descriptor / value arrays
2711 * @desc_array: array of GPIO descriptors whose values will be read
2712 * @value_array: array to store the read values
2714 * Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
2715 * into account. Return 0 in case of success, else an error code.
2717 * This function should be called from contexts where we cannot sleep,
2718 * and it will complain if the GPIO chip functions potentially sleep.
2720 int gpiod_get_array_value(unsigned int array_size,
2721 struct gpio_desc **desc_array, int *value_array)
2725 return gpiod_get_array_value_complex(false, false, array_size,
2726 desc_array, value_array);
2728 EXPORT_SYMBOL_GPL(gpiod_get_array_value);
2731 * gpio_set_open_drain_value_commit() - Set the open drain gpio's value.
2732 * @desc: gpio descriptor whose state need to be set.
2733 * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
2735 static void gpio_set_open_drain_value_commit(struct gpio_desc *desc, bool value)
2738 struct gpio_chip *chip = desc->gdev->chip;
2739 int offset = gpio_chip_hwgpio(desc);
2742 err = chip->direction_input(chip, offset);
2744 clear_bit(FLAG_IS_OUT, &desc->flags);
2746 err = chip->direction_output(chip, offset, 0);
2748 set_bit(FLAG_IS_OUT, &desc->flags);
2750 trace_gpio_direction(desc_to_gpio(desc), value, err);
2753 "%s: Error in set_value for open drain err %d\n",
2758 * _gpio_set_open_source_value() - Set the open source gpio's value.
2759 * @desc: gpio descriptor whose state need to be set.
2760 * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
2762 static void gpio_set_open_source_value_commit(struct gpio_desc *desc, bool value)
2765 struct gpio_chip *chip = desc->gdev->chip;
2766 int offset = gpio_chip_hwgpio(desc);
2769 err = chip->direction_output(chip, offset, 1);
2771 set_bit(FLAG_IS_OUT, &desc->flags);
2773 err = chip->direction_input(chip, offset);
2775 clear_bit(FLAG_IS_OUT, &desc->flags);
2777 trace_gpio_direction(desc_to_gpio(desc), !value, err);
2780 "%s: Error in set_value for open source err %d\n",
2784 static void gpiod_set_raw_value_commit(struct gpio_desc *desc, bool value)
2786 struct gpio_chip *chip;
2788 chip = desc->gdev->chip;
2789 trace_gpio_value(desc_to_gpio(desc), 0, value);
2790 chip->set(chip, gpio_chip_hwgpio(desc), value);
2794 * set multiple outputs on the same chip;
2795 * use the chip's set_multiple function if available;
2796 * otherwise set the outputs sequentially;
2797 * @mask: bit mask array; one bit per output; BITS_PER_LONG bits per word
2798 * defines which outputs are to be changed
2799 * @bits: bit value array; one bit per output; BITS_PER_LONG bits per word
2800 * defines the values the outputs specified by mask are to be set to
2802 static void gpio_chip_set_multiple(struct gpio_chip *chip,
2803 unsigned long *mask, unsigned long *bits)
2805 if (chip->set_multiple) {
2806 chip->set_multiple(chip, mask, bits);
2810 /* set outputs if the corresponding mask bit is set */
2811 for_each_set_bit(i, mask, chip->ngpio)
2812 chip->set(chip, i, test_bit(i, bits));
2816 void gpiod_set_array_value_complex(bool raw, bool can_sleep,
2817 unsigned int array_size,
2818 struct gpio_desc **desc_array,
2823 while (i < array_size) {
2824 struct gpio_chip *chip = desc_array[i]->gdev->chip;
2825 unsigned long mask[BITS_TO_LONGS(chip->ngpio)];
2826 unsigned long bits[BITS_TO_LONGS(chip->ngpio)];
2830 WARN_ON(chip->can_sleep);
2832 memset(mask, 0, sizeof(mask));
2834 struct gpio_desc *desc = desc_array[i];
2835 int hwgpio = gpio_chip_hwgpio(desc);
2836 int value = value_array[i];
2838 if (!raw && test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2840 trace_gpio_value(desc_to_gpio(desc), 0, value);
2842 * collect all normal outputs belonging to the same chip
2843 * open drain and open source outputs are set individually
2845 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags) && !raw) {
2846 gpio_set_open_drain_value_commit(desc, value);
2847 } else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags) && !raw) {
2848 gpio_set_open_source_value_commit(desc, value);
2850 __set_bit(hwgpio, mask);
2852 __set_bit(hwgpio, bits);
2854 __clear_bit(hwgpio, bits);
2858 } while ((i < array_size) &&
2859 (desc_array[i]->gdev->chip == chip));
2860 /* push collected bits to outputs */
2862 gpio_chip_set_multiple(chip, mask, bits);
2867 * gpiod_set_raw_value() - assign a gpio's raw value
2868 * @desc: gpio whose value will be assigned
2869 * @value: value to assign
2871 * Set the raw value of the GPIO, i.e. the value of its physical line without
2872 * regard for its ACTIVE_LOW status.
2874 * This function should be called from contexts where we cannot sleep, and will
2875 * complain if the GPIO chip functions potentially sleep.
2877 void gpiod_set_raw_value(struct gpio_desc *desc, int value)
2879 VALIDATE_DESC_VOID(desc);
2880 /* Should be using gpiod_set_value_cansleep() */
2881 WARN_ON(desc->gdev->chip->can_sleep);
2882 gpiod_set_raw_value_commit(desc, value);
2884 EXPORT_SYMBOL_GPL(gpiod_set_raw_value);
2887 * gpiod_set_value() - assign a gpio's value
2888 * @desc: gpio whose value will be assigned
2889 * @value: value to assign
2891 * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW,
2892 * OPEN_DRAIN and OPEN_SOURCE flags into account.
2894 * This function should be called from contexts where we cannot sleep, and will
2895 * complain if the GPIO chip functions potentially sleep.
2897 void gpiod_set_value(struct gpio_desc *desc, int value)
2899 VALIDATE_DESC_VOID(desc);
2900 /* Should be using gpiod_set_value_cansleep() */
2901 WARN_ON(desc->gdev->chip->can_sleep);
2902 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2904 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
2905 gpio_set_open_drain_value_commit(desc, value);
2906 else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
2907 gpio_set_open_source_value_commit(desc, value);
2909 gpiod_set_raw_value_commit(desc, value);
2911 EXPORT_SYMBOL_GPL(gpiod_set_value);
2914 * gpiod_set_raw_array_value() - assign values to an array of GPIOs
2915 * @array_size: number of elements in the descriptor / value arrays
2916 * @desc_array: array of GPIO descriptors whose values will be assigned
2917 * @value_array: array of values to assign
2919 * Set the raw values of the GPIOs, i.e. the values of the physical lines
2920 * without regard for their ACTIVE_LOW status.
2922 * This function should be called from contexts where we cannot sleep, and will
2923 * complain if the GPIO chip functions potentially sleep.
2925 void gpiod_set_raw_array_value(unsigned int array_size,
2926 struct gpio_desc **desc_array, int *value_array)
2930 gpiod_set_array_value_complex(true, false, array_size, desc_array,
2933 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value);
2936 * gpiod_set_array_value() - assign values to an array of GPIOs
2937 * @array_size: number of elements in the descriptor / value arrays
2938 * @desc_array: array of GPIO descriptors whose values will be assigned
2939 * @value_array: array of values to assign
2941 * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
2944 * This function should be called from contexts where we cannot sleep, and will
2945 * complain if the GPIO chip functions potentially sleep.
2947 void gpiod_set_array_value(unsigned int array_size,
2948 struct gpio_desc **desc_array, int *value_array)
2952 gpiod_set_array_value_complex(false, false, array_size, desc_array,
2955 EXPORT_SYMBOL_GPL(gpiod_set_array_value);
2958 * gpiod_cansleep() - report whether gpio value access may sleep
2959 * @desc: gpio to check
2962 int gpiod_cansleep(const struct gpio_desc *desc)
2964 VALIDATE_DESC(desc);
2965 return desc->gdev->chip->can_sleep;
2967 EXPORT_SYMBOL_GPL(gpiod_cansleep);
2970 * gpiod_to_irq() - return the IRQ corresponding to a GPIO
2971 * @desc: gpio whose IRQ will be returned (already requested)
2973 * Return the IRQ corresponding to the passed GPIO, or an error code in case of
2976 int gpiod_to_irq(const struct gpio_desc *desc)
2978 struct gpio_chip *chip;
2982 * Cannot VALIDATE_DESC() here as gpiod_to_irq() consumer semantics
2983 * requires this function to not return zero on an invalid descriptor
2984 * but rather a negative error number.
2986 if (!desc || IS_ERR(desc) || !desc->gdev || !desc->gdev->chip)
2989 chip = desc->gdev->chip;
2990 offset = gpio_chip_hwgpio(desc);
2992 int retirq = chip->to_irq(chip, offset);
2994 /* Zero means NO_IRQ */
3002 EXPORT_SYMBOL_GPL(gpiod_to_irq);
3005 * gpiochip_lock_as_irq() - lock a GPIO to be used as IRQ
3006 * @chip: the chip the GPIO to lock belongs to
3007 * @offset: the offset of the GPIO to lock as IRQ
3009 * This is used directly by GPIO drivers that want to lock down
3010 * a certain GPIO line to be used for IRQs.
3012 int gpiochip_lock_as_irq(struct gpio_chip *chip, unsigned int offset)
3014 struct gpio_desc *desc;
3016 desc = gpiochip_get_desc(chip, offset);
3018 return PTR_ERR(desc);
3021 * If it's fast: flush the direction setting if something changed
3024 if (!chip->can_sleep && chip->get_direction) {
3025 int dir = chip->get_direction(chip, offset);
3028 clear_bit(FLAG_IS_OUT, &desc->flags);
3030 set_bit(FLAG_IS_OUT, &desc->flags);
3033 if (test_bit(FLAG_IS_OUT, &desc->flags)) {
3035 "%s: tried to flag a GPIO set as output for IRQ\n",
3040 set_bit(FLAG_USED_AS_IRQ, &desc->flags);
3043 * If the consumer has not set up a label (such as when the
3044 * IRQ is referenced from .to_irq()) we set up a label here
3045 * so it is clear this is used as an interrupt.
3048 desc_set_label(desc, "interrupt");
3052 EXPORT_SYMBOL_GPL(gpiochip_lock_as_irq);
3055 * gpiochip_unlock_as_irq() - unlock a GPIO used as IRQ
3056 * @chip: the chip the GPIO to lock belongs to
3057 * @offset: the offset of the GPIO to lock as IRQ
3059 * This is used directly by GPIO drivers that want to indicate
3060 * that a certain GPIO is no longer used exclusively for IRQ.
3062 void gpiochip_unlock_as_irq(struct gpio_chip *chip, unsigned int offset)
3064 struct gpio_desc *desc;
3066 desc = gpiochip_get_desc(chip, offset);
3070 clear_bit(FLAG_USED_AS_IRQ, &desc->flags);
3072 /* If we only had this marking, erase it */
3073 if (desc->label && !strcmp(desc->label, "interrupt"))
3074 desc_set_label(desc, NULL);
3076 EXPORT_SYMBOL_GPL(gpiochip_unlock_as_irq);
3078 bool gpiochip_line_is_irq(struct gpio_chip *chip, unsigned int offset)
3080 if (offset >= chip->ngpio)
3083 return test_bit(FLAG_USED_AS_IRQ, &chip->gpiodev->descs[offset].flags);
3085 EXPORT_SYMBOL_GPL(gpiochip_line_is_irq);
3087 bool gpiochip_line_is_open_drain(struct gpio_chip *chip, unsigned int offset)
3089 if (offset >= chip->ngpio)
3092 return test_bit(FLAG_OPEN_DRAIN, &chip->gpiodev->descs[offset].flags);
3094 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_drain);
3096 bool gpiochip_line_is_open_source(struct gpio_chip *chip, unsigned int offset)
3098 if (offset >= chip->ngpio)
3101 return test_bit(FLAG_OPEN_SOURCE, &chip->gpiodev->descs[offset].flags);
3103 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_source);
3105 bool gpiochip_line_is_persistent(struct gpio_chip *chip, unsigned int offset)
3107 if (offset >= chip->ngpio)
3110 return !test_bit(FLAG_SLEEP_MAY_LOSE_VALUE,
3111 &chip->gpiodev->descs[offset].flags);
3113 EXPORT_SYMBOL_GPL(gpiochip_line_is_persistent);
3116 * gpiod_get_raw_value_cansleep() - return a gpio's raw value
3117 * @desc: gpio whose value will be returned
3119 * Return the GPIO's raw value, i.e. the value of the physical line disregarding
3120 * its ACTIVE_LOW status, or negative errno on failure.
3122 * This function is to be called from contexts that can sleep.
3124 int gpiod_get_raw_value_cansleep(const struct gpio_desc *desc)
3126 might_sleep_if(extra_checks);
3127 VALIDATE_DESC(desc);
3128 return gpiod_get_raw_value_commit(desc);
3130 EXPORT_SYMBOL_GPL(gpiod_get_raw_value_cansleep);
3133 * gpiod_get_value_cansleep() - return a gpio's value
3134 * @desc: gpio whose value will be returned
3136 * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
3137 * account, or negative errno on failure.
3139 * This function is to be called from contexts that can sleep.
3141 int gpiod_get_value_cansleep(const struct gpio_desc *desc)
3145 might_sleep_if(extra_checks);
3146 VALIDATE_DESC(desc);
3147 value = gpiod_get_raw_value_commit(desc);
3151 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3156 EXPORT_SYMBOL_GPL(gpiod_get_value_cansleep);
3159 * gpiod_get_raw_array_value_cansleep() - read raw values from an array of GPIOs
3160 * @array_size: number of elements in the descriptor / value arrays
3161 * @desc_array: array of GPIO descriptors whose values will be read
3162 * @value_array: array to store the read values
3164 * Read the raw values of the GPIOs, i.e. the values of the physical lines
3165 * without regard for their ACTIVE_LOW status. Return 0 in case of success,
3166 * else an error code.
3168 * This function is to be called from contexts that can sleep.
3170 int gpiod_get_raw_array_value_cansleep(unsigned int array_size,
3171 struct gpio_desc **desc_array,
3174 might_sleep_if(extra_checks);
3177 return gpiod_get_array_value_complex(true, true, array_size,
3178 desc_array, value_array);
3180 EXPORT_SYMBOL_GPL(gpiod_get_raw_array_value_cansleep);
3183 * gpiod_get_array_value_cansleep() - read values from an array of GPIOs
3184 * @array_size: number of elements in the descriptor / value arrays
3185 * @desc_array: array of GPIO descriptors whose values will be read
3186 * @value_array: array to store the read values
3188 * Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3189 * into account. Return 0 in case of success, else an error code.
3191 * This function is to be called from contexts that can sleep.
3193 int gpiod_get_array_value_cansleep(unsigned int array_size,
3194 struct gpio_desc **desc_array,
3197 might_sleep_if(extra_checks);
3200 return gpiod_get_array_value_complex(false, true, array_size,
3201 desc_array, value_array);
3203 EXPORT_SYMBOL_GPL(gpiod_get_array_value_cansleep);
3206 * gpiod_set_raw_value_cansleep() - assign a gpio's raw value
3207 * @desc: gpio whose value will be assigned
3208 * @value: value to assign
3210 * Set the raw value of the GPIO, i.e. the value of its physical line without
3211 * regard for its ACTIVE_LOW status.
3213 * This function is to be called from contexts that can sleep.
3215 void gpiod_set_raw_value_cansleep(struct gpio_desc *desc, int value)
3217 might_sleep_if(extra_checks);
3218 VALIDATE_DESC_VOID(desc);
3219 gpiod_set_raw_value_commit(desc, value);
3221 EXPORT_SYMBOL_GPL(gpiod_set_raw_value_cansleep);
3224 * gpiod_set_value_cansleep() - assign a gpio's value
3225 * @desc: gpio whose value will be assigned
3226 * @value: value to assign
3228 * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
3231 * This function is to be called from contexts that can sleep.
3233 void gpiod_set_value_cansleep(struct gpio_desc *desc, int value)
3235 might_sleep_if(extra_checks);
3236 VALIDATE_DESC_VOID(desc);
3237 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3239 gpiod_set_raw_value_commit(desc, value);
3241 EXPORT_SYMBOL_GPL(gpiod_set_value_cansleep);
3244 * gpiod_set_raw_array_value_cansleep() - assign values to an array of GPIOs
3245 * @array_size: number of elements in the descriptor / value arrays
3246 * @desc_array: array of GPIO descriptors whose values will be assigned
3247 * @value_array: array of values to assign
3249 * Set the raw values of the GPIOs, i.e. the values of the physical lines
3250 * without regard for their ACTIVE_LOW status.
3252 * This function is to be called from contexts that can sleep.
3254 void gpiod_set_raw_array_value_cansleep(unsigned int array_size,
3255 struct gpio_desc **desc_array,
3258 might_sleep_if(extra_checks);
3261 gpiod_set_array_value_complex(true, true, array_size, desc_array,
3264 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value_cansleep);
3267 * gpiod_add_lookup_tables() - register GPIO device consumers
3268 * @tables: list of tables of consumers to register
3269 * @n: number of tables in the list
3271 void gpiod_add_lookup_tables(struct gpiod_lookup_table **tables, size_t n)
3275 mutex_lock(&gpio_lookup_lock);
3277 for (i = 0; i < n; i++)
3278 list_add_tail(&tables[i]->list, &gpio_lookup_list);
3280 mutex_unlock(&gpio_lookup_lock);
3284 * gpiod_set_array_value_cansleep() - assign values to an array of GPIOs
3285 * @array_size: number of elements in the descriptor / value arrays
3286 * @desc_array: array of GPIO descriptors whose values will be assigned
3287 * @value_array: array of values to assign
3289 * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3292 * This function is to be called from contexts that can sleep.
3294 void gpiod_set_array_value_cansleep(unsigned int array_size,
3295 struct gpio_desc **desc_array,
3298 might_sleep_if(extra_checks);
3301 gpiod_set_array_value_complex(false, true, array_size, desc_array,
3304 EXPORT_SYMBOL_GPL(gpiod_set_array_value_cansleep);
3307 * gpiod_add_lookup_table() - register GPIO device consumers
3308 * @table: table of consumers to register
3310 void gpiod_add_lookup_table(struct gpiod_lookup_table *table)
3312 mutex_lock(&gpio_lookup_lock);
3314 list_add_tail(&table->list, &gpio_lookup_list);
3316 mutex_unlock(&gpio_lookup_lock);
3318 EXPORT_SYMBOL_GPL(gpiod_add_lookup_table);
3321 * gpiod_remove_lookup_table() - unregister GPIO device consumers
3322 * @table: table of consumers to unregister
3324 void gpiod_remove_lookup_table(struct gpiod_lookup_table *table)
3326 mutex_lock(&gpio_lookup_lock);
3328 list_del(&table->list);
3330 mutex_unlock(&gpio_lookup_lock);
3332 EXPORT_SYMBOL_GPL(gpiod_remove_lookup_table);
3334 static struct gpiod_lookup_table *gpiod_find_lookup_table(struct device *dev)
3336 const char *dev_id = dev ? dev_name(dev) : NULL;
3337 struct gpiod_lookup_table *table;
3339 mutex_lock(&gpio_lookup_lock);
3341 list_for_each_entry(table, &gpio_lookup_list, list) {
3342 if (table->dev_id && dev_id) {
3344 * Valid strings on both ends, must be identical to have
3347 if (!strcmp(table->dev_id, dev_id))
3351 * One of the pointers is NULL, so both must be to have
3354 if (dev_id == table->dev_id)
3361 mutex_unlock(&gpio_lookup_lock);
3365 static struct gpio_desc *gpiod_find(struct device *dev, const char *con_id,
3367 enum gpio_lookup_flags *flags)
3369 struct gpio_desc *desc = ERR_PTR(-ENOENT);
3370 struct gpiod_lookup_table *table;
3371 struct gpiod_lookup *p;
3373 table = gpiod_find_lookup_table(dev);
3377 for (p = &table->table[0]; p->chip_label; p++) {
3378 struct gpio_chip *chip;
3380 /* idx must always match exactly */
3384 /* If the lookup entry has a con_id, require exact match */
3385 if (p->con_id && (!con_id || strcmp(p->con_id, con_id)))
3388 chip = find_chip_by_name(p->chip_label);
3391 dev_err(dev, "cannot find GPIO chip %s\n",
3393 return ERR_PTR(-ENODEV);
3396 if (chip->ngpio <= p->chip_hwnum) {
3398 "requested GPIO %d is out of range [0..%d] for chip %s\n",
3399 idx, chip->ngpio, chip->label);
3400 return ERR_PTR(-EINVAL);
3403 desc = gpiochip_get_desc(chip, p->chip_hwnum);
3412 static int dt_gpio_count(struct device *dev, const char *con_id)
3418 for (i = 0; i < ARRAY_SIZE(gpio_suffixes); i++) {
3420 snprintf(propname, sizeof(propname), "%s-%s",
3421 con_id, gpio_suffixes[i]);
3423 snprintf(propname, sizeof(propname), "%s",
3426 ret = of_gpio_named_count(dev->of_node, propname);
3430 return ret ? ret : -ENOENT;
3433 static int platform_gpio_count(struct device *dev, const char *con_id)
3435 struct gpiod_lookup_table *table;
3436 struct gpiod_lookup *p;
3437 unsigned int count = 0;
3439 table = gpiod_find_lookup_table(dev);
3443 for (p = &table->table[0]; p->chip_label; p++) {
3444 if ((con_id && p->con_id && !strcmp(con_id, p->con_id)) ||
3445 (!con_id && !p->con_id))
3455 * gpiod_count - return the number of GPIOs associated with a device / function
3456 * or -ENOENT if no GPIO has been assigned to the requested function
3457 * @dev: GPIO consumer, can be NULL for system-global GPIOs
3458 * @con_id: function within the GPIO consumer
3460 int gpiod_count(struct device *dev, const char *con_id)
3462 int count = -ENOENT;
3464 if (IS_ENABLED(CONFIG_OF) && dev && dev->of_node)
3465 count = dt_gpio_count(dev, con_id);
3466 else if (IS_ENABLED(CONFIG_ACPI) && dev && ACPI_HANDLE(dev))
3467 count = acpi_gpio_count(dev, con_id);
3470 count = platform_gpio_count(dev, con_id);
3474 EXPORT_SYMBOL_GPL(gpiod_count);
3477 * gpiod_get - obtain a GPIO for a given GPIO function
3478 * @dev: GPIO consumer, can be NULL for system-global GPIOs
3479 * @con_id: function within the GPIO consumer
3480 * @flags: optional GPIO initialization flags
3482 * Return the GPIO descriptor corresponding to the function con_id of device
3483 * dev, -ENOENT if no GPIO has been assigned to the requested function, or
3484 * another IS_ERR() code if an error occurred while trying to acquire the GPIO.
3486 struct gpio_desc *__must_check gpiod_get(struct device *dev, const char *con_id,
3487 enum gpiod_flags flags)
3489 return gpiod_get_index(dev, con_id, 0, flags);
3491 EXPORT_SYMBOL_GPL(gpiod_get);
3494 * gpiod_get_optional - obtain an optional GPIO for a given GPIO function
3495 * @dev: GPIO consumer, can be NULL for system-global GPIOs
3496 * @con_id: function within the GPIO consumer
3497 * @flags: optional GPIO initialization flags
3499 * This is equivalent to gpiod_get(), except that when no GPIO was assigned to
3500 * the requested function it will return NULL. This is convenient for drivers
3501 * that need to handle optional GPIOs.
3503 struct gpio_desc *__must_check gpiod_get_optional(struct device *dev,
3505 enum gpiod_flags flags)
3507 return gpiod_get_index_optional(dev, con_id, 0, flags);
3509 EXPORT_SYMBOL_GPL(gpiod_get_optional);
3513 * gpiod_configure_flags - helper function to configure a given GPIO
3514 * @desc: gpio whose value will be assigned
3515 * @con_id: function within the GPIO consumer
3516 * @lflags: gpio_lookup_flags - returned from of_find_gpio() or
3518 * @dflags: gpiod_flags - optional GPIO initialization flags
3520 * Return 0 on success, -ENOENT if no GPIO has been assigned to the
3521 * requested function and/or index, or another IS_ERR() code if an error
3522 * occurred while trying to acquire the GPIO.
3524 int gpiod_configure_flags(struct gpio_desc *desc, const char *con_id,
3525 unsigned long lflags, enum gpiod_flags dflags)
3529 if (lflags & GPIO_ACTIVE_LOW)
3530 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
3531 if (lflags & GPIO_OPEN_DRAIN)
3532 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
3533 if (lflags & GPIO_OPEN_SOURCE)
3534 set_bit(FLAG_OPEN_SOURCE, &desc->flags);
3535 if (lflags & GPIO_SLEEP_MAY_LOSE_VALUE)
3536 set_bit(FLAG_SLEEP_MAY_LOSE_VALUE, &desc->flags);
3538 /* No particular flag request, return here... */
3539 if (!(dflags & GPIOD_FLAGS_BIT_DIR_SET)) {
3540 pr_debug("no flags found for %s\n", con_id);
3545 if (dflags & GPIOD_FLAGS_BIT_DIR_OUT)
3546 status = gpiod_direction_output(desc,
3547 !!(dflags & GPIOD_FLAGS_BIT_DIR_VAL));
3549 status = gpiod_direction_input(desc);
3555 * gpiod_get_index - obtain a GPIO from a multi-index GPIO function
3556 * @dev: GPIO consumer, can be NULL for system-global GPIOs
3557 * @con_id: function within the GPIO consumer
3558 * @idx: index of the GPIO to obtain in the consumer
3559 * @flags: optional GPIO initialization flags
3561 * This variant of gpiod_get() allows to access GPIOs other than the first
3562 * defined one for functions that define several GPIOs.
3564 * Return a valid GPIO descriptor, -ENOENT if no GPIO has been assigned to the
3565 * requested function and/or index, or another IS_ERR() code if an error
3566 * occurred while trying to acquire the GPIO.
3568 struct gpio_desc *__must_check gpiod_get_index(struct device *dev,
3571 enum gpiod_flags flags)
3573 struct gpio_desc *desc = NULL;
3575 enum gpio_lookup_flags lookupflags = 0;
3577 dev_dbg(dev, "GPIO lookup for consumer %s\n", con_id);
3580 /* Using device tree? */
3581 if (IS_ENABLED(CONFIG_OF) && dev->of_node) {
3582 dev_dbg(dev, "using device tree for GPIO lookup\n");
3583 desc = of_find_gpio(dev, con_id, idx, &lookupflags);
3584 } else if (ACPI_COMPANION(dev)) {
3585 dev_dbg(dev, "using ACPI for GPIO lookup\n");
3586 desc = acpi_find_gpio(dev, con_id, idx, &flags, &lookupflags);
3591 * Either we are not using DT or ACPI, or their lookup did not return
3592 * a result. In that case, use platform lookup as a fallback.
3594 if (!desc || desc == ERR_PTR(-ENOENT)) {
3595 dev_dbg(dev, "using lookup tables for GPIO lookup\n");
3596 desc = gpiod_find(dev, con_id, idx, &lookupflags);
3600 dev_dbg(dev, "lookup for GPIO %s failed\n", con_id);
3604 status = gpiod_request(desc, con_id);
3606 return ERR_PTR(status);
3608 status = gpiod_configure_flags(desc, con_id, lookupflags, flags);
3610 dev_dbg(dev, "setup of GPIO %s failed\n", con_id);
3612 return ERR_PTR(status);
3617 EXPORT_SYMBOL_GPL(gpiod_get_index);
3620 * fwnode_get_named_gpiod - obtain a GPIO from firmware node
3621 * @fwnode: handle of the firmware node
3622 * @propname: name of the firmware property representing the GPIO
3623 * @index: index of the GPIO to obtain in the consumer
3624 * @dflags: GPIO initialization flags
3625 * @label: label to attach to the requested GPIO
3627 * This function can be used for drivers that get their configuration
3630 * Function properly finds the corresponding GPIO using whatever is the
3631 * underlying firmware interface and then makes sure that the GPIO
3632 * descriptor is requested before it is returned to the caller.
3635 * On successful request the GPIO pin is configured in accordance with
3638 * In case of error an ERR_PTR() is returned.
3640 struct gpio_desc *fwnode_get_named_gpiod(struct fwnode_handle *fwnode,
3641 const char *propname, int index,
3642 enum gpiod_flags dflags,
3645 struct gpio_desc *desc = ERR_PTR(-ENODEV);
3646 unsigned long lflags = 0;
3647 bool active_low = false;
3648 bool single_ended = false;
3649 bool open_drain = false;
3653 return ERR_PTR(-EINVAL);
3655 if (is_of_node(fwnode)) {
3656 enum of_gpio_flags flags;
3658 desc = of_get_named_gpiod_flags(to_of_node(fwnode), propname,
3660 if (!IS_ERR(desc)) {
3661 active_low = flags & OF_GPIO_ACTIVE_LOW;
3662 single_ended = flags & OF_GPIO_SINGLE_ENDED;
3663 open_drain = flags & OF_GPIO_OPEN_DRAIN;
3665 } else if (is_acpi_node(fwnode)) {
3666 struct acpi_gpio_info info;
3668 desc = acpi_node_get_gpiod(fwnode, propname, index, &info);
3669 if (!IS_ERR(desc)) {
3670 active_low = info.polarity == GPIO_ACTIVE_LOW;
3671 ret = acpi_gpio_update_gpiod_flags(&dflags, info.flags);
3673 pr_debug("Override GPIO initialization flags\n");
3680 ret = gpiod_request(desc, label);
3682 return ERR_PTR(ret);
3685 lflags |= GPIO_ACTIVE_LOW;
3689 lflags |= GPIO_OPEN_DRAIN;
3691 lflags |= GPIO_OPEN_SOURCE;
3694 ret = gpiod_configure_flags(desc, propname, lflags, dflags);
3697 return ERR_PTR(ret);
3702 EXPORT_SYMBOL_GPL(fwnode_get_named_gpiod);
3705 * gpiod_get_index_optional - obtain an optional GPIO from a multi-index GPIO
3707 * @dev: GPIO consumer, can be NULL for system-global GPIOs
3708 * @con_id: function within the GPIO consumer
3709 * @index: index of the GPIO to obtain in the consumer
3710 * @flags: optional GPIO initialization flags
3712 * This is equivalent to gpiod_get_index(), except that when no GPIO with the
3713 * specified index was assigned to the requested function it will return NULL.
3714 * This is convenient for drivers that need to handle optional GPIOs.
3716 struct gpio_desc *__must_check gpiod_get_index_optional(struct device *dev,
3719 enum gpiod_flags flags)
3721 struct gpio_desc *desc;
3723 desc = gpiod_get_index(dev, con_id, index, flags);
3725 if (PTR_ERR(desc) == -ENOENT)
3731 EXPORT_SYMBOL_GPL(gpiod_get_index_optional);
3734 * gpiod_hog - Hog the specified GPIO desc given the provided flags
3735 * @desc: gpio whose value will be assigned
3736 * @name: gpio line name
3737 * @lflags: gpio_lookup_flags - returned from of_find_gpio() or
3739 * @dflags: gpiod_flags - optional GPIO initialization flags
3741 int gpiod_hog(struct gpio_desc *desc, const char *name,
3742 unsigned long lflags, enum gpiod_flags dflags)
3744 struct gpio_chip *chip;
3745 struct gpio_desc *local_desc;
3749 chip = gpiod_to_chip(desc);
3750 hwnum = gpio_chip_hwgpio(desc);
3752 local_desc = gpiochip_request_own_desc(chip, hwnum, name);
3753 if (IS_ERR(local_desc)) {
3754 status = PTR_ERR(local_desc);
3755 pr_err("requesting hog GPIO %s (chip %s, offset %d) failed, %d\n",
3756 name, chip->label, hwnum, status);
3760 status = gpiod_configure_flags(desc, name, lflags, dflags);
3762 pr_err("setup of hog GPIO %s (chip %s, offset %d) failed, %d\n",
3763 name, chip->label, hwnum, status);
3764 gpiochip_free_own_desc(desc);
3768 /* Mark GPIO as hogged so it can be identified and removed later */
3769 set_bit(FLAG_IS_HOGGED, &desc->flags);
3771 pr_info("GPIO line %d (%s) hogged as %s%s\n",
3772 desc_to_gpio(desc), name,
3773 (dflags&GPIOD_FLAGS_BIT_DIR_OUT) ? "output" : "input",
3774 (dflags&GPIOD_FLAGS_BIT_DIR_OUT) ?
3775 (dflags&GPIOD_FLAGS_BIT_DIR_VAL) ? "/high" : "/low":"");
3781 * gpiochip_free_hogs - Scan gpio-controller chip and release GPIO hog
3782 * @chip: gpio chip to act on
3784 * This is only used by of_gpiochip_remove to free hogged gpios
3786 static void gpiochip_free_hogs(struct gpio_chip *chip)
3790 for (id = 0; id < chip->ngpio; id++) {
3791 if (test_bit(FLAG_IS_HOGGED, &chip->gpiodev->descs[id].flags))
3792 gpiochip_free_own_desc(&chip->gpiodev->descs[id]);
3797 * gpiod_get_array - obtain multiple GPIOs from a multi-index GPIO function
3798 * @dev: GPIO consumer, can be NULL for system-global GPIOs
3799 * @con_id: function within the GPIO consumer
3800 * @flags: optional GPIO initialization flags
3802 * This function acquires all the GPIOs defined under a given function.
3804 * Return a struct gpio_descs containing an array of descriptors, -ENOENT if
3805 * no GPIO has been assigned to the requested function, or another IS_ERR()
3806 * code if an error occurred while trying to acquire the GPIOs.
3808 struct gpio_descs *__must_check gpiod_get_array(struct device *dev,
3810 enum gpiod_flags flags)
3812 struct gpio_desc *desc;
3813 struct gpio_descs *descs;
3816 count = gpiod_count(dev, con_id);
3818 return ERR_PTR(count);
3820 descs = kzalloc(sizeof(*descs) + sizeof(descs->desc[0]) * count,
3823 return ERR_PTR(-ENOMEM);
3825 for (descs->ndescs = 0; descs->ndescs < count; ) {
3826 desc = gpiod_get_index(dev, con_id, descs->ndescs, flags);
3828 gpiod_put_array(descs);
3829 return ERR_CAST(desc);
3831 descs->desc[descs->ndescs] = desc;
3836 EXPORT_SYMBOL_GPL(gpiod_get_array);
3839 * gpiod_get_array_optional - obtain multiple GPIOs from a multi-index GPIO
3841 * @dev: GPIO consumer, can be NULL for system-global GPIOs
3842 * @con_id: function within the GPIO consumer
3843 * @flags: optional GPIO initialization flags
3845 * This is equivalent to gpiod_get_array(), except that when no GPIO was
3846 * assigned to the requested function it will return NULL.
3848 struct gpio_descs *__must_check gpiod_get_array_optional(struct device *dev,
3850 enum gpiod_flags flags)
3852 struct gpio_descs *descs;
3854 descs = gpiod_get_array(dev, con_id, flags);
3855 if (IS_ERR(descs) && (PTR_ERR(descs) == -ENOENT))
3860 EXPORT_SYMBOL_GPL(gpiod_get_array_optional);
3863 * gpiod_put - dispose of a GPIO descriptor
3864 * @desc: GPIO descriptor to dispose of
3866 * No descriptor can be used after gpiod_put() has been called on it.
3868 void gpiod_put(struct gpio_desc *desc)
3872 EXPORT_SYMBOL_GPL(gpiod_put);
3875 * gpiod_put_array - dispose of multiple GPIO descriptors
3876 * @descs: struct gpio_descs containing an array of descriptors
3878 void gpiod_put_array(struct gpio_descs *descs)
3882 for (i = 0; i < descs->ndescs; i++)
3883 gpiod_put(descs->desc[i]);
3887 EXPORT_SYMBOL_GPL(gpiod_put_array);
3889 static int __init gpiolib_dev_init(void)
3893 /* Register GPIO sysfs bus */
3894 ret = bus_register(&gpio_bus_type);
3896 pr_err("gpiolib: could not register GPIO bus type\n");
3900 ret = alloc_chrdev_region(&gpio_devt, 0, GPIO_DEV_MAX, "gpiochip");
3902 pr_err("gpiolib: failed to allocate char dev region\n");
3903 bus_unregister(&gpio_bus_type);
3905 gpiolib_initialized = true;
3906 gpiochip_setup_devs();
3910 core_initcall(gpiolib_dev_init);
3912 #ifdef CONFIG_DEBUG_FS
3914 static void gpiolib_dbg_show(struct seq_file *s, struct gpio_device *gdev)
3917 struct gpio_chip *chip = gdev->chip;
3918 unsigned gpio = gdev->base;
3919 struct gpio_desc *gdesc = &gdev->descs[0];
3923 for (i = 0; i < gdev->ngpio; i++, gpio++, gdesc++) {
3924 if (!test_bit(FLAG_REQUESTED, &gdesc->flags)) {
3926 seq_printf(s, " gpio-%-3d (%-20.20s)\n",
3932 gpiod_get_direction(gdesc);
3933 is_out = test_bit(FLAG_IS_OUT, &gdesc->flags);
3934 is_irq = test_bit(FLAG_USED_AS_IRQ, &gdesc->flags);
3935 seq_printf(s, " gpio-%-3d (%-20.20s|%-20.20s) %s %s %s",
3936 gpio, gdesc->name ? gdesc->name : "", gdesc->label,
3937 is_out ? "out" : "in ",
3939 ? (chip->get(chip, i) ? "hi" : "lo")
3941 is_irq ? "IRQ" : " ");
3942 seq_printf(s, "\n");
3946 static void *gpiolib_seq_start(struct seq_file *s, loff_t *pos)
3948 unsigned long flags;
3949 struct gpio_device *gdev = NULL;
3950 loff_t index = *pos;
3954 spin_lock_irqsave(&gpio_lock, flags);
3955 list_for_each_entry(gdev, &gpio_devices, list)
3957 spin_unlock_irqrestore(&gpio_lock, flags);
3960 spin_unlock_irqrestore(&gpio_lock, flags);
3965 static void *gpiolib_seq_next(struct seq_file *s, void *v, loff_t *pos)
3967 unsigned long flags;
3968 struct gpio_device *gdev = v;
3971 spin_lock_irqsave(&gpio_lock, flags);
3972 if (list_is_last(&gdev->list, &gpio_devices))
3975 ret = list_entry(gdev->list.next, struct gpio_device, list);
3976 spin_unlock_irqrestore(&gpio_lock, flags);
3984 static void gpiolib_seq_stop(struct seq_file *s, void *v)
3988 static int gpiolib_seq_show(struct seq_file *s, void *v)
3990 struct gpio_device *gdev = v;
3991 struct gpio_chip *chip = gdev->chip;
3992 struct device *parent;
3995 seq_printf(s, "%s%s: (dangling chip)", (char *)s->private,
3996 dev_name(&gdev->dev));
4000 seq_printf(s, "%s%s: GPIOs %d-%d", (char *)s->private,
4001 dev_name(&gdev->dev),
4002 gdev->base, gdev->base + gdev->ngpio - 1);
4003 parent = chip->parent;
4005 seq_printf(s, ", parent: %s/%s",
4006 parent->bus ? parent->bus->name : "no-bus",
4009 seq_printf(s, ", %s", chip->label);
4010 if (chip->can_sleep)
4011 seq_printf(s, ", can sleep");
4012 seq_printf(s, ":\n");
4015 chip->dbg_show(s, chip);
4017 gpiolib_dbg_show(s, gdev);
4022 static const struct seq_operations gpiolib_seq_ops = {
4023 .start = gpiolib_seq_start,
4024 .next = gpiolib_seq_next,
4025 .stop = gpiolib_seq_stop,
4026 .show = gpiolib_seq_show,
4029 static int gpiolib_open(struct inode *inode, struct file *file)
4031 return seq_open(file, &gpiolib_seq_ops);
4034 static const struct file_operations gpiolib_operations = {
4035 .owner = THIS_MODULE,
4036 .open = gpiolib_open,
4038 .llseek = seq_lseek,
4039 .release = seq_release,
4042 static int __init gpiolib_debugfs_init(void)
4044 /* /sys/kernel/debug/gpio */
4045 (void) debugfs_create_file("gpio", S_IFREG | S_IRUGO,
4046 NULL, NULL, &gpiolib_operations);
4049 subsys_initcall(gpiolib_debugfs_init);
4051 #endif /* DEBUG_FS */