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 *lock_key,
77 struct lock_class_key *request_key);
78 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip);
79 static int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gpiochip);
80 static void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gpiochip);
82 static bool gpiolib_initialized;
84 static inline void desc_set_label(struct gpio_desc *d, const char *label)
90 * gpio_to_desc - Convert a GPIO number to its descriptor
91 * @gpio: global GPIO number
94 * The GPIO descriptor associated with the given GPIO, or %NULL if no GPIO
95 * with the given number exists in the system.
97 struct gpio_desc *gpio_to_desc(unsigned gpio)
99 struct gpio_device *gdev;
102 spin_lock_irqsave(&gpio_lock, flags);
104 list_for_each_entry(gdev, &gpio_devices, list) {
105 if (gdev->base <= gpio &&
106 gdev->base + gdev->ngpio > gpio) {
107 spin_unlock_irqrestore(&gpio_lock, flags);
108 return &gdev->descs[gpio - gdev->base];
112 spin_unlock_irqrestore(&gpio_lock, flags);
114 if (!gpio_is_valid(gpio))
115 WARN(1, "invalid GPIO %d\n", gpio);
119 EXPORT_SYMBOL_GPL(gpio_to_desc);
122 * gpiochip_get_desc - get the GPIO descriptor corresponding to the given
123 * hardware number for this chip
125 * @hwnum: hardware number of the GPIO for this chip
128 * A pointer to the GPIO descriptor or %ERR_PTR(-EINVAL) if no GPIO exists
129 * in the given chip for the specified hardware number.
131 struct gpio_desc *gpiochip_get_desc(struct gpio_chip *chip,
134 struct gpio_device *gdev = chip->gpiodev;
136 if (hwnum >= gdev->ngpio)
137 return ERR_PTR(-EINVAL);
139 return &gdev->descs[hwnum];
143 * desc_to_gpio - convert a GPIO descriptor to the integer namespace
144 * @desc: GPIO descriptor
146 * This should disappear in the future but is needed since we still
147 * use GPIO numbers for error messages and sysfs nodes.
150 * The global GPIO number for the GPIO specified by its descriptor.
152 int desc_to_gpio(const struct gpio_desc *desc)
154 return desc->gdev->base + (desc - &desc->gdev->descs[0]);
156 EXPORT_SYMBOL_GPL(desc_to_gpio);
160 * gpiod_to_chip - Return the GPIO chip to which a GPIO descriptor belongs
161 * @desc: descriptor to return the chip of
163 struct gpio_chip *gpiod_to_chip(const struct gpio_desc *desc)
165 if (!desc || !desc->gdev || !desc->gdev->chip)
167 return desc->gdev->chip;
169 EXPORT_SYMBOL_GPL(gpiod_to_chip);
171 /* dynamic allocation of GPIOs, e.g. on a hotplugged device */
172 static int gpiochip_find_base(int ngpio)
174 struct gpio_device *gdev;
175 int base = ARCH_NR_GPIOS - ngpio;
177 list_for_each_entry_reverse(gdev, &gpio_devices, list) {
178 /* found a free space? */
179 if (gdev->base + gdev->ngpio <= base)
182 /* nope, check the space right before the chip */
183 base = gdev->base - ngpio;
186 if (gpio_is_valid(base)) {
187 pr_debug("%s: found new base at %d\n", __func__, base);
190 pr_err("%s: cannot find free range\n", __func__);
196 * gpiod_get_direction - return the current direction of a GPIO
197 * @desc: GPIO to get the direction of
199 * Return GPIOF_DIR_IN or GPIOF_DIR_OUT, or an error code in case of error.
201 * This function may sleep if gpiod_cansleep() is true.
203 int gpiod_get_direction(struct gpio_desc *desc)
205 struct gpio_chip *chip;
207 int status = -EINVAL;
209 chip = gpiod_to_chip(desc);
210 offset = gpio_chip_hwgpio(desc);
212 if (!chip->get_direction)
215 status = chip->get_direction(chip, offset);
217 /* GPIOF_DIR_IN, or other positive */
219 clear_bit(FLAG_IS_OUT, &desc->flags);
223 set_bit(FLAG_IS_OUT, &desc->flags);
227 EXPORT_SYMBOL_GPL(gpiod_get_direction);
230 * Add a new chip to the global chips list, keeping the list of chips sorted
231 * by range(means [base, base + ngpio - 1]) order.
233 * Return -EBUSY if the new chip overlaps with some other chip's integer
236 static int gpiodev_add_to_list(struct gpio_device *gdev)
238 struct gpio_device *prev, *next;
240 if (list_empty(&gpio_devices)) {
241 /* initial entry in list */
242 list_add_tail(&gdev->list, &gpio_devices);
246 next = list_entry(gpio_devices.next, struct gpio_device, list);
247 if (gdev->base + gdev->ngpio <= next->base) {
248 /* add before first entry */
249 list_add(&gdev->list, &gpio_devices);
253 prev = list_entry(gpio_devices.prev, struct gpio_device, list);
254 if (prev->base + prev->ngpio <= gdev->base) {
255 /* add behind last entry */
256 list_add_tail(&gdev->list, &gpio_devices);
260 list_for_each_entry_safe(prev, next, &gpio_devices, list) {
261 /* at the end of the list */
262 if (&next->list == &gpio_devices)
265 /* add between prev and next */
266 if (prev->base + prev->ngpio <= gdev->base
267 && gdev->base + gdev->ngpio <= next->base) {
268 list_add(&gdev->list, &prev->list);
273 dev_err(&gdev->dev, "GPIO integer space overlap, cannot add chip\n");
278 * Convert a GPIO name to its descriptor
280 static struct gpio_desc *gpio_name_to_desc(const char * const name)
282 struct gpio_device *gdev;
285 spin_lock_irqsave(&gpio_lock, flags);
287 list_for_each_entry(gdev, &gpio_devices, list) {
290 for (i = 0; i != gdev->ngpio; ++i) {
291 struct gpio_desc *desc = &gdev->descs[i];
293 if (!desc->name || !name)
296 if (!strcmp(desc->name, name)) {
297 spin_unlock_irqrestore(&gpio_lock, flags);
303 spin_unlock_irqrestore(&gpio_lock, flags);
309 * Takes the names from gc->names and checks if they are all unique. If they
310 * are, they are assigned to their gpio descriptors.
312 * Warning if one of the names is already used for a different GPIO.
314 static int gpiochip_set_desc_names(struct gpio_chip *gc)
316 struct gpio_device *gdev = gc->gpiodev;
322 /* First check all names if they are unique */
323 for (i = 0; i != gc->ngpio; ++i) {
324 struct gpio_desc *gpio;
326 gpio = gpio_name_to_desc(gc->names[i]);
329 "Detected name collision for GPIO name '%s'\n",
333 /* Then add all names to the GPIO descriptors */
334 for (i = 0; i != gc->ngpio; ++i)
335 gdev->descs[i].name = gc->names[i];
341 * GPIO line handle management
345 * struct linehandle_state - contains the state of a userspace handle
346 * @gdev: the GPIO device the handle pertains to
347 * @label: consumer label used to tag descriptors
348 * @descs: the GPIO descriptors held by this handle
349 * @numdescs: the number of descriptors held in the descs array
351 struct linehandle_state {
352 struct gpio_device *gdev;
354 struct gpio_desc *descs[GPIOHANDLES_MAX];
358 #define GPIOHANDLE_REQUEST_VALID_FLAGS \
359 (GPIOHANDLE_REQUEST_INPUT | \
360 GPIOHANDLE_REQUEST_OUTPUT | \
361 GPIOHANDLE_REQUEST_ACTIVE_LOW | \
362 GPIOHANDLE_REQUEST_OPEN_DRAIN | \
363 GPIOHANDLE_REQUEST_OPEN_SOURCE)
365 static long linehandle_ioctl(struct file *filep, unsigned int cmd,
368 struct linehandle_state *lh = filep->private_data;
369 void __user *ip = (void __user *)arg;
370 struct gpiohandle_data ghd;
371 int vals[GPIOHANDLES_MAX];
374 if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
375 /* TODO: check if descriptors are really input */
376 int ret = gpiod_get_array_value_complex(false,
384 memset(&ghd, 0, sizeof(ghd));
385 for (i = 0; i < lh->numdescs; i++)
386 ghd.values[i] = vals[i];
388 if (copy_to_user(ip, &ghd, sizeof(ghd)))
392 } else if (cmd == GPIOHANDLE_SET_LINE_VALUES_IOCTL) {
393 /* TODO: check if descriptors are really output */
394 if (copy_from_user(&ghd, ip, sizeof(ghd)))
397 /* Clamp all values to [0,1] */
398 for (i = 0; i < lh->numdescs; i++)
399 vals[i] = !!ghd.values[i];
401 /* Reuse the array setting function */
402 gpiod_set_array_value_complex(false,
413 static long linehandle_ioctl_compat(struct file *filep, unsigned int cmd,
416 return linehandle_ioctl(filep, cmd, (unsigned long)compat_ptr(arg));
420 static int linehandle_release(struct inode *inode, struct file *filep)
422 struct linehandle_state *lh = filep->private_data;
423 struct gpio_device *gdev = lh->gdev;
426 for (i = 0; i < lh->numdescs; i++)
427 gpiod_free(lh->descs[i]);
430 put_device(&gdev->dev);
434 static const struct file_operations linehandle_fileops = {
435 .release = linehandle_release,
436 .owner = THIS_MODULE,
437 .llseek = noop_llseek,
438 .unlocked_ioctl = linehandle_ioctl,
440 .compat_ioctl = linehandle_ioctl_compat,
444 static int linehandle_create(struct gpio_device *gdev, void __user *ip)
446 struct gpiohandle_request handlereq;
447 struct linehandle_state *lh;
452 if (copy_from_user(&handlereq, ip, sizeof(handlereq)))
454 if ((handlereq.lines == 0) || (handlereq.lines > GPIOHANDLES_MAX))
457 lflags = handlereq.flags;
459 /* Return an error if an unknown flag is set */
460 if (lflags & ~GPIOHANDLE_REQUEST_VALID_FLAGS)
463 /* OPEN_DRAIN and OPEN_SOURCE flags only make sense for output mode. */
464 if (!(lflags & GPIOHANDLE_REQUEST_OUTPUT) &&
465 ((lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN) ||
466 (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE)))
469 lh = kzalloc(sizeof(*lh), GFP_KERNEL);
473 get_device(&gdev->dev);
475 /* Make sure this is terminated */
476 handlereq.consumer_label[sizeof(handlereq.consumer_label)-1] = '\0';
477 if (strlen(handlereq.consumer_label)) {
478 lh->label = kstrdup(handlereq.consumer_label,
486 /* Request each GPIO */
487 for (i = 0; i < handlereq.lines; i++) {
488 u32 offset = handlereq.lineoffsets[i];
489 struct gpio_desc *desc;
491 if (offset >= gdev->ngpio) {
496 desc = &gdev->descs[offset];
497 ret = gpiod_request(desc, lh->label);
502 if (lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW)
503 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
504 if (lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN)
505 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
506 if (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE)
507 set_bit(FLAG_OPEN_SOURCE, &desc->flags);
510 * Lines have to be requested explicitly for input
511 * or output, else the line will be treated "as is".
513 if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
514 int val = !!handlereq.default_values[i];
516 ret = gpiod_direction_output(desc, val);
519 } else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
520 ret = gpiod_direction_input(desc);
524 dev_dbg(&gdev->dev, "registered chardev handle for line %d\n",
527 /* Let i point at the last handle */
529 lh->numdescs = handlereq.lines;
531 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
537 file = anon_inode_getfile("gpio-linehandle",
540 O_RDONLY | O_CLOEXEC);
543 goto out_put_unused_fd;
547 if (copy_to_user(ip, &handlereq, sizeof(handlereq))) {
549 * fput() will trigger the release() callback, so do not go onto
550 * the regular error cleanup path here.
557 fd_install(fd, file);
559 dev_dbg(&gdev->dev, "registered chardev handle for %d lines\n",
568 gpiod_free(lh->descs[i]);
572 put_device(&gdev->dev);
577 * GPIO line event management
581 * struct lineevent_state - contains the state of a userspace event
582 * @gdev: the GPIO device the event pertains to
583 * @label: consumer label used to tag descriptors
584 * @desc: the GPIO descriptor held by this event
585 * @eflags: the event flags this line was requested with
586 * @irq: the interrupt that trigger in response to events on this GPIO
587 * @wait: wait queue that handles blocking reads of events
588 * @events: KFIFO for the GPIO events
589 * @read_lock: mutex lock to protect reads from colliding with adding
590 * new events to the FIFO
592 struct lineevent_state {
593 struct gpio_device *gdev;
595 struct gpio_desc *desc;
598 wait_queue_head_t wait;
599 DECLARE_KFIFO(events, struct gpioevent_data, 16);
600 struct mutex read_lock;
603 #define GPIOEVENT_REQUEST_VALID_FLAGS \
604 (GPIOEVENT_REQUEST_RISING_EDGE | \
605 GPIOEVENT_REQUEST_FALLING_EDGE)
607 static unsigned int lineevent_poll(struct file *filep,
608 struct poll_table_struct *wait)
610 struct lineevent_state *le = filep->private_data;
611 unsigned int events = 0;
613 poll_wait(filep, &le->wait, wait);
615 if (!kfifo_is_empty(&le->events))
616 events = POLLIN | POLLRDNORM;
622 static ssize_t lineevent_read(struct file *filep,
627 struct lineevent_state *le = filep->private_data;
631 if (count < sizeof(struct gpioevent_data))
635 if (kfifo_is_empty(&le->events)) {
636 if (filep->f_flags & O_NONBLOCK)
639 ret = wait_event_interruptible(le->wait,
640 !kfifo_is_empty(&le->events));
645 if (mutex_lock_interruptible(&le->read_lock))
647 ret = kfifo_to_user(&le->events, buf, count, &copied);
648 mutex_unlock(&le->read_lock);
654 * If we couldn't read anything from the fifo (a different
655 * thread might have been faster) we either return -EAGAIN if
656 * the file descriptor is non-blocking, otherwise we go back to
657 * sleep and wait for more data to arrive.
659 if (copied == 0 && (filep->f_flags & O_NONBLOCK))
662 } while (copied == 0);
667 static int lineevent_release(struct inode *inode, struct file *filep)
669 struct lineevent_state *le = filep->private_data;
670 struct gpio_device *gdev = le->gdev;
672 free_irq(le->irq, le);
673 gpiod_free(le->desc);
676 put_device(&gdev->dev);
680 static long lineevent_ioctl(struct file *filep, unsigned int cmd,
683 struct lineevent_state *le = filep->private_data;
684 void __user *ip = (void __user *)arg;
685 struct gpiohandle_data ghd;
688 * We can get the value for an event line but not set it,
689 * because it is input by definition.
691 if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
694 memset(&ghd, 0, sizeof(ghd));
696 val = gpiod_get_value_cansleep(le->desc);
701 if (copy_to_user(ip, &ghd, sizeof(ghd)))
710 static long lineevent_ioctl_compat(struct file *filep, unsigned int cmd,
713 return lineevent_ioctl(filep, cmd, (unsigned long)compat_ptr(arg));
717 static const struct file_operations lineevent_fileops = {
718 .release = lineevent_release,
719 .read = lineevent_read,
720 .poll = lineevent_poll,
721 .owner = THIS_MODULE,
722 .llseek = noop_llseek,
723 .unlocked_ioctl = lineevent_ioctl,
725 .compat_ioctl = lineevent_ioctl_compat,
729 static irqreturn_t lineevent_irq_thread(int irq, void *p)
731 struct lineevent_state *le = p;
732 struct gpioevent_data ge;
735 ge.timestamp = ktime_get_real_ns();
736 level = gpiod_get_value_cansleep(le->desc);
738 if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE
739 && le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
741 /* Emit low-to-high event */
742 ge.id = GPIOEVENT_EVENT_RISING_EDGE;
744 /* Emit high-to-low event */
745 ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
746 } else if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE && level) {
747 /* Emit low-to-high event */
748 ge.id = GPIOEVENT_EVENT_RISING_EDGE;
749 } else if (le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE && !level) {
750 /* Emit high-to-low event */
751 ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
756 ret = kfifo_put(&le->events, ge);
758 wake_up_poll(&le->wait, POLLIN);
763 static int lineevent_create(struct gpio_device *gdev, void __user *ip)
765 struct gpioevent_request eventreq;
766 struct lineevent_state *le;
767 struct gpio_desc *desc;
776 if (copy_from_user(&eventreq, ip, sizeof(eventreq)))
779 le = kzalloc(sizeof(*le), GFP_KERNEL);
783 get_device(&gdev->dev);
785 /* Make sure this is terminated */
786 eventreq.consumer_label[sizeof(eventreq.consumer_label)-1] = '\0';
787 if (strlen(eventreq.consumer_label)) {
788 le->label = kstrdup(eventreq.consumer_label,
796 offset = eventreq.lineoffset;
797 lflags = eventreq.handleflags;
798 eflags = eventreq.eventflags;
800 if (offset >= gdev->ngpio) {
805 /* Return an error if a unknown flag is set */
806 if ((lflags & ~GPIOHANDLE_REQUEST_VALID_FLAGS) ||
807 (eflags & ~GPIOEVENT_REQUEST_VALID_FLAGS)) {
812 /* This is just wrong: we don't look for events on output lines */
813 if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
818 desc = &gdev->descs[offset];
819 ret = gpiod_request(desc, le->label);
825 if (lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW)
826 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
827 if (lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN)
828 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
829 if (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE)
830 set_bit(FLAG_OPEN_SOURCE, &desc->flags);
832 ret = gpiod_direction_input(desc);
836 le->irq = gpiod_to_irq(desc);
842 if (eflags & GPIOEVENT_REQUEST_RISING_EDGE)
843 irqflags |= IRQF_TRIGGER_RISING;
844 if (eflags & GPIOEVENT_REQUEST_FALLING_EDGE)
845 irqflags |= IRQF_TRIGGER_FALLING;
846 irqflags |= IRQF_ONESHOT;
847 irqflags |= IRQF_SHARED;
849 INIT_KFIFO(le->events);
850 init_waitqueue_head(&le->wait);
851 mutex_init(&le->read_lock);
853 /* Request a thread to read the events */
854 ret = request_threaded_irq(le->irq,
856 lineevent_irq_thread,
863 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
869 file = anon_inode_getfile("gpio-event",
872 O_RDONLY | O_CLOEXEC);
875 goto out_put_unused_fd;
879 if (copy_to_user(ip, &eventreq, sizeof(eventreq))) {
881 * fput() will trigger the release() callback, so do not go onto
882 * the regular error cleanup path here.
889 fd_install(fd, file);
896 free_irq(le->irq, le);
898 gpiod_free(le->desc);
903 put_device(&gdev->dev);
908 * gpio_ioctl() - ioctl handler for the GPIO chardev
910 static long gpio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
912 struct gpio_device *gdev = filp->private_data;
913 struct gpio_chip *chip = gdev->chip;
914 void __user *ip = (void __user *)arg;
916 /* We fail any subsequent ioctl():s when the chip is gone */
920 /* Fill in the struct and pass to userspace */
921 if (cmd == GPIO_GET_CHIPINFO_IOCTL) {
922 struct gpiochip_info chipinfo;
924 memset(&chipinfo, 0, sizeof(chipinfo));
926 strncpy(chipinfo.name, dev_name(&gdev->dev),
927 sizeof(chipinfo.name));
928 chipinfo.name[sizeof(chipinfo.name)-1] = '\0';
929 strncpy(chipinfo.label, gdev->label,
930 sizeof(chipinfo.label));
931 chipinfo.label[sizeof(chipinfo.label)-1] = '\0';
932 chipinfo.lines = gdev->ngpio;
933 if (copy_to_user(ip, &chipinfo, sizeof(chipinfo)))
936 } else if (cmd == GPIO_GET_LINEINFO_IOCTL) {
937 struct gpioline_info lineinfo;
938 struct gpio_desc *desc;
940 if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
942 if (lineinfo.line_offset >= gdev->ngpio)
945 desc = &gdev->descs[lineinfo.line_offset];
947 strncpy(lineinfo.name, desc->name,
948 sizeof(lineinfo.name));
949 lineinfo.name[sizeof(lineinfo.name)-1] = '\0';
951 lineinfo.name[0] = '\0';
954 strncpy(lineinfo.consumer, desc->label,
955 sizeof(lineinfo.consumer));
956 lineinfo.consumer[sizeof(lineinfo.consumer)-1] = '\0';
958 lineinfo.consumer[0] = '\0';
962 * Userspace only need to know that the kernel is using
963 * this GPIO so it can't use it.
966 if (test_bit(FLAG_REQUESTED, &desc->flags) ||
967 test_bit(FLAG_IS_HOGGED, &desc->flags) ||
968 test_bit(FLAG_USED_AS_IRQ, &desc->flags) ||
969 test_bit(FLAG_EXPORT, &desc->flags) ||
970 test_bit(FLAG_SYSFS, &desc->flags))
971 lineinfo.flags |= GPIOLINE_FLAG_KERNEL;
972 if (test_bit(FLAG_IS_OUT, &desc->flags))
973 lineinfo.flags |= GPIOLINE_FLAG_IS_OUT;
974 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
975 lineinfo.flags |= GPIOLINE_FLAG_ACTIVE_LOW;
976 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
977 lineinfo.flags |= GPIOLINE_FLAG_OPEN_DRAIN;
978 if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
979 lineinfo.flags |= GPIOLINE_FLAG_OPEN_SOURCE;
981 if (copy_to_user(ip, &lineinfo, sizeof(lineinfo)))
984 } else if (cmd == GPIO_GET_LINEHANDLE_IOCTL) {
985 return linehandle_create(gdev, ip);
986 } else if (cmd == GPIO_GET_LINEEVENT_IOCTL) {
987 return lineevent_create(gdev, ip);
993 static long gpio_ioctl_compat(struct file *filp, unsigned int cmd,
996 return gpio_ioctl(filp, cmd, (unsigned long)compat_ptr(arg));
1001 * gpio_chrdev_open() - open the chardev for ioctl operations
1002 * @inode: inode for this chardev
1003 * @filp: file struct for storing private data
1004 * Returns 0 on success
1006 static int gpio_chrdev_open(struct inode *inode, struct file *filp)
1008 struct gpio_device *gdev = container_of(inode->i_cdev,
1009 struct gpio_device, chrdev);
1011 /* Fail on open if the backing gpiochip is gone */
1014 get_device(&gdev->dev);
1015 filp->private_data = gdev;
1017 return nonseekable_open(inode, filp);
1021 * gpio_chrdev_release() - close chardev after ioctl operations
1022 * @inode: inode for this chardev
1023 * @filp: file struct for storing private data
1024 * Returns 0 on success
1026 static int gpio_chrdev_release(struct inode *inode, struct file *filp)
1028 struct gpio_device *gdev = container_of(inode->i_cdev,
1029 struct gpio_device, chrdev);
1031 put_device(&gdev->dev);
1036 static const struct file_operations gpio_fileops = {
1037 .release = gpio_chrdev_release,
1038 .open = gpio_chrdev_open,
1039 .owner = THIS_MODULE,
1040 .llseek = no_llseek,
1041 .unlocked_ioctl = gpio_ioctl,
1042 #ifdef CONFIG_COMPAT
1043 .compat_ioctl = gpio_ioctl_compat,
1047 static void gpiodevice_release(struct device *dev)
1049 struct gpio_device *gdev = dev_get_drvdata(dev);
1051 list_del(&gdev->list);
1052 ida_simple_remove(&gpio_ida, gdev->id);
1058 static int gpiochip_setup_dev(struct gpio_device *gdev)
1062 cdev_init(&gdev->chrdev, &gpio_fileops);
1063 gdev->chrdev.owner = THIS_MODULE;
1064 gdev->dev.devt = MKDEV(MAJOR(gpio_devt), gdev->id);
1066 status = cdev_device_add(&gdev->chrdev, &gdev->dev);
1070 chip_dbg(gdev->chip, "added GPIO chardev (%d:%d)\n",
1071 MAJOR(gpio_devt), gdev->id);
1073 status = gpiochip_sysfs_register(gdev);
1075 goto err_remove_device;
1077 /* From this point, the .release() function cleans up gpio_device */
1078 gdev->dev.release = gpiodevice_release;
1079 pr_debug("%s: registered GPIOs %d to %d on device: %s (%s)\n",
1080 __func__, gdev->base, gdev->base + gdev->ngpio - 1,
1081 dev_name(&gdev->dev), gdev->chip->label ? : "generic");
1086 cdev_device_del(&gdev->chrdev, &gdev->dev);
1090 static void gpiochip_setup_devs(void)
1092 struct gpio_device *gdev;
1095 list_for_each_entry(gdev, &gpio_devices, list) {
1096 err = gpiochip_setup_dev(gdev);
1098 pr_err("%s: Failed to initialize gpio device (%d)\n",
1099 dev_name(&gdev->dev), err);
1103 int gpiochip_add_data_with_key(struct gpio_chip *chip, void *data,
1104 struct lock_class_key *lock_key,
1105 struct lock_class_key *request_key)
1107 unsigned long flags;
1110 int base = chip->base;
1111 struct gpio_device *gdev;
1114 * First: allocate and populate the internal stat container, and
1115 * set up the struct device.
1117 gdev = kzalloc(sizeof(*gdev), GFP_KERNEL);
1120 gdev->dev.bus = &gpio_bus_type;
1122 chip->gpiodev = gdev;
1124 gdev->dev.parent = chip->parent;
1125 gdev->dev.of_node = chip->parent->of_node;
1128 #ifdef CONFIG_OF_GPIO
1129 /* If the gpiochip has an assigned OF node this takes precedence */
1131 gdev->dev.of_node = chip->of_node;
1134 gdev->id = ida_simple_get(&gpio_ida, 0, 0, GFP_KERNEL);
1139 dev_set_name(&gdev->dev, "gpiochip%d", gdev->id);
1140 device_initialize(&gdev->dev);
1141 dev_set_drvdata(&gdev->dev, gdev);
1142 if (chip->parent && chip->parent->driver)
1143 gdev->owner = chip->parent->driver->owner;
1144 else if (chip->owner)
1145 /* TODO: remove chip->owner */
1146 gdev->owner = chip->owner;
1148 gdev->owner = THIS_MODULE;
1150 gdev->descs = kcalloc(chip->ngpio, sizeof(gdev->descs[0]), GFP_KERNEL);
1156 if (chip->ngpio == 0) {
1157 chip_err(chip, "tried to insert a GPIO chip with zero lines\n");
1159 goto err_free_descs;
1163 gdev->label = kstrdup(chip->label, GFP_KERNEL);
1165 gdev->label = kstrdup("unknown", GFP_KERNEL);
1168 goto err_free_descs;
1171 gdev->ngpio = chip->ngpio;
1174 spin_lock_irqsave(&gpio_lock, flags);
1177 * TODO: this allocates a Linux GPIO number base in the global
1178 * GPIO numberspace for this chip. In the long run we want to
1179 * get *rid* of this numberspace and use only descriptors, but
1180 * it may be a pipe dream. It will not happen before we get rid
1181 * of the sysfs interface anyways.
1184 base = gpiochip_find_base(chip->ngpio);
1187 spin_unlock_irqrestore(&gpio_lock, flags);
1188 goto err_free_label;
1191 * TODO: it should not be necessary to reflect the assigned
1192 * base outside of the GPIO subsystem. Go over drivers and
1193 * see if anyone makes use of this, else drop this and assign
1200 status = gpiodev_add_to_list(gdev);
1202 spin_unlock_irqrestore(&gpio_lock, flags);
1203 goto err_free_label;
1206 spin_unlock_irqrestore(&gpio_lock, flags);
1208 for (i = 0; i < chip->ngpio; i++) {
1209 struct gpio_desc *desc = &gdev->descs[i];
1213 * REVISIT: most hardware initializes GPIOs as inputs
1214 * (often with pullups enabled) so power usage is
1215 * minimized. Linux code should set the gpio direction
1216 * first thing; but until it does, and in case
1217 * chip->get_direction is not set, we may expose the
1218 * wrong direction in sysfs.
1221 if (chip->get_direction) {
1223 * If we have .get_direction, set up the initial
1224 * direction flag from the hardware.
1226 int dir = chip->get_direction(chip, i);
1229 set_bit(FLAG_IS_OUT, &desc->flags);
1230 } else if (!chip->direction_input) {
1232 * If the chip lacks the .direction_input callback
1233 * we logically assume all lines are outputs.
1235 set_bit(FLAG_IS_OUT, &desc->flags);
1239 #ifdef CONFIG_PINCTRL
1240 INIT_LIST_HEAD(&gdev->pin_ranges);
1243 status = gpiochip_set_desc_names(chip);
1245 goto err_remove_from_list;
1247 status = gpiochip_irqchip_init_valid_mask(chip);
1249 goto err_remove_from_list;
1251 status = gpiochip_add_irqchip(chip, lock_key, request_key);
1253 goto err_remove_chip;
1255 status = of_gpiochip_add(chip);
1257 goto err_remove_chip;
1259 acpi_gpiochip_add(chip);
1262 * By first adding the chardev, and then adding the device,
1263 * we get a device node entry in sysfs under
1264 * /sys/bus/gpio/devices/gpiochipN/dev that can be used for
1265 * coldplug of device nodes and other udev business.
1266 * We can do this only if gpiolib has been initialized.
1267 * Otherwise, defer until later.
1269 if (gpiolib_initialized) {
1270 status = gpiochip_setup_dev(gdev);
1272 goto err_remove_chip;
1277 acpi_gpiochip_remove(chip);
1278 gpiochip_free_hogs(chip);
1279 of_gpiochip_remove(chip);
1280 gpiochip_irqchip_free_valid_mask(chip);
1281 err_remove_from_list:
1282 spin_lock_irqsave(&gpio_lock, flags);
1283 list_del(&gdev->list);
1284 spin_unlock_irqrestore(&gpio_lock, flags);
1290 ida_simple_remove(&gpio_ida, gdev->id);
1291 /* failures here can mean systems won't boot... */
1292 pr_err("%s: GPIOs %d..%d (%s) failed to register\n", __func__,
1293 gdev->base, gdev->base + gdev->ngpio - 1,
1294 chip->label ? : "generic");
1298 EXPORT_SYMBOL_GPL(gpiochip_add_data_with_key);
1301 * gpiochip_get_data() - get per-subdriver data for the chip
1305 * The per-subdriver data for the chip.
1307 void *gpiochip_get_data(struct gpio_chip *chip)
1309 return chip->gpiodev->data;
1311 EXPORT_SYMBOL_GPL(gpiochip_get_data);
1314 * gpiochip_remove() - unregister a gpio_chip
1315 * @chip: the chip to unregister
1317 * A gpio_chip with any GPIOs still requested may not be removed.
1319 void gpiochip_remove(struct gpio_chip *chip)
1321 struct gpio_device *gdev = chip->gpiodev;
1322 struct gpio_desc *desc;
1323 unsigned long flags;
1325 bool requested = false;
1327 /* FIXME: should the legacy sysfs handling be moved to gpio_device? */
1328 gpiochip_sysfs_unregister(gdev);
1329 gpiochip_free_hogs(chip);
1330 /* Numb the device, cancelling all outstanding operations */
1332 gpiochip_irqchip_remove(chip);
1333 acpi_gpiochip_remove(chip);
1334 gpiochip_remove_pin_ranges(chip);
1335 of_gpiochip_remove(chip);
1337 * We accept no more calls into the driver from this point, so
1338 * NULL the driver data pointer
1342 spin_lock_irqsave(&gpio_lock, flags);
1343 for (i = 0; i < gdev->ngpio; i++) {
1344 desc = &gdev->descs[i];
1345 if (test_bit(FLAG_REQUESTED, &desc->flags))
1348 spin_unlock_irqrestore(&gpio_lock, flags);
1351 dev_crit(&gdev->dev,
1352 "REMOVING GPIOCHIP WITH GPIOS STILL REQUESTED\n");
1355 * The gpiochip side puts its use of the device to rest here:
1356 * if there are no userspace clients, the chardev and device will
1357 * be removed, else it will be dangling until the last user is
1360 cdev_device_del(&gdev->chrdev, &gdev->dev);
1361 put_device(&gdev->dev);
1363 EXPORT_SYMBOL_GPL(gpiochip_remove);
1365 static void devm_gpio_chip_release(struct device *dev, void *res)
1367 struct gpio_chip *chip = *(struct gpio_chip **)res;
1369 gpiochip_remove(chip);
1372 static int devm_gpio_chip_match(struct device *dev, void *res, void *data)
1375 struct gpio_chip **r = res;
1386 * devm_gpiochip_add_data() - Resource manager piochip_add_data()
1387 * @dev: the device pointer on which irq_chip belongs to.
1388 * @chip: the chip to register, with chip->base initialized
1389 * @data: driver-private data associated with this chip
1391 * Context: potentially before irqs will work
1393 * The gpio chip automatically be released when the device is unbound.
1396 * A negative errno if the chip can't be registered, such as because the
1397 * chip->base is invalid or already associated with a different chip.
1398 * Otherwise it returns zero as a success code.
1400 int devm_gpiochip_add_data(struct device *dev, struct gpio_chip *chip,
1403 struct gpio_chip **ptr;
1406 ptr = devres_alloc(devm_gpio_chip_release, sizeof(*ptr),
1411 ret = gpiochip_add_data(chip, data);
1418 devres_add(dev, ptr);
1422 EXPORT_SYMBOL_GPL(devm_gpiochip_add_data);
1425 * devm_gpiochip_remove() - Resource manager of gpiochip_remove()
1426 * @dev: device for which which resource was allocated
1427 * @chip: the chip to remove
1429 * A gpio_chip with any GPIOs still requested may not be removed.
1431 void devm_gpiochip_remove(struct device *dev, struct gpio_chip *chip)
1435 ret = devres_release(dev, devm_gpio_chip_release,
1436 devm_gpio_chip_match, chip);
1439 EXPORT_SYMBOL_GPL(devm_gpiochip_remove);
1442 * gpiochip_find() - iterator for locating a specific gpio_chip
1443 * @data: data to pass to match function
1444 * @match: Callback function to check gpio_chip
1446 * Similar to bus_find_device. It returns a reference to a gpio_chip as
1447 * determined by a user supplied @match callback. The callback should return
1448 * 0 if the device doesn't match and non-zero if it does. If the callback is
1449 * non-zero, this function will return to the caller and not iterate over any
1452 struct gpio_chip *gpiochip_find(void *data,
1453 int (*match)(struct gpio_chip *chip,
1456 struct gpio_device *gdev;
1457 struct gpio_chip *chip = NULL;
1458 unsigned long flags;
1460 spin_lock_irqsave(&gpio_lock, flags);
1461 list_for_each_entry(gdev, &gpio_devices, list)
1462 if (gdev->chip && match(gdev->chip, data)) {
1467 spin_unlock_irqrestore(&gpio_lock, flags);
1471 EXPORT_SYMBOL_GPL(gpiochip_find);
1473 static int gpiochip_match_name(struct gpio_chip *chip, void *data)
1475 const char *name = data;
1477 return !strcmp(chip->label, name);
1480 static struct gpio_chip *find_chip_by_name(const char *name)
1482 return gpiochip_find((void *)name, gpiochip_match_name);
1485 #ifdef CONFIG_GPIOLIB_IRQCHIP
1488 * The following is irqchip helper code for gpiochips.
1491 static int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gpiochip)
1493 if (!gpiochip->irq.need_valid_mask)
1496 gpiochip->irq.valid_mask = kcalloc(BITS_TO_LONGS(gpiochip->ngpio),
1497 sizeof(long), GFP_KERNEL);
1498 if (!gpiochip->irq.valid_mask)
1501 /* Assume by default all GPIOs are valid */
1502 bitmap_fill(gpiochip->irq.valid_mask, gpiochip->ngpio);
1507 static void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gpiochip)
1509 kfree(gpiochip->irq.valid_mask);
1510 gpiochip->irq.valid_mask = NULL;
1513 static bool gpiochip_irqchip_irq_valid(const struct gpio_chip *gpiochip,
1514 unsigned int offset)
1516 /* No mask means all valid */
1517 if (likely(!gpiochip->irq.valid_mask))
1519 return test_bit(offset, gpiochip->irq.valid_mask);
1523 * gpiochip_set_cascaded_irqchip() - connects a cascaded irqchip to a gpiochip
1524 * @gpiochip: the gpiochip to set the irqchip chain to
1525 * @irqchip: the irqchip to chain to the gpiochip
1526 * @parent_irq: the irq number corresponding to the parent IRQ for this
1528 * @parent_handler: the parent interrupt handler for the accumulated IRQ
1529 * coming out of the gpiochip. If the interrupt is nested rather than
1530 * cascaded, pass NULL in this handler argument
1532 static void gpiochip_set_cascaded_irqchip(struct gpio_chip *gpiochip,
1533 struct irq_chip *irqchip,
1534 unsigned int parent_irq,
1535 irq_flow_handler_t parent_handler)
1537 unsigned int offset;
1539 if (!gpiochip->irq.domain) {
1540 chip_err(gpiochip, "called %s before setting up irqchip\n",
1545 if (parent_handler) {
1546 if (gpiochip->can_sleep) {
1548 "you cannot have chained interrupts on a "
1549 "chip that may sleep\n");
1553 * The parent irqchip is already using the chip_data for this
1554 * irqchip, so our callbacks simply use the handler_data.
1556 irq_set_chained_handler_and_data(parent_irq, parent_handler,
1559 gpiochip->irq.parents = &parent_irq;
1560 gpiochip->irq.num_parents = 1;
1563 /* Set the parent IRQ for all affected IRQs */
1564 for (offset = 0; offset < gpiochip->ngpio; offset++) {
1565 if (!gpiochip_irqchip_irq_valid(gpiochip, offset))
1567 irq_set_parent(irq_find_mapping(gpiochip->irq.domain, offset),
1573 * gpiochip_set_chained_irqchip() - connects a chained irqchip to a gpiochip
1574 * @gpiochip: the gpiochip to set the irqchip chain to
1575 * @irqchip: the irqchip to chain to the gpiochip
1576 * @parent_irq: the irq number corresponding to the parent IRQ for this
1578 * @parent_handler: the parent interrupt handler for the accumulated IRQ
1579 * coming out of the gpiochip. If the interrupt is nested rather than
1580 * cascaded, pass NULL in this handler argument
1582 void gpiochip_set_chained_irqchip(struct gpio_chip *gpiochip,
1583 struct irq_chip *irqchip,
1584 unsigned int parent_irq,
1585 irq_flow_handler_t parent_handler)
1587 if (gpiochip->irq.threaded) {
1588 chip_err(gpiochip, "tried to chain a threaded gpiochip\n");
1592 gpiochip_set_cascaded_irqchip(gpiochip, irqchip, parent_irq,
1595 EXPORT_SYMBOL_GPL(gpiochip_set_chained_irqchip);
1598 * gpiochip_set_nested_irqchip() - connects a nested irqchip to a gpiochip
1599 * @gpiochip: the gpiochip to set the irqchip nested handler to
1600 * @irqchip: the irqchip to nest to the gpiochip
1601 * @parent_irq: the irq number corresponding to the parent IRQ for this
1604 void gpiochip_set_nested_irqchip(struct gpio_chip *gpiochip,
1605 struct irq_chip *irqchip,
1606 unsigned int parent_irq)
1608 gpiochip_set_cascaded_irqchip(gpiochip, irqchip, parent_irq,
1611 EXPORT_SYMBOL_GPL(gpiochip_set_nested_irqchip);
1614 * gpiochip_irq_map() - maps an IRQ into a GPIO irqchip
1615 * @d: the irqdomain used by this irqchip
1616 * @irq: the global irq number used by this GPIO irqchip irq
1617 * @hwirq: the local IRQ/GPIO line offset on this gpiochip
1619 * This function will set up the mapping for a certain IRQ line on a
1620 * gpiochip by assigning the gpiochip as chip data, and using the irqchip
1621 * stored inside the gpiochip.
1623 int gpiochip_irq_map(struct irq_domain *d, unsigned int irq,
1624 irq_hw_number_t hwirq)
1626 struct gpio_chip *chip = d->host_data;
1629 if (!gpiochip_irqchip_irq_valid(chip, hwirq))
1632 irq_set_chip_data(irq, chip);
1634 * This lock class tells lockdep that GPIO irqs are in a different
1635 * category than their parents, so it won't report false recursion.
1637 irq_set_lockdep_class(irq, chip->irq.lock_key, chip->irq.request_key);
1638 irq_set_chip_and_handler(irq, chip->irq.chip, chip->irq.handler);
1639 /* Chips that use nested thread handlers have them marked */
1640 if (chip->irq.threaded)
1641 irq_set_nested_thread(irq, 1);
1642 irq_set_noprobe(irq);
1644 if (chip->irq.num_parents == 1)
1645 err = irq_set_parent(irq, chip->irq.parents[0]);
1646 else if (chip->irq.map)
1647 err = irq_set_parent(irq, chip->irq.map[hwirq]);
1653 * No set-up of the hardware will happen if IRQ_TYPE_NONE
1654 * is passed as default type.
1656 if (chip->irq.default_type != IRQ_TYPE_NONE)
1657 irq_set_irq_type(irq, chip->irq.default_type);
1661 EXPORT_SYMBOL_GPL(gpiochip_irq_map);
1663 void gpiochip_irq_unmap(struct irq_domain *d, unsigned int irq)
1665 struct gpio_chip *chip = d->host_data;
1667 if (chip->irq.threaded)
1668 irq_set_nested_thread(irq, 0);
1669 irq_set_chip_and_handler(irq, NULL, NULL);
1670 irq_set_chip_data(irq, NULL);
1672 EXPORT_SYMBOL_GPL(gpiochip_irq_unmap);
1674 static const struct irq_domain_ops gpiochip_domain_ops = {
1675 .map = gpiochip_irq_map,
1676 .unmap = gpiochip_irq_unmap,
1677 /* Virtually all GPIO irqchips are twocell:ed */
1678 .xlate = irq_domain_xlate_twocell,
1681 static int gpiochip_irq_reqres(struct irq_data *d)
1683 struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
1685 if (!try_module_get(chip->gpiodev->owner))
1688 if (gpiochip_lock_as_irq(chip, d->hwirq)) {
1690 "unable to lock HW IRQ %lu for IRQ\n",
1692 module_put(chip->gpiodev->owner);
1698 static void gpiochip_irq_relres(struct irq_data *d)
1700 struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
1702 gpiochip_unlock_as_irq(chip, d->hwirq);
1703 module_put(chip->gpiodev->owner);
1706 static int gpiochip_to_irq(struct gpio_chip *chip, unsigned offset)
1708 if (!gpiochip_irqchip_irq_valid(chip, offset))
1711 return irq_create_mapping(chip->irq.domain, offset);
1715 * gpiochip_add_irqchip() - adds an IRQ chip to a GPIO chip
1716 * @gpiochip: the GPIO chip to add the IRQ chip to
1717 * @lock_key: lockdep class for IRQ lock
1718 * @request_key: lockdep class for IRQ request
1720 static int gpiochip_add_irqchip(struct gpio_chip *gpiochip,
1721 struct lock_class_key *lock_key,
1722 struct lock_class_key *request_key)
1724 struct irq_chip *irqchip = gpiochip->irq.chip;
1725 const struct irq_domain_ops *ops;
1726 struct device_node *np;
1733 if (gpiochip->irq.parent_handler && gpiochip->can_sleep) {
1734 chip_err(gpiochip, "you cannot have chained interrupts on a "
1735 "chip that may sleep\n");
1739 np = gpiochip->gpiodev->dev.of_node;
1740 type = gpiochip->irq.default_type;
1743 * Specifying a default trigger is a terrible idea if DT or ACPI is
1744 * used to configure the interrupts, as you may end up with
1745 * conflicting triggers. Tell the user, and reset to NONE.
1747 if (WARN(np && type != IRQ_TYPE_NONE,
1748 "%s: Ignoring %u default trigger\n", np->full_name, type))
1749 type = IRQ_TYPE_NONE;
1751 if (has_acpi_companion(gpiochip->parent) && type != IRQ_TYPE_NONE) {
1752 acpi_handle_warn(ACPI_HANDLE(gpiochip->parent),
1753 "Ignoring %u default trigger\n", type);
1754 type = IRQ_TYPE_NONE;
1757 gpiochip->to_irq = gpiochip_to_irq;
1758 gpiochip->irq.default_type = type;
1759 gpiochip->irq.lock_key = lock_key;
1760 gpiochip->irq.request_key = request_key;
1762 if (gpiochip->irq.domain_ops)
1763 ops = gpiochip->irq.domain_ops;
1765 ops = &gpiochip_domain_ops;
1767 gpiochip->irq.domain = irq_domain_add_simple(np, gpiochip->ngpio,
1768 gpiochip->irq.first,
1770 if (!gpiochip->irq.domain)
1774 * It is possible for a driver to override this, but only if the
1775 * alternative functions are both implemented.
1777 if (!irqchip->irq_request_resources &&
1778 !irqchip->irq_release_resources) {
1779 irqchip->irq_request_resources = gpiochip_irq_reqres;
1780 irqchip->irq_release_resources = gpiochip_irq_relres;
1783 if (gpiochip->irq.parent_handler) {
1784 void *data = gpiochip->irq.parent_handler_data ?: gpiochip;
1786 for (i = 0; i < gpiochip->irq.num_parents; i++) {
1788 * The parent IRQ chip is already using the chip_data
1789 * for this IRQ chip, so our callbacks simply use the
1792 irq_set_chained_handler_and_data(gpiochip->irq.parents[i],
1793 gpiochip->irq.parent_handler,
1798 acpi_gpiochip_request_interrupts(gpiochip);
1804 * gpiochip_irqchip_remove() - removes an irqchip added to a gpiochip
1805 * @gpiochip: the gpiochip to remove the irqchip from
1807 * This is called only from gpiochip_remove()
1809 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip)
1811 unsigned int offset;
1813 acpi_gpiochip_free_interrupts(gpiochip);
1815 if (gpiochip->irq.chip && gpiochip->irq.parent_handler) {
1816 struct gpio_irq_chip *irq = &gpiochip->irq;
1819 for (i = 0; i < irq->num_parents; i++)
1820 irq_set_chained_handler_and_data(irq->parents[i],
1824 /* Remove all IRQ mappings and delete the domain */
1825 if (gpiochip->irq.domain) {
1828 for (offset = 0; offset < gpiochip->ngpio; offset++) {
1829 if (!gpiochip_irqchip_irq_valid(gpiochip, offset))
1832 irq = irq_find_mapping(gpiochip->irq.domain, offset);
1833 irq_dispose_mapping(irq);
1836 irq_domain_remove(gpiochip->irq.domain);
1839 if (gpiochip->irq.chip) {
1840 gpiochip->irq.chip->irq_request_resources = NULL;
1841 gpiochip->irq.chip->irq_release_resources = NULL;
1842 gpiochip->irq.chip = NULL;
1845 gpiochip_irqchip_free_valid_mask(gpiochip);
1849 * gpiochip_irqchip_add_key() - adds an irqchip to a gpiochip
1850 * @gpiochip: the gpiochip to add the irqchip to
1851 * @irqchip: the irqchip to add to the gpiochip
1852 * @first_irq: if not dynamically assigned, the base (first) IRQ to
1853 * allocate gpiochip irqs from
1854 * @handler: the irq handler to use (often a predefined irq core function)
1855 * @type: the default type for IRQs on this irqchip, pass IRQ_TYPE_NONE
1856 * to have the core avoid setting up any default type in the hardware.
1857 * @threaded: whether this irqchip uses a nested thread handler
1858 * @lock_key: lockdep class for IRQ lock
1859 * @request_key: lockdep class for IRQ request
1861 * This function closely associates a certain irqchip with a certain
1862 * gpiochip, providing an irq domain to translate the local IRQs to
1863 * global irqs in the gpiolib core, and making sure that the gpiochip
1864 * is passed as chip data to all related functions. Driver callbacks
1865 * need to use gpiochip_get_data() to get their local state containers back
1866 * from the gpiochip passed as chip data. An irqdomain will be stored
1867 * in the gpiochip that shall be used by the driver to handle IRQ number
1868 * translation. The gpiochip will need to be initialized and registered
1869 * before calling this function.
1871 * This function will handle two cell:ed simple IRQs and assumes all
1872 * the pins on the gpiochip can generate a unique IRQ. Everything else
1873 * need to be open coded.
1875 int gpiochip_irqchip_add_key(struct gpio_chip *gpiochip,
1876 struct irq_chip *irqchip,
1877 unsigned int first_irq,
1878 irq_flow_handler_t handler,
1881 struct lock_class_key *lock_key,
1882 struct lock_class_key *request_key)
1884 struct device_node *of_node;
1886 if (!gpiochip || !irqchip)
1889 if (!gpiochip->parent) {
1890 pr_err("missing gpiochip .dev parent pointer\n");
1893 gpiochip->irq.threaded = threaded;
1894 of_node = gpiochip->parent->of_node;
1895 #ifdef CONFIG_OF_GPIO
1897 * If the gpiochip has an assigned OF node this takes precedence
1898 * FIXME: get rid of this and use gpiochip->parent->of_node
1901 if (gpiochip->of_node)
1902 of_node = gpiochip->of_node;
1905 * Specifying a default trigger is a terrible idea if DT or ACPI is
1906 * used to configure the interrupts, as you may end-up with
1907 * conflicting triggers. Tell the user, and reset to NONE.
1909 if (WARN(of_node && type != IRQ_TYPE_NONE,
1910 "%pOF: Ignoring %d default trigger\n", of_node, type))
1911 type = IRQ_TYPE_NONE;
1912 if (has_acpi_companion(gpiochip->parent) && type != IRQ_TYPE_NONE) {
1913 acpi_handle_warn(ACPI_HANDLE(gpiochip->parent),
1914 "Ignoring %d default trigger\n", type);
1915 type = IRQ_TYPE_NONE;
1918 gpiochip->irq.chip = irqchip;
1919 gpiochip->irq.handler = handler;
1920 gpiochip->irq.default_type = type;
1921 gpiochip->to_irq = gpiochip_to_irq;
1922 gpiochip->irq.lock_key = lock_key;
1923 gpiochip->irq.request_key = request_key;
1924 gpiochip->irq.domain = irq_domain_add_simple(of_node,
1925 gpiochip->ngpio, first_irq,
1926 &gpiochip_domain_ops, gpiochip);
1927 if (!gpiochip->irq.domain) {
1928 gpiochip->irq.chip = NULL;
1933 * It is possible for a driver to override this, but only if the
1934 * alternative functions are both implemented.
1936 if (!irqchip->irq_request_resources &&
1937 !irqchip->irq_release_resources) {
1938 irqchip->irq_request_resources = gpiochip_irq_reqres;
1939 irqchip->irq_release_resources = gpiochip_irq_relres;
1942 acpi_gpiochip_request_interrupts(gpiochip);
1946 EXPORT_SYMBOL_GPL(gpiochip_irqchip_add_key);
1948 #else /* CONFIG_GPIOLIB_IRQCHIP */
1950 static inline int gpiochip_add_irqchip(struct gpio_chip *gpiochip,
1951 struct lock_class_key *lock_key,
1952 struct lock_class_key *request_key)
1957 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip) {}
1958 static inline int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gpiochip)
1962 static inline void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gpiochip)
1965 #endif /* CONFIG_GPIOLIB_IRQCHIP */
1968 * gpiochip_generic_request() - request the gpio function for a pin
1969 * @chip: the gpiochip owning the GPIO
1970 * @offset: the offset of the GPIO to request for GPIO function
1972 int gpiochip_generic_request(struct gpio_chip *chip, unsigned offset)
1974 return pinctrl_gpio_request(chip->gpiodev->base + offset);
1976 EXPORT_SYMBOL_GPL(gpiochip_generic_request);
1979 * gpiochip_generic_free() - free the gpio function from a pin
1980 * @chip: the gpiochip to request the gpio function for
1981 * @offset: the offset of the GPIO to free from GPIO function
1983 void gpiochip_generic_free(struct gpio_chip *chip, unsigned offset)
1985 pinctrl_gpio_free(chip->gpiodev->base + offset);
1987 EXPORT_SYMBOL_GPL(gpiochip_generic_free);
1990 * gpiochip_generic_config() - apply configuration for a pin
1991 * @chip: the gpiochip owning the GPIO
1992 * @offset: the offset of the GPIO to apply the configuration
1993 * @config: the configuration to be applied
1995 int gpiochip_generic_config(struct gpio_chip *chip, unsigned offset,
1996 unsigned long config)
1998 return pinctrl_gpio_set_config(chip->gpiodev->base + offset, config);
2000 EXPORT_SYMBOL_GPL(gpiochip_generic_config);
2002 #ifdef CONFIG_PINCTRL
2005 * gpiochip_add_pingroup_range() - add a range for GPIO <-> pin mapping
2006 * @chip: the gpiochip to add the range for
2007 * @pctldev: the pin controller to map to
2008 * @gpio_offset: the start offset in the current gpio_chip number space
2009 * @pin_group: name of the pin group inside the pin controller
2011 int gpiochip_add_pingroup_range(struct gpio_chip *chip,
2012 struct pinctrl_dev *pctldev,
2013 unsigned int gpio_offset, const char *pin_group)
2015 struct gpio_pin_range *pin_range;
2016 struct gpio_device *gdev = chip->gpiodev;
2019 pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
2021 chip_err(chip, "failed to allocate pin ranges\n");
2025 /* Use local offset as range ID */
2026 pin_range->range.id = gpio_offset;
2027 pin_range->range.gc = chip;
2028 pin_range->range.name = chip->label;
2029 pin_range->range.base = gdev->base + gpio_offset;
2030 pin_range->pctldev = pctldev;
2032 ret = pinctrl_get_group_pins(pctldev, pin_group,
2033 &pin_range->range.pins,
2034 &pin_range->range.npins);
2040 pinctrl_add_gpio_range(pctldev, &pin_range->range);
2042 chip_dbg(chip, "created GPIO range %d->%d ==> %s PINGRP %s\n",
2043 gpio_offset, gpio_offset + pin_range->range.npins - 1,
2044 pinctrl_dev_get_devname(pctldev), pin_group);
2046 list_add_tail(&pin_range->node, &gdev->pin_ranges);
2050 EXPORT_SYMBOL_GPL(gpiochip_add_pingroup_range);
2053 * gpiochip_add_pin_range() - add a range for GPIO <-> pin mapping
2054 * @chip: the gpiochip to add the range for
2055 * @pinctl_name: the dev_name() of the pin controller to map to
2056 * @gpio_offset: the start offset in the current gpio_chip number space
2057 * @pin_offset: the start offset in the pin controller number space
2058 * @npins: the number of pins from the offset of each pin space (GPIO and
2059 * pin controller) to accumulate in this range
2062 * 0 on success, or a negative error-code on failure.
2064 int gpiochip_add_pin_range(struct gpio_chip *chip, const char *pinctl_name,
2065 unsigned int gpio_offset, unsigned int pin_offset,
2068 struct gpio_pin_range *pin_range;
2069 struct gpio_device *gdev = chip->gpiodev;
2072 pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
2074 chip_err(chip, "failed to allocate pin ranges\n");
2078 /* Use local offset as range ID */
2079 pin_range->range.id = gpio_offset;
2080 pin_range->range.gc = chip;
2081 pin_range->range.name = chip->label;
2082 pin_range->range.base = gdev->base + gpio_offset;
2083 pin_range->range.pin_base = pin_offset;
2084 pin_range->range.npins = npins;
2085 pin_range->pctldev = pinctrl_find_and_add_gpio_range(pinctl_name,
2087 if (IS_ERR(pin_range->pctldev)) {
2088 ret = PTR_ERR(pin_range->pctldev);
2089 chip_err(chip, "could not create pin range\n");
2093 chip_dbg(chip, "created GPIO range %d->%d ==> %s PIN %d->%d\n",
2094 gpio_offset, gpio_offset + npins - 1,
2096 pin_offset, pin_offset + npins - 1);
2098 list_add_tail(&pin_range->node, &gdev->pin_ranges);
2102 EXPORT_SYMBOL_GPL(gpiochip_add_pin_range);
2105 * gpiochip_remove_pin_ranges() - remove all the GPIO <-> pin mappings
2106 * @chip: the chip to remove all the mappings for
2108 void gpiochip_remove_pin_ranges(struct gpio_chip *chip)
2110 struct gpio_pin_range *pin_range, *tmp;
2111 struct gpio_device *gdev = chip->gpiodev;
2113 list_for_each_entry_safe(pin_range, tmp, &gdev->pin_ranges, node) {
2114 list_del(&pin_range->node);
2115 pinctrl_remove_gpio_range(pin_range->pctldev,
2120 EXPORT_SYMBOL_GPL(gpiochip_remove_pin_ranges);
2122 #endif /* CONFIG_PINCTRL */
2124 /* These "optional" allocation calls help prevent drivers from stomping
2125 * on each other, and help provide better diagnostics in debugfs.
2126 * They're called even less than the "set direction" calls.
2128 static int gpiod_request_commit(struct gpio_desc *desc, const char *label)
2130 struct gpio_chip *chip = desc->gdev->chip;
2132 unsigned long flags;
2134 spin_lock_irqsave(&gpio_lock, flags);
2136 /* NOTE: gpio_request() can be called in early boot,
2137 * before IRQs are enabled, for non-sleeping (SOC) GPIOs.
2140 if (test_and_set_bit(FLAG_REQUESTED, &desc->flags) == 0) {
2141 desc_set_label(desc, label ? : "?");
2148 if (chip->request) {
2149 /* chip->request may sleep */
2150 spin_unlock_irqrestore(&gpio_lock, flags);
2151 status = chip->request(chip, gpio_chip_hwgpio(desc));
2152 spin_lock_irqsave(&gpio_lock, flags);
2155 desc_set_label(desc, NULL);
2156 clear_bit(FLAG_REQUESTED, &desc->flags);
2160 if (chip->get_direction) {
2161 /* chip->get_direction may sleep */
2162 spin_unlock_irqrestore(&gpio_lock, flags);
2163 gpiod_get_direction(desc);
2164 spin_lock_irqsave(&gpio_lock, flags);
2167 spin_unlock_irqrestore(&gpio_lock, flags);
2172 * This descriptor validation needs to be inserted verbatim into each
2173 * function taking a descriptor, so we need to use a preprocessor
2174 * macro to avoid endless duplication. If the desc is NULL it is an
2175 * optional GPIO and calls should just bail out.
2177 #define VALIDATE_DESC(desc) do { \
2180 if (IS_ERR(desc)) { \
2181 pr_warn("%s: invalid GPIO (errorpointer)\n", __func__); \
2182 return PTR_ERR(desc); \
2184 if (!desc->gdev) { \
2185 pr_warn("%s: invalid GPIO (no device)\n", __func__); \
2188 if ( !desc->gdev->chip ) { \
2189 dev_warn(&desc->gdev->dev, \
2190 "%s: backing chip is gone\n", __func__); \
2194 #define VALIDATE_DESC_VOID(desc) do { \
2197 if (IS_ERR(desc)) { \
2198 pr_warn("%s: invalid GPIO (errorpointer)\n", __func__); \
2201 if (!desc->gdev) { \
2202 pr_warn("%s: invalid GPIO (no device)\n", __func__); \
2205 if (!desc->gdev->chip) { \
2206 dev_warn(&desc->gdev->dev, \
2207 "%s: backing chip is gone\n", __func__); \
2212 int gpiod_request(struct gpio_desc *desc, const char *label)
2214 int status = -EPROBE_DEFER;
2215 struct gpio_device *gdev;
2217 VALIDATE_DESC(desc);
2220 if (try_module_get(gdev->owner)) {
2221 status = gpiod_request_commit(desc, label);
2223 module_put(gdev->owner);
2225 get_device(&gdev->dev);
2229 gpiod_dbg(desc, "%s: status %d\n", __func__, status);
2234 static bool gpiod_free_commit(struct gpio_desc *desc)
2237 unsigned long flags;
2238 struct gpio_chip *chip;
2242 gpiod_unexport(desc);
2244 spin_lock_irqsave(&gpio_lock, flags);
2246 chip = desc->gdev->chip;
2247 if (chip && test_bit(FLAG_REQUESTED, &desc->flags)) {
2249 spin_unlock_irqrestore(&gpio_lock, flags);
2250 might_sleep_if(chip->can_sleep);
2251 chip->free(chip, gpio_chip_hwgpio(desc));
2252 spin_lock_irqsave(&gpio_lock, flags);
2254 desc_set_label(desc, NULL);
2255 clear_bit(FLAG_ACTIVE_LOW, &desc->flags);
2256 clear_bit(FLAG_REQUESTED, &desc->flags);
2257 clear_bit(FLAG_OPEN_DRAIN, &desc->flags);
2258 clear_bit(FLAG_OPEN_SOURCE, &desc->flags);
2259 clear_bit(FLAG_IS_HOGGED, &desc->flags);
2263 spin_unlock_irqrestore(&gpio_lock, flags);
2267 void gpiod_free(struct gpio_desc *desc)
2269 if (desc && desc->gdev && gpiod_free_commit(desc)) {
2270 module_put(desc->gdev->owner);
2271 put_device(&desc->gdev->dev);
2273 WARN_ON(extra_checks);
2278 * gpiochip_is_requested - return string iff signal was requested
2279 * @chip: controller managing the signal
2280 * @offset: of signal within controller's 0..(ngpio - 1) range
2282 * Returns NULL if the GPIO is not currently requested, else a string.
2283 * The string returned is the label passed to gpio_request(); if none has been
2284 * passed it is a meaningless, non-NULL constant.
2286 * This function is for use by GPIO controller drivers. The label can
2287 * help with diagnostics, and knowing that the signal is used as a GPIO
2288 * can help avoid accidentally multiplexing it to another controller.
2290 const char *gpiochip_is_requested(struct gpio_chip *chip, unsigned offset)
2292 struct gpio_desc *desc;
2294 if (offset >= chip->ngpio)
2297 desc = &chip->gpiodev->descs[offset];
2299 if (test_bit(FLAG_REQUESTED, &desc->flags) == 0)
2303 EXPORT_SYMBOL_GPL(gpiochip_is_requested);
2306 * gpiochip_request_own_desc - Allow GPIO chip to request its own descriptor
2308 * @hwnum: hardware number of the GPIO for which to request the descriptor
2309 * @label: label for the GPIO
2311 * Function allows GPIO chip drivers to request and use their own GPIO
2312 * descriptors via gpiolib API. Difference to gpiod_request() is that this
2313 * function will not increase reference count of the GPIO chip module. This
2314 * allows the GPIO chip module to be unloaded as needed (we assume that the
2315 * GPIO chip driver handles freeing the GPIOs it has requested).
2318 * A pointer to the GPIO descriptor, or an ERR_PTR()-encoded negative error
2321 struct gpio_desc *gpiochip_request_own_desc(struct gpio_chip *chip, u16 hwnum,
2324 struct gpio_desc *desc = gpiochip_get_desc(chip, hwnum);
2328 chip_err(chip, "failed to get GPIO descriptor\n");
2332 err = gpiod_request_commit(desc, label);
2334 return ERR_PTR(err);
2338 EXPORT_SYMBOL_GPL(gpiochip_request_own_desc);
2341 * gpiochip_free_own_desc - Free GPIO requested by the chip driver
2342 * @desc: GPIO descriptor to free
2344 * Function frees the given GPIO requested previously with
2345 * gpiochip_request_own_desc().
2347 void gpiochip_free_own_desc(struct gpio_desc *desc)
2350 gpiod_free_commit(desc);
2352 EXPORT_SYMBOL_GPL(gpiochip_free_own_desc);
2355 * Drivers MUST set GPIO direction before making get/set calls. In
2356 * some cases this is done in early boot, before IRQs are enabled.
2358 * As a rule these aren't called more than once (except for drivers
2359 * using the open-drain emulation idiom) so these are natural places
2360 * to accumulate extra debugging checks. Note that we can't (yet)
2361 * rely on gpio_request() having been called beforehand.
2365 * gpiod_direction_input - set the GPIO direction to input
2366 * @desc: GPIO to set to input
2368 * Set the direction of the passed GPIO to input, such as gpiod_get_value() can
2369 * be called safely on it.
2371 * Return 0 in case of success, else an error code.
2373 int gpiod_direction_input(struct gpio_desc *desc)
2375 struct gpio_chip *chip;
2376 int status = -EINVAL;
2378 VALIDATE_DESC(desc);
2379 chip = desc->gdev->chip;
2381 if (!chip->get || !chip->direction_input) {
2383 "%s: missing get() or direction_input() operations\n",
2388 status = chip->direction_input(chip, gpio_chip_hwgpio(desc));
2390 clear_bit(FLAG_IS_OUT, &desc->flags);
2392 trace_gpio_direction(desc_to_gpio(desc), 1, status);
2396 EXPORT_SYMBOL_GPL(gpiod_direction_input);
2398 static int gpio_set_drive_single_ended(struct gpio_chip *gc, unsigned offset,
2399 enum pin_config_param mode)
2401 unsigned long config = { PIN_CONF_PACKED(mode, 0) };
2403 return gc->set_config ? gc->set_config(gc, offset, config) : -ENOTSUPP;
2406 static int gpiod_direction_output_raw_commit(struct gpio_desc *desc, int value)
2408 struct gpio_chip *gc = desc->gdev->chip;
2412 if (!gc->set || !gc->direction_output) {
2414 "%s: missing set() or direction_output() operations\n",
2419 ret = gc->direction_output(gc, gpio_chip_hwgpio(desc), val);
2421 set_bit(FLAG_IS_OUT, &desc->flags);
2422 trace_gpio_value(desc_to_gpio(desc), 0, val);
2423 trace_gpio_direction(desc_to_gpio(desc), 0, ret);
2428 * gpiod_direction_output_raw - set the GPIO direction to output
2429 * @desc: GPIO to set to output
2430 * @value: initial output value of the GPIO
2432 * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
2433 * be called safely on it. The initial value of the output must be specified
2434 * as raw value on the physical line without regard for the ACTIVE_LOW status.
2436 * Return 0 in case of success, else an error code.
2438 int gpiod_direction_output_raw(struct gpio_desc *desc, int value)
2440 VALIDATE_DESC(desc);
2441 return gpiod_direction_output_raw_commit(desc, value);
2443 EXPORT_SYMBOL_GPL(gpiod_direction_output_raw);
2446 * gpiod_direction_output - set the GPIO direction to output
2447 * @desc: GPIO to set to output
2448 * @value: initial output value of the GPIO
2450 * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
2451 * be called safely on it. The initial value of the output must be specified
2452 * as the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
2455 * Return 0 in case of success, else an error code.
2457 int gpiod_direction_output(struct gpio_desc *desc, int value)
2459 struct gpio_chip *gc = desc->gdev->chip;
2462 VALIDATE_DESC(desc);
2463 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2468 /* GPIOs used for IRQs shall not be set as output */
2469 if (test_bit(FLAG_USED_AS_IRQ, &desc->flags)) {
2471 "%s: tried to set a GPIO tied to an IRQ as output\n",
2476 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags)) {
2477 /* First see if we can enable open drain in hardware */
2478 ret = gpio_set_drive_single_ended(gc, gpio_chip_hwgpio(desc),
2479 PIN_CONFIG_DRIVE_OPEN_DRAIN);
2481 goto set_output_value;
2482 /* Emulate open drain by not actively driving the line high */
2484 return gpiod_direction_input(desc);
2486 else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags)) {
2487 ret = gpio_set_drive_single_ended(gc, gpio_chip_hwgpio(desc),
2488 PIN_CONFIG_DRIVE_OPEN_SOURCE);
2490 goto set_output_value;
2491 /* Emulate open source by not actively driving the line low */
2493 return gpiod_direction_input(desc);
2495 gpio_set_drive_single_ended(gc, gpio_chip_hwgpio(desc),
2496 PIN_CONFIG_DRIVE_PUSH_PULL);
2500 return gpiod_direction_output_raw_commit(desc, value);
2502 EXPORT_SYMBOL_GPL(gpiod_direction_output);
2505 * gpiod_set_debounce - sets @debounce time for a GPIO
2506 * @desc: descriptor of the GPIO for which to set debounce time
2507 * @debounce: debounce time in microseconds
2510 * 0 on success, %-ENOTSUPP if the controller doesn't support setting the
2513 int gpiod_set_debounce(struct gpio_desc *desc, unsigned debounce)
2515 struct gpio_chip *chip;
2516 unsigned long config;
2518 VALIDATE_DESC(desc);
2519 chip = desc->gdev->chip;
2520 if (!chip->set || !chip->set_config) {
2522 "%s: missing set() or set_config() operations\n",
2527 config = pinconf_to_config_packed(PIN_CONFIG_INPUT_DEBOUNCE, debounce);
2528 return chip->set_config(chip, gpio_chip_hwgpio(desc), config);
2530 EXPORT_SYMBOL_GPL(gpiod_set_debounce);
2533 * gpiod_is_active_low - test whether a GPIO is active-low or not
2534 * @desc: the gpio descriptor to test
2536 * Returns 1 if the GPIO is active-low, 0 otherwise.
2538 int gpiod_is_active_low(const struct gpio_desc *desc)
2540 VALIDATE_DESC(desc);
2541 return test_bit(FLAG_ACTIVE_LOW, &desc->flags);
2543 EXPORT_SYMBOL_GPL(gpiod_is_active_low);
2545 /* I/O calls are only valid after configuration completed; the relevant
2546 * "is this a valid GPIO" error checks should already have been done.
2548 * "Get" operations are often inlinable as reading a pin value register,
2549 * and masking the relevant bit in that register.
2551 * When "set" operations are inlinable, they involve writing that mask to
2552 * one register to set a low value, or a different register to set it high.
2553 * Otherwise locking is needed, so there may be little value to inlining.
2555 *------------------------------------------------------------------------
2557 * IMPORTANT!!! The hot paths -- get/set value -- assume that callers
2558 * have requested the GPIO. That can include implicit requesting by
2559 * a direction setting call. Marking a gpio as requested locks its chip
2560 * in memory, guaranteeing that these table lookups need no more locking
2561 * and that gpiochip_remove() will fail.
2563 * REVISIT when debugging, consider adding some instrumentation to ensure
2564 * that the GPIO was actually requested.
2567 static int gpiod_get_raw_value_commit(const struct gpio_desc *desc)
2569 struct gpio_chip *chip;
2573 chip = desc->gdev->chip;
2574 offset = gpio_chip_hwgpio(desc);
2575 value = chip->get ? chip->get(chip, offset) : -EIO;
2576 value = value < 0 ? value : !!value;
2577 trace_gpio_value(desc_to_gpio(desc), 1, value);
2581 static int gpio_chip_get_multiple(struct gpio_chip *chip,
2582 unsigned long *mask, unsigned long *bits)
2584 if (chip->get_multiple) {
2585 return chip->get_multiple(chip, mask, bits);
2586 } else if (chip->get) {
2589 for_each_set_bit(i, mask, chip->ngpio) {
2590 value = chip->get(chip, i);
2593 __assign_bit(i, bits, value);
2600 int gpiod_get_array_value_complex(bool raw, bool can_sleep,
2601 unsigned int array_size,
2602 struct gpio_desc **desc_array,
2607 while (i < array_size) {
2608 struct gpio_chip *chip = desc_array[i]->gdev->chip;
2609 unsigned long mask[BITS_TO_LONGS(chip->ngpio)];
2610 unsigned long bits[BITS_TO_LONGS(chip->ngpio)];
2614 WARN_ON(chip->can_sleep);
2616 /* collect all inputs belonging to the same chip */
2618 memset(mask, 0, sizeof(mask));
2620 const struct gpio_desc *desc = desc_array[i];
2621 int hwgpio = gpio_chip_hwgpio(desc);
2623 __set_bit(hwgpio, mask);
2625 } while ((i < array_size) &&
2626 (desc_array[i]->gdev->chip == chip));
2628 ret = gpio_chip_get_multiple(chip, mask, bits);
2632 for (j = first; j < i; j++) {
2633 const struct gpio_desc *desc = desc_array[j];
2634 int hwgpio = gpio_chip_hwgpio(desc);
2635 int value = test_bit(hwgpio, bits);
2637 if (!raw && test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2639 value_array[j] = value;
2640 trace_gpio_value(desc_to_gpio(desc), 1, value);
2647 * gpiod_get_raw_value() - return a gpio's raw value
2648 * @desc: gpio whose value will be returned
2650 * Return the GPIO's raw value, i.e. the value of the physical line disregarding
2651 * its ACTIVE_LOW status, or negative errno on failure.
2653 * This function should be called from contexts where we cannot sleep, and will
2654 * complain if the GPIO chip functions potentially sleep.
2656 int gpiod_get_raw_value(const struct gpio_desc *desc)
2658 VALIDATE_DESC(desc);
2659 /* Should be using gpio_get_value_cansleep() */
2660 WARN_ON(desc->gdev->chip->can_sleep);
2661 return gpiod_get_raw_value_commit(desc);
2663 EXPORT_SYMBOL_GPL(gpiod_get_raw_value);
2666 * gpiod_get_value() - return a gpio's value
2667 * @desc: gpio whose value will be returned
2669 * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
2670 * account, or negative errno on failure.
2672 * This function should be called from contexts where we cannot sleep, and will
2673 * complain if the GPIO chip functions potentially sleep.
2675 int gpiod_get_value(const struct gpio_desc *desc)
2679 VALIDATE_DESC(desc);
2680 /* Should be using gpio_get_value_cansleep() */
2681 WARN_ON(desc->gdev->chip->can_sleep);
2683 value = gpiod_get_raw_value_commit(desc);
2687 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2692 EXPORT_SYMBOL_GPL(gpiod_get_value);
2695 * gpiod_get_raw_array_value() - read raw values from an array of GPIOs
2696 * @array_size: number of elements in the descriptor / value arrays
2697 * @desc_array: array of GPIO descriptors whose values will be read
2698 * @value_array: array to store the read values
2700 * Read the raw values of the GPIOs, i.e. the values of the physical lines
2701 * without regard for their ACTIVE_LOW status. Return 0 in case of success,
2702 * else an error code.
2704 * This function should be called from contexts where we cannot sleep,
2705 * and it will complain if the GPIO chip functions potentially sleep.
2707 int gpiod_get_raw_array_value(unsigned int array_size,
2708 struct gpio_desc **desc_array, int *value_array)
2712 return gpiod_get_array_value_complex(true, false, array_size,
2713 desc_array, value_array);
2715 EXPORT_SYMBOL_GPL(gpiod_get_raw_array_value);
2718 * gpiod_get_array_value() - read values from an array of GPIOs
2719 * @array_size: number of elements in the descriptor / value arrays
2720 * @desc_array: array of GPIO descriptors whose values will be read
2721 * @value_array: array to store the read values
2723 * Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
2724 * into account. Return 0 in case of success, else an error code.
2726 * This function should be called from contexts where we cannot sleep,
2727 * and it will complain if the GPIO chip functions potentially sleep.
2729 int gpiod_get_array_value(unsigned int array_size,
2730 struct gpio_desc **desc_array, int *value_array)
2734 return gpiod_get_array_value_complex(false, false, array_size,
2735 desc_array, value_array);
2737 EXPORT_SYMBOL_GPL(gpiod_get_array_value);
2740 * gpio_set_open_drain_value_commit() - Set the open drain gpio's value.
2741 * @desc: gpio descriptor whose state need to be set.
2742 * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
2744 static void gpio_set_open_drain_value_commit(struct gpio_desc *desc, bool value)
2747 struct gpio_chip *chip = desc->gdev->chip;
2748 int offset = gpio_chip_hwgpio(desc);
2751 err = chip->direction_input(chip, offset);
2753 clear_bit(FLAG_IS_OUT, &desc->flags);
2755 err = chip->direction_output(chip, offset, 0);
2757 set_bit(FLAG_IS_OUT, &desc->flags);
2759 trace_gpio_direction(desc_to_gpio(desc), value, err);
2762 "%s: Error in set_value for open drain err %d\n",
2767 * _gpio_set_open_source_value() - Set the open source gpio's value.
2768 * @desc: gpio descriptor whose state need to be set.
2769 * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
2771 static void gpio_set_open_source_value_commit(struct gpio_desc *desc, bool value)
2774 struct gpio_chip *chip = desc->gdev->chip;
2775 int offset = gpio_chip_hwgpio(desc);
2778 err = chip->direction_output(chip, offset, 1);
2780 set_bit(FLAG_IS_OUT, &desc->flags);
2782 err = chip->direction_input(chip, offset);
2784 clear_bit(FLAG_IS_OUT, &desc->flags);
2786 trace_gpio_direction(desc_to_gpio(desc), !value, err);
2789 "%s: Error in set_value for open source err %d\n",
2793 static void gpiod_set_raw_value_commit(struct gpio_desc *desc, bool value)
2795 struct gpio_chip *chip;
2797 chip = desc->gdev->chip;
2798 trace_gpio_value(desc_to_gpio(desc), 0, value);
2799 chip->set(chip, gpio_chip_hwgpio(desc), value);
2803 * set multiple outputs on the same chip;
2804 * use the chip's set_multiple function if available;
2805 * otherwise set the outputs sequentially;
2806 * @mask: bit mask array; one bit per output; BITS_PER_LONG bits per word
2807 * defines which outputs are to be changed
2808 * @bits: bit value array; one bit per output; BITS_PER_LONG bits per word
2809 * defines the values the outputs specified by mask are to be set to
2811 static void gpio_chip_set_multiple(struct gpio_chip *chip,
2812 unsigned long *mask, unsigned long *bits)
2814 if (chip->set_multiple) {
2815 chip->set_multiple(chip, mask, bits);
2819 /* set outputs if the corresponding mask bit is set */
2820 for_each_set_bit(i, mask, chip->ngpio)
2821 chip->set(chip, i, test_bit(i, bits));
2825 void gpiod_set_array_value_complex(bool raw, bool can_sleep,
2826 unsigned int array_size,
2827 struct gpio_desc **desc_array,
2832 while (i < array_size) {
2833 struct gpio_chip *chip = desc_array[i]->gdev->chip;
2834 unsigned long mask[BITS_TO_LONGS(chip->ngpio)];
2835 unsigned long bits[BITS_TO_LONGS(chip->ngpio)];
2839 WARN_ON(chip->can_sleep);
2841 memset(mask, 0, sizeof(mask));
2843 struct gpio_desc *desc = desc_array[i];
2844 int hwgpio = gpio_chip_hwgpio(desc);
2845 int value = value_array[i];
2847 if (!raw && test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2849 trace_gpio_value(desc_to_gpio(desc), 0, value);
2851 * collect all normal outputs belonging to the same chip
2852 * open drain and open source outputs are set individually
2854 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags) && !raw) {
2855 gpio_set_open_drain_value_commit(desc, value);
2856 } else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags) && !raw) {
2857 gpio_set_open_source_value_commit(desc, value);
2859 __set_bit(hwgpio, mask);
2861 __set_bit(hwgpio, bits);
2863 __clear_bit(hwgpio, bits);
2867 } while ((i < array_size) &&
2868 (desc_array[i]->gdev->chip == chip));
2869 /* push collected bits to outputs */
2871 gpio_chip_set_multiple(chip, mask, bits);
2876 * gpiod_set_raw_value() - assign a gpio's raw value
2877 * @desc: gpio whose value will be assigned
2878 * @value: value to assign
2880 * Set the raw value of the GPIO, i.e. the value of its physical line without
2881 * regard for its ACTIVE_LOW status.
2883 * This function should be called from contexts where we cannot sleep, and will
2884 * complain if the GPIO chip functions potentially sleep.
2886 void gpiod_set_raw_value(struct gpio_desc *desc, int value)
2888 VALIDATE_DESC_VOID(desc);
2889 /* Should be using gpiod_set_value_cansleep() */
2890 WARN_ON(desc->gdev->chip->can_sleep);
2891 gpiod_set_raw_value_commit(desc, value);
2893 EXPORT_SYMBOL_GPL(gpiod_set_raw_value);
2896 * gpiod_set_value_nocheck() - set a GPIO line value without checking
2897 * @desc: the descriptor to set the value on
2898 * @value: value to set
2900 * This sets the value of a GPIO line backing a descriptor, applying
2901 * different semantic quirks like active low and open drain/source
2904 static void gpiod_set_value_nocheck(struct gpio_desc *desc, int value)
2906 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2908 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
2909 gpio_set_open_drain_value_commit(desc, value);
2910 else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
2911 gpio_set_open_source_value_commit(desc, value);
2913 gpiod_set_raw_value_commit(desc, value);
2917 * gpiod_set_value() - assign a gpio's value
2918 * @desc: gpio whose value will be assigned
2919 * @value: value to assign
2921 * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW,
2922 * OPEN_DRAIN and OPEN_SOURCE flags into account.
2924 * This function should be called from contexts where we cannot sleep, and will
2925 * complain if the GPIO chip functions potentially sleep.
2927 void gpiod_set_value(struct gpio_desc *desc, int value)
2929 VALIDATE_DESC_VOID(desc);
2930 WARN_ON(desc->gdev->chip->can_sleep);
2931 gpiod_set_value_nocheck(desc, value);
2933 EXPORT_SYMBOL_GPL(gpiod_set_value);
2936 * gpiod_set_raw_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 raw values of the GPIOs, i.e. the values of the physical lines
2942 * without regard for 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_raw_array_value(unsigned int array_size,
2948 struct gpio_desc **desc_array, int *value_array)
2952 gpiod_set_array_value_complex(true, false, array_size, desc_array,
2955 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value);
2958 * gpiod_set_array_value() - assign values to an array of GPIOs
2959 * @array_size: number of elements in the descriptor / value arrays
2960 * @desc_array: array of GPIO descriptors whose values will be assigned
2961 * @value_array: array of values to assign
2963 * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
2966 * This function should be called from contexts where we cannot sleep, and will
2967 * complain if the GPIO chip functions potentially sleep.
2969 void gpiod_set_array_value(unsigned int array_size,
2970 struct gpio_desc **desc_array, int *value_array)
2974 gpiod_set_array_value_complex(false, false, array_size, desc_array,
2977 EXPORT_SYMBOL_GPL(gpiod_set_array_value);
2980 * gpiod_cansleep() - report whether gpio value access may sleep
2981 * @desc: gpio to check
2984 int gpiod_cansleep(const struct gpio_desc *desc)
2986 VALIDATE_DESC(desc);
2987 return desc->gdev->chip->can_sleep;
2989 EXPORT_SYMBOL_GPL(gpiod_cansleep);
2992 * gpiod_to_irq() - return the IRQ corresponding to a GPIO
2993 * @desc: gpio whose IRQ will be returned (already requested)
2995 * Return the IRQ corresponding to the passed GPIO, or an error code in case of
2998 int gpiod_to_irq(const struct gpio_desc *desc)
3000 struct gpio_chip *chip;
3004 * Cannot VALIDATE_DESC() here as gpiod_to_irq() consumer semantics
3005 * requires this function to not return zero on an invalid descriptor
3006 * but rather a negative error number.
3008 if (!desc || IS_ERR(desc) || !desc->gdev || !desc->gdev->chip)
3011 chip = desc->gdev->chip;
3012 offset = gpio_chip_hwgpio(desc);
3014 int retirq = chip->to_irq(chip, offset);
3016 /* Zero means NO_IRQ */
3024 EXPORT_SYMBOL_GPL(gpiod_to_irq);
3027 * gpiochip_lock_as_irq() - lock a GPIO to be used as IRQ
3028 * @chip: the chip the GPIO to lock belongs to
3029 * @offset: the offset of the GPIO to lock as IRQ
3031 * This is used directly by GPIO drivers that want to lock down
3032 * a certain GPIO line to be used for IRQs.
3034 int gpiochip_lock_as_irq(struct gpio_chip *chip, unsigned int offset)
3036 struct gpio_desc *desc;
3038 desc = gpiochip_get_desc(chip, offset);
3040 return PTR_ERR(desc);
3043 * If it's fast: flush the direction setting if something changed
3046 if (!chip->can_sleep && chip->get_direction) {
3047 int dir = chip->get_direction(chip, offset);
3050 clear_bit(FLAG_IS_OUT, &desc->flags);
3052 set_bit(FLAG_IS_OUT, &desc->flags);
3055 if (test_bit(FLAG_IS_OUT, &desc->flags)) {
3057 "%s: tried to flag a GPIO set as output for IRQ\n",
3062 set_bit(FLAG_USED_AS_IRQ, &desc->flags);
3065 * If the consumer has not set up a label (such as when the
3066 * IRQ is referenced from .to_irq()) we set up a label here
3067 * so it is clear this is used as an interrupt.
3070 desc_set_label(desc, "interrupt");
3074 EXPORT_SYMBOL_GPL(gpiochip_lock_as_irq);
3077 * gpiochip_unlock_as_irq() - unlock a GPIO used as IRQ
3078 * @chip: the chip the GPIO to lock belongs to
3079 * @offset: the offset of the GPIO to lock as IRQ
3081 * This is used directly by GPIO drivers that want to indicate
3082 * that a certain GPIO is no longer used exclusively for IRQ.
3084 void gpiochip_unlock_as_irq(struct gpio_chip *chip, unsigned int offset)
3086 struct gpio_desc *desc;
3088 desc = gpiochip_get_desc(chip, offset);
3092 clear_bit(FLAG_USED_AS_IRQ, &desc->flags);
3094 /* If we only had this marking, erase it */
3095 if (desc->label && !strcmp(desc->label, "interrupt"))
3096 desc_set_label(desc, NULL);
3098 EXPORT_SYMBOL_GPL(gpiochip_unlock_as_irq);
3100 bool gpiochip_line_is_irq(struct gpio_chip *chip, unsigned int offset)
3102 if (offset >= chip->ngpio)
3105 return test_bit(FLAG_USED_AS_IRQ, &chip->gpiodev->descs[offset].flags);
3107 EXPORT_SYMBOL_GPL(gpiochip_line_is_irq);
3109 bool gpiochip_line_is_open_drain(struct gpio_chip *chip, unsigned int offset)
3111 if (offset >= chip->ngpio)
3114 return test_bit(FLAG_OPEN_DRAIN, &chip->gpiodev->descs[offset].flags);
3116 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_drain);
3118 bool gpiochip_line_is_open_source(struct gpio_chip *chip, unsigned int offset)
3120 if (offset >= chip->ngpio)
3123 return test_bit(FLAG_OPEN_SOURCE, &chip->gpiodev->descs[offset].flags);
3125 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_source);
3127 bool gpiochip_line_is_persistent(struct gpio_chip *chip, unsigned int offset)
3129 if (offset >= chip->ngpio)
3132 return !test_bit(FLAG_SLEEP_MAY_LOSE_VALUE,
3133 &chip->gpiodev->descs[offset].flags);
3135 EXPORT_SYMBOL_GPL(gpiochip_line_is_persistent);
3138 * gpiod_get_raw_value_cansleep() - return a gpio's raw value
3139 * @desc: gpio whose value will be returned
3141 * Return the GPIO's raw value, i.e. the value of the physical line disregarding
3142 * its ACTIVE_LOW status, or negative errno on failure.
3144 * This function is to be called from contexts that can sleep.
3146 int gpiod_get_raw_value_cansleep(const struct gpio_desc *desc)
3148 might_sleep_if(extra_checks);
3149 VALIDATE_DESC(desc);
3150 return gpiod_get_raw_value_commit(desc);
3152 EXPORT_SYMBOL_GPL(gpiod_get_raw_value_cansleep);
3155 * gpiod_get_value_cansleep() - return a gpio's value
3156 * @desc: gpio whose value will be returned
3158 * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
3159 * account, or negative errno on failure.
3161 * This function is to be called from contexts that can sleep.
3163 int gpiod_get_value_cansleep(const struct gpio_desc *desc)
3167 might_sleep_if(extra_checks);
3168 VALIDATE_DESC(desc);
3169 value = gpiod_get_raw_value_commit(desc);
3173 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3178 EXPORT_SYMBOL_GPL(gpiod_get_value_cansleep);
3181 * gpiod_get_raw_array_value_cansleep() - read raw values from an array of GPIOs
3182 * @array_size: number of elements in the descriptor / value arrays
3183 * @desc_array: array of GPIO descriptors whose values will be read
3184 * @value_array: array to store the read values
3186 * Read the raw values of the GPIOs, i.e. the values of the physical lines
3187 * without regard for their ACTIVE_LOW status. Return 0 in case of success,
3188 * else an error code.
3190 * This function is to be called from contexts that can sleep.
3192 int gpiod_get_raw_array_value_cansleep(unsigned int array_size,
3193 struct gpio_desc **desc_array,
3196 might_sleep_if(extra_checks);
3199 return gpiod_get_array_value_complex(true, true, array_size,
3200 desc_array, value_array);
3202 EXPORT_SYMBOL_GPL(gpiod_get_raw_array_value_cansleep);
3205 * gpiod_get_array_value_cansleep() - read values from an array of GPIOs
3206 * @array_size: number of elements in the descriptor / value arrays
3207 * @desc_array: array of GPIO descriptors whose values will be read
3208 * @value_array: array to store the read values
3210 * Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3211 * into account. Return 0 in case of success, else an error code.
3213 * This function is to be called from contexts that can sleep.
3215 int gpiod_get_array_value_cansleep(unsigned int array_size,
3216 struct gpio_desc **desc_array,
3219 might_sleep_if(extra_checks);
3222 return gpiod_get_array_value_complex(false, true, array_size,
3223 desc_array, value_array);
3225 EXPORT_SYMBOL_GPL(gpiod_get_array_value_cansleep);
3228 * gpiod_set_raw_value_cansleep() - assign a gpio's raw value
3229 * @desc: gpio whose value will be assigned
3230 * @value: value to assign
3232 * Set the raw value of the GPIO, i.e. the value of its physical line without
3233 * regard for its ACTIVE_LOW status.
3235 * This function is to be called from contexts that can sleep.
3237 void gpiod_set_raw_value_cansleep(struct gpio_desc *desc, int value)
3239 might_sleep_if(extra_checks);
3240 VALIDATE_DESC_VOID(desc);
3241 gpiod_set_raw_value_commit(desc, value);
3243 EXPORT_SYMBOL_GPL(gpiod_set_raw_value_cansleep);
3246 * gpiod_set_value_cansleep() - assign a gpio's value
3247 * @desc: gpio whose value will be assigned
3248 * @value: value to assign
3250 * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
3253 * This function is to be called from contexts that can sleep.
3255 void gpiod_set_value_cansleep(struct gpio_desc *desc, int value)
3257 might_sleep_if(extra_checks);
3258 VALIDATE_DESC_VOID(desc);
3259 gpiod_set_value_nocheck(desc, value);
3261 EXPORT_SYMBOL_GPL(gpiod_set_value_cansleep);
3264 * gpiod_set_raw_array_value_cansleep() - assign values to an array of GPIOs
3265 * @array_size: number of elements in the descriptor / value arrays
3266 * @desc_array: array of GPIO descriptors whose values will be assigned
3267 * @value_array: array of values to assign
3269 * Set the raw values of the GPIOs, i.e. the values of the physical lines
3270 * without regard for their ACTIVE_LOW status.
3272 * This function is to be called from contexts that can sleep.
3274 void gpiod_set_raw_array_value_cansleep(unsigned int array_size,
3275 struct gpio_desc **desc_array,
3278 might_sleep_if(extra_checks);
3281 gpiod_set_array_value_complex(true, true, array_size, desc_array,
3284 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value_cansleep);
3287 * gpiod_add_lookup_tables() - register GPIO device consumers
3288 * @tables: list of tables of consumers to register
3289 * @n: number of tables in the list
3291 void gpiod_add_lookup_tables(struct gpiod_lookup_table **tables, size_t n)
3295 mutex_lock(&gpio_lookup_lock);
3297 for (i = 0; i < n; i++)
3298 list_add_tail(&tables[i]->list, &gpio_lookup_list);
3300 mutex_unlock(&gpio_lookup_lock);
3304 * gpiod_set_array_value_cansleep() - assign values to an array of GPIOs
3305 * @array_size: number of elements in the descriptor / value arrays
3306 * @desc_array: array of GPIO descriptors whose values will be assigned
3307 * @value_array: array of values to assign
3309 * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3312 * This function is to be called from contexts that can sleep.
3314 void gpiod_set_array_value_cansleep(unsigned int array_size,
3315 struct gpio_desc **desc_array,
3318 might_sleep_if(extra_checks);
3321 gpiod_set_array_value_complex(false, true, array_size, desc_array,
3324 EXPORT_SYMBOL_GPL(gpiod_set_array_value_cansleep);
3327 * gpiod_add_lookup_table() - register GPIO device consumers
3328 * @table: table of consumers to register
3330 void gpiod_add_lookup_table(struct gpiod_lookup_table *table)
3332 mutex_lock(&gpio_lookup_lock);
3334 list_add_tail(&table->list, &gpio_lookup_list);
3336 mutex_unlock(&gpio_lookup_lock);
3338 EXPORT_SYMBOL_GPL(gpiod_add_lookup_table);
3341 * gpiod_remove_lookup_table() - unregister GPIO device consumers
3342 * @table: table of consumers to unregister
3344 void gpiod_remove_lookup_table(struct gpiod_lookup_table *table)
3346 mutex_lock(&gpio_lookup_lock);
3348 list_del(&table->list);
3350 mutex_unlock(&gpio_lookup_lock);
3352 EXPORT_SYMBOL_GPL(gpiod_remove_lookup_table);
3354 static struct gpiod_lookup_table *gpiod_find_lookup_table(struct device *dev)
3356 const char *dev_id = dev ? dev_name(dev) : NULL;
3357 struct gpiod_lookup_table *table;
3359 mutex_lock(&gpio_lookup_lock);
3361 list_for_each_entry(table, &gpio_lookup_list, list) {
3362 if (table->dev_id && dev_id) {
3364 * Valid strings on both ends, must be identical to have
3367 if (!strcmp(table->dev_id, dev_id))
3371 * One of the pointers is NULL, so both must be to have
3374 if (dev_id == table->dev_id)
3381 mutex_unlock(&gpio_lookup_lock);
3385 static struct gpio_desc *gpiod_find(struct device *dev, const char *con_id,
3387 enum gpio_lookup_flags *flags)
3389 struct gpio_desc *desc = ERR_PTR(-ENOENT);
3390 struct gpiod_lookup_table *table;
3391 struct gpiod_lookup *p;
3393 table = gpiod_find_lookup_table(dev);
3397 for (p = &table->table[0]; p->chip_label; p++) {
3398 struct gpio_chip *chip;
3400 /* idx must always match exactly */
3404 /* If the lookup entry has a con_id, require exact match */
3405 if (p->con_id && (!con_id || strcmp(p->con_id, con_id)))
3408 chip = find_chip_by_name(p->chip_label);
3411 dev_err(dev, "cannot find GPIO chip %s\n",
3413 return ERR_PTR(-ENODEV);
3416 if (chip->ngpio <= p->chip_hwnum) {
3418 "requested GPIO %d is out of range [0..%d] for chip %s\n",
3419 idx, chip->ngpio, chip->label);
3420 return ERR_PTR(-EINVAL);
3423 desc = gpiochip_get_desc(chip, p->chip_hwnum);
3432 static int dt_gpio_count(struct device *dev, const char *con_id)
3438 for (i = 0; i < ARRAY_SIZE(gpio_suffixes); i++) {
3440 snprintf(propname, sizeof(propname), "%s-%s",
3441 con_id, gpio_suffixes[i]);
3443 snprintf(propname, sizeof(propname), "%s",
3446 ret = of_gpio_named_count(dev->of_node, propname);
3450 return ret ? ret : -ENOENT;
3453 static int platform_gpio_count(struct device *dev, const char *con_id)
3455 struct gpiod_lookup_table *table;
3456 struct gpiod_lookup *p;
3457 unsigned int count = 0;
3459 table = gpiod_find_lookup_table(dev);
3463 for (p = &table->table[0]; p->chip_label; p++) {
3464 if ((con_id && p->con_id && !strcmp(con_id, p->con_id)) ||
3465 (!con_id && !p->con_id))
3475 * gpiod_count - return the number of GPIOs associated with a device / function
3476 * or -ENOENT if no GPIO has been assigned to the requested function
3477 * @dev: GPIO consumer, can be NULL for system-global GPIOs
3478 * @con_id: function within the GPIO consumer
3480 int gpiod_count(struct device *dev, const char *con_id)
3482 int count = -ENOENT;
3484 if (IS_ENABLED(CONFIG_OF) && dev && dev->of_node)
3485 count = dt_gpio_count(dev, con_id);
3486 else if (IS_ENABLED(CONFIG_ACPI) && dev && ACPI_HANDLE(dev))
3487 count = acpi_gpio_count(dev, con_id);
3490 count = platform_gpio_count(dev, con_id);
3494 EXPORT_SYMBOL_GPL(gpiod_count);
3497 * gpiod_get - obtain a GPIO for a given GPIO function
3498 * @dev: GPIO consumer, can be NULL for system-global GPIOs
3499 * @con_id: function within the GPIO consumer
3500 * @flags: optional GPIO initialization flags
3502 * Return the GPIO descriptor corresponding to the function con_id of device
3503 * dev, -ENOENT if no GPIO has been assigned to the requested function, or
3504 * another IS_ERR() code if an error occurred while trying to acquire the GPIO.
3506 struct gpio_desc *__must_check gpiod_get(struct device *dev, const char *con_id,
3507 enum gpiod_flags flags)
3509 return gpiod_get_index(dev, con_id, 0, flags);
3511 EXPORT_SYMBOL_GPL(gpiod_get);
3514 * gpiod_get_optional - obtain an optional GPIO for a given GPIO function
3515 * @dev: GPIO consumer, can be NULL for system-global GPIOs
3516 * @con_id: function within the GPIO consumer
3517 * @flags: optional GPIO initialization flags
3519 * This is equivalent to gpiod_get(), except that when no GPIO was assigned to
3520 * the requested function it will return NULL. This is convenient for drivers
3521 * that need to handle optional GPIOs.
3523 struct gpio_desc *__must_check gpiod_get_optional(struct device *dev,
3525 enum gpiod_flags flags)
3527 return gpiod_get_index_optional(dev, con_id, 0, flags);
3529 EXPORT_SYMBOL_GPL(gpiod_get_optional);
3533 * gpiod_configure_flags - helper function to configure a given GPIO
3534 * @desc: gpio whose value will be assigned
3535 * @con_id: function within the GPIO consumer
3536 * @lflags: gpio_lookup_flags - returned from of_find_gpio() or
3538 * @dflags: gpiod_flags - optional GPIO initialization flags
3540 * Return 0 on success, -ENOENT if no GPIO has been assigned to the
3541 * requested function and/or index, or another IS_ERR() code if an error
3542 * occurred while trying to acquire the GPIO.
3544 int gpiod_configure_flags(struct gpio_desc *desc, const char *con_id,
3545 unsigned long lflags, enum gpiod_flags dflags)
3549 if (lflags & GPIO_ACTIVE_LOW)
3550 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
3552 if (lflags & GPIO_OPEN_DRAIN)
3553 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
3554 else if (dflags & GPIOD_FLAGS_BIT_OPEN_DRAIN) {
3556 * This enforces open drain mode from the consumer side.
3557 * This is necessary for some busses like I2C, but the lookup
3558 * should *REALLY* have specified them as open drain in the
3559 * first place, so print a little warning here.
3561 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
3563 "enforced open drain please flag it properly in DT/ACPI DSDT/board file\n");
3566 if (lflags & GPIO_OPEN_SOURCE)
3567 set_bit(FLAG_OPEN_SOURCE, &desc->flags);
3568 if (lflags & GPIO_SLEEP_MAY_LOSE_VALUE)
3569 set_bit(FLAG_SLEEP_MAY_LOSE_VALUE, &desc->flags);
3571 /* No particular flag request, return here... */
3572 if (!(dflags & GPIOD_FLAGS_BIT_DIR_SET)) {
3573 pr_debug("no flags found for %s\n", con_id);
3578 if (dflags & GPIOD_FLAGS_BIT_DIR_OUT)
3579 status = gpiod_direction_output(desc,
3580 !!(dflags & GPIOD_FLAGS_BIT_DIR_VAL));
3582 status = gpiod_direction_input(desc);
3588 * gpiod_get_index - obtain a GPIO from a multi-index GPIO function
3589 * @dev: GPIO consumer, can be NULL for system-global GPIOs
3590 * @con_id: function within the GPIO consumer
3591 * @idx: index of the GPIO to obtain in the consumer
3592 * @flags: optional GPIO initialization flags
3594 * This variant of gpiod_get() allows to access GPIOs other than the first
3595 * defined one for functions that define several GPIOs.
3597 * Return a valid GPIO descriptor, -ENOENT if no GPIO has been assigned to the
3598 * requested function and/or index, or another IS_ERR() code if an error
3599 * occurred while trying to acquire the GPIO.
3601 struct gpio_desc *__must_check gpiod_get_index(struct device *dev,
3604 enum gpiod_flags flags)
3606 struct gpio_desc *desc = NULL;
3608 enum gpio_lookup_flags lookupflags = 0;
3610 dev_dbg(dev, "GPIO lookup for consumer %s\n", con_id);
3613 /* Using device tree? */
3614 if (IS_ENABLED(CONFIG_OF) && dev->of_node) {
3615 dev_dbg(dev, "using device tree for GPIO lookup\n");
3616 desc = of_find_gpio(dev, con_id, idx, &lookupflags);
3617 } else if (ACPI_COMPANION(dev)) {
3618 dev_dbg(dev, "using ACPI for GPIO lookup\n");
3619 desc = acpi_find_gpio(dev, con_id, idx, &flags, &lookupflags);
3624 * Either we are not using DT or ACPI, or their lookup did not return
3625 * a result. In that case, use platform lookup as a fallback.
3627 if (!desc || desc == ERR_PTR(-ENOENT)) {
3628 dev_dbg(dev, "using lookup tables for GPIO lookup\n");
3629 desc = gpiod_find(dev, con_id, idx, &lookupflags);
3633 dev_dbg(dev, "lookup for GPIO %s failed\n", con_id);
3637 status = gpiod_request(desc, con_id);
3639 return ERR_PTR(status);
3641 status = gpiod_configure_flags(desc, con_id, lookupflags, flags);
3643 dev_dbg(dev, "setup of GPIO %s failed\n", con_id);
3645 return ERR_PTR(status);
3650 EXPORT_SYMBOL_GPL(gpiod_get_index);
3653 * fwnode_get_named_gpiod - obtain a GPIO from firmware node
3654 * @fwnode: handle of the firmware node
3655 * @propname: name of the firmware property representing the GPIO
3656 * @index: index of the GPIO to obtain in the consumer
3657 * @dflags: GPIO initialization flags
3658 * @label: label to attach to the requested GPIO
3660 * This function can be used for drivers that get their configuration
3663 * Function properly finds the corresponding GPIO using whatever is the
3664 * underlying firmware interface and then makes sure that the GPIO
3665 * descriptor is requested before it is returned to the caller.
3668 * On successful request the GPIO pin is configured in accordance with
3671 * In case of error an ERR_PTR() is returned.
3673 struct gpio_desc *fwnode_get_named_gpiod(struct fwnode_handle *fwnode,
3674 const char *propname, int index,
3675 enum gpiod_flags dflags,
3678 struct gpio_desc *desc = ERR_PTR(-ENODEV);
3679 unsigned long lflags = 0;
3680 bool active_low = false;
3681 bool single_ended = false;
3682 bool open_drain = false;
3686 return ERR_PTR(-EINVAL);
3688 if (is_of_node(fwnode)) {
3689 enum of_gpio_flags flags;
3691 desc = of_get_named_gpiod_flags(to_of_node(fwnode), propname,
3693 if (!IS_ERR(desc)) {
3694 active_low = flags & OF_GPIO_ACTIVE_LOW;
3695 single_ended = flags & OF_GPIO_SINGLE_ENDED;
3696 open_drain = flags & OF_GPIO_OPEN_DRAIN;
3698 } else if (is_acpi_node(fwnode)) {
3699 struct acpi_gpio_info info;
3701 desc = acpi_node_get_gpiod(fwnode, propname, index, &info);
3702 if (!IS_ERR(desc)) {
3703 active_low = info.polarity == GPIO_ACTIVE_LOW;
3704 ret = acpi_gpio_update_gpiod_flags(&dflags, info.flags);
3706 pr_debug("Override GPIO initialization flags\n");
3713 ret = gpiod_request(desc, label);
3715 return ERR_PTR(ret);
3718 lflags |= GPIO_ACTIVE_LOW;
3722 lflags |= GPIO_OPEN_DRAIN;
3724 lflags |= GPIO_OPEN_SOURCE;
3727 ret = gpiod_configure_flags(desc, propname, lflags, dflags);
3730 return ERR_PTR(ret);
3735 EXPORT_SYMBOL_GPL(fwnode_get_named_gpiod);
3738 * gpiod_get_index_optional - obtain an optional GPIO from a multi-index GPIO
3740 * @dev: GPIO consumer, can be NULL for system-global GPIOs
3741 * @con_id: function within the GPIO consumer
3742 * @index: index of the GPIO to obtain in the consumer
3743 * @flags: optional GPIO initialization flags
3745 * This is equivalent to gpiod_get_index(), except that when no GPIO with the
3746 * specified index was assigned to the requested function it will return NULL.
3747 * This is convenient for drivers that need to handle optional GPIOs.
3749 struct gpio_desc *__must_check gpiod_get_index_optional(struct device *dev,
3752 enum gpiod_flags flags)
3754 struct gpio_desc *desc;
3756 desc = gpiod_get_index(dev, con_id, index, flags);
3758 if (PTR_ERR(desc) == -ENOENT)
3764 EXPORT_SYMBOL_GPL(gpiod_get_index_optional);
3767 * gpiod_hog - Hog the specified GPIO desc given the provided flags
3768 * @desc: gpio whose value will be assigned
3769 * @name: gpio line name
3770 * @lflags: gpio_lookup_flags - returned from of_find_gpio() or
3772 * @dflags: gpiod_flags - optional GPIO initialization flags
3774 int gpiod_hog(struct gpio_desc *desc, const char *name,
3775 unsigned long lflags, enum gpiod_flags dflags)
3777 struct gpio_chip *chip;
3778 struct gpio_desc *local_desc;
3782 chip = gpiod_to_chip(desc);
3783 hwnum = gpio_chip_hwgpio(desc);
3785 local_desc = gpiochip_request_own_desc(chip, hwnum, name);
3786 if (IS_ERR(local_desc)) {
3787 status = PTR_ERR(local_desc);
3788 pr_err("requesting hog GPIO %s (chip %s, offset %d) failed, %d\n",
3789 name, chip->label, hwnum, status);
3793 status = gpiod_configure_flags(desc, name, lflags, dflags);
3795 pr_err("setup of hog GPIO %s (chip %s, offset %d) failed, %d\n",
3796 name, chip->label, hwnum, status);
3797 gpiochip_free_own_desc(desc);
3801 /* Mark GPIO as hogged so it can be identified and removed later */
3802 set_bit(FLAG_IS_HOGGED, &desc->flags);
3804 pr_info("GPIO line %d (%s) hogged as %s%s\n",
3805 desc_to_gpio(desc), name,
3806 (dflags&GPIOD_FLAGS_BIT_DIR_OUT) ? "output" : "input",
3807 (dflags&GPIOD_FLAGS_BIT_DIR_OUT) ?
3808 (dflags&GPIOD_FLAGS_BIT_DIR_VAL) ? "/high" : "/low":"");
3814 * gpiochip_free_hogs - Scan gpio-controller chip and release GPIO hog
3815 * @chip: gpio chip to act on
3817 * This is only used by of_gpiochip_remove to free hogged gpios
3819 static void gpiochip_free_hogs(struct gpio_chip *chip)
3823 for (id = 0; id < chip->ngpio; id++) {
3824 if (test_bit(FLAG_IS_HOGGED, &chip->gpiodev->descs[id].flags))
3825 gpiochip_free_own_desc(&chip->gpiodev->descs[id]);
3830 * gpiod_get_array - obtain multiple GPIOs from a multi-index GPIO function
3831 * @dev: GPIO consumer, can be NULL for system-global GPIOs
3832 * @con_id: function within the GPIO consumer
3833 * @flags: optional GPIO initialization flags
3835 * This function acquires all the GPIOs defined under a given function.
3837 * Return a struct gpio_descs containing an array of descriptors, -ENOENT if
3838 * no GPIO has been assigned to the requested function, or another IS_ERR()
3839 * code if an error occurred while trying to acquire the GPIOs.
3841 struct gpio_descs *__must_check gpiod_get_array(struct device *dev,
3843 enum gpiod_flags flags)
3845 struct gpio_desc *desc;
3846 struct gpio_descs *descs;
3849 count = gpiod_count(dev, con_id);
3851 return ERR_PTR(count);
3853 descs = kzalloc(sizeof(*descs) + sizeof(descs->desc[0]) * count,
3856 return ERR_PTR(-ENOMEM);
3858 for (descs->ndescs = 0; descs->ndescs < count; ) {
3859 desc = gpiod_get_index(dev, con_id, descs->ndescs, flags);
3861 gpiod_put_array(descs);
3862 return ERR_CAST(desc);
3864 descs->desc[descs->ndescs] = desc;
3869 EXPORT_SYMBOL_GPL(gpiod_get_array);
3872 * gpiod_get_array_optional - obtain multiple GPIOs from a multi-index GPIO
3874 * @dev: GPIO consumer, can be NULL for system-global GPIOs
3875 * @con_id: function within the GPIO consumer
3876 * @flags: optional GPIO initialization flags
3878 * This is equivalent to gpiod_get_array(), except that when no GPIO was
3879 * assigned to the requested function it will return NULL.
3881 struct gpio_descs *__must_check gpiod_get_array_optional(struct device *dev,
3883 enum gpiod_flags flags)
3885 struct gpio_descs *descs;
3887 descs = gpiod_get_array(dev, con_id, flags);
3888 if (IS_ERR(descs) && (PTR_ERR(descs) == -ENOENT))
3893 EXPORT_SYMBOL_GPL(gpiod_get_array_optional);
3896 * gpiod_put - dispose of a GPIO descriptor
3897 * @desc: GPIO descriptor to dispose of
3899 * No descriptor can be used after gpiod_put() has been called on it.
3901 void gpiod_put(struct gpio_desc *desc)
3905 EXPORT_SYMBOL_GPL(gpiod_put);
3908 * gpiod_put_array - dispose of multiple GPIO descriptors
3909 * @descs: struct gpio_descs containing an array of descriptors
3911 void gpiod_put_array(struct gpio_descs *descs)
3915 for (i = 0; i < descs->ndescs; i++)
3916 gpiod_put(descs->desc[i]);
3920 EXPORT_SYMBOL_GPL(gpiod_put_array);
3922 static int __init gpiolib_dev_init(void)
3926 /* Register GPIO sysfs bus */
3927 ret = bus_register(&gpio_bus_type);
3929 pr_err("gpiolib: could not register GPIO bus type\n");
3933 ret = alloc_chrdev_region(&gpio_devt, 0, GPIO_DEV_MAX, "gpiochip");
3935 pr_err("gpiolib: failed to allocate char dev region\n");
3936 bus_unregister(&gpio_bus_type);
3938 gpiolib_initialized = true;
3939 gpiochip_setup_devs();
3943 core_initcall(gpiolib_dev_init);
3945 #ifdef CONFIG_DEBUG_FS
3947 static void gpiolib_dbg_show(struct seq_file *s, struct gpio_device *gdev)
3950 struct gpio_chip *chip = gdev->chip;
3951 unsigned gpio = gdev->base;
3952 struct gpio_desc *gdesc = &gdev->descs[0];
3956 for (i = 0; i < gdev->ngpio; i++, gpio++, gdesc++) {
3957 if (!test_bit(FLAG_REQUESTED, &gdesc->flags)) {
3959 seq_printf(s, " gpio-%-3d (%-20.20s)\n",
3965 gpiod_get_direction(gdesc);
3966 is_out = test_bit(FLAG_IS_OUT, &gdesc->flags);
3967 is_irq = test_bit(FLAG_USED_AS_IRQ, &gdesc->flags);
3968 seq_printf(s, " gpio-%-3d (%-20.20s|%-20.20s) %s %s %s",
3969 gpio, gdesc->name ? gdesc->name : "", gdesc->label,
3970 is_out ? "out" : "in ",
3972 ? (chip->get(chip, i) ? "hi" : "lo")
3974 is_irq ? "IRQ" : " ");
3975 seq_printf(s, "\n");
3979 static void *gpiolib_seq_start(struct seq_file *s, loff_t *pos)
3981 unsigned long flags;
3982 struct gpio_device *gdev = NULL;
3983 loff_t index = *pos;
3987 spin_lock_irqsave(&gpio_lock, flags);
3988 list_for_each_entry(gdev, &gpio_devices, list)
3990 spin_unlock_irqrestore(&gpio_lock, flags);
3993 spin_unlock_irqrestore(&gpio_lock, flags);
3998 static void *gpiolib_seq_next(struct seq_file *s, void *v, loff_t *pos)
4000 unsigned long flags;
4001 struct gpio_device *gdev = v;
4004 spin_lock_irqsave(&gpio_lock, flags);
4005 if (list_is_last(&gdev->list, &gpio_devices))
4008 ret = list_entry(gdev->list.next, struct gpio_device, list);
4009 spin_unlock_irqrestore(&gpio_lock, flags);
4017 static void gpiolib_seq_stop(struct seq_file *s, void *v)
4021 static int gpiolib_seq_show(struct seq_file *s, void *v)
4023 struct gpio_device *gdev = v;
4024 struct gpio_chip *chip = gdev->chip;
4025 struct device *parent;
4028 seq_printf(s, "%s%s: (dangling chip)", (char *)s->private,
4029 dev_name(&gdev->dev));
4033 seq_printf(s, "%s%s: GPIOs %d-%d", (char *)s->private,
4034 dev_name(&gdev->dev),
4035 gdev->base, gdev->base + gdev->ngpio - 1);
4036 parent = chip->parent;
4038 seq_printf(s, ", parent: %s/%s",
4039 parent->bus ? parent->bus->name : "no-bus",
4042 seq_printf(s, ", %s", chip->label);
4043 if (chip->can_sleep)
4044 seq_printf(s, ", can sleep");
4045 seq_printf(s, ":\n");
4048 chip->dbg_show(s, chip);
4050 gpiolib_dbg_show(s, gdev);
4055 static const struct seq_operations gpiolib_seq_ops = {
4056 .start = gpiolib_seq_start,
4057 .next = gpiolib_seq_next,
4058 .stop = gpiolib_seq_stop,
4059 .show = gpiolib_seq_show,
4062 static int gpiolib_open(struct inode *inode, struct file *file)
4064 return seq_open(file, &gpiolib_seq_ops);
4067 static const struct file_operations gpiolib_operations = {
4068 .owner = THIS_MODULE,
4069 .open = gpiolib_open,
4071 .llseek = seq_lseek,
4072 .release = seq_release,
4075 static int __init gpiolib_debugfs_init(void)
4077 /* /sys/kernel/debug/gpio */
4078 (void) debugfs_create_file("gpio", S_IFREG | S_IRUGO,
4079 NULL, NULL, &gpiolib_operations);
4082 subsys_initcall(gpiolib_debugfs_init);
4084 #endif /* DEBUG_FS */