gpiolib: fix bitmap operations related to line event watching
[linux/fpc-iii.git] / drivers / gpio / gpiolib.c
blobbc71f05d51933727adf41c7af668df92a4ab6dbf
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/bitmap.h>
3 #include <linux/kernel.h>
4 #include <linux/module.h>
5 #include <linux/interrupt.h>
6 #include <linux/irq.h>
7 #include <linux/spinlock.h>
8 #include <linux/list.h>
9 #include <linux/device.h>
10 #include <linux/err.h>
11 #include <linux/debugfs.h>
12 #include <linux/seq_file.h>
13 #include <linux/gpio.h>
14 #include <linux/idr.h>
15 #include <linux/slab.h>
16 #include <linux/acpi.h>
17 #include <linux/gpio/driver.h>
18 #include <linux/gpio/machine.h>
19 #include <linux/pinctrl/consumer.h>
20 #include <linux/cdev.h>
21 #include <linux/fs.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>
31 #include "gpiolib.h"
32 #include "gpiolib-of.h"
33 #include "gpiolib-acpi.h"
35 #define CREATE_TRACE_POINTS
36 #include <trace/events/gpio.h>
38 /* Implementation infrastructure for GPIO interfaces.
40 * The GPIO programming interface allows for inlining speed-critical
41 * get/set operations for common cases, so that access to SOC-integrated
42 * GPIOs can sometimes cost only an instruction or two per bit.
46 /* When debugging, extend minimal trust to callers and platform code.
47 * Also emit diagnostic messages that may help initial bringup, when
48 * board setup or driver bugs are most common.
50 * Otherwise, minimize overhead in what may be bitbanging codepaths.
52 #ifdef DEBUG
53 #define extra_checks 1
54 #else
55 #define extra_checks 0
56 #endif
58 /* Device and char device-related information */
59 static DEFINE_IDA(gpio_ida);
60 static dev_t gpio_devt;
61 #define GPIO_DEV_MAX 256 /* 256 GPIO chip devices supported */
62 static struct bus_type gpio_bus_type = {
63 .name = "gpio",
67 * Number of GPIOs to use for the fast path in set array
69 #define FASTPATH_NGPIO CONFIG_GPIOLIB_FASTPATH_LIMIT
71 /* gpio_lock prevents conflicts during gpio_desc[] table updates.
72 * While any GPIO is requested, its gpio_chip is not removable;
73 * each GPIO's "requested" flag serves as a lock and refcount.
75 DEFINE_SPINLOCK(gpio_lock);
77 static DEFINE_MUTEX(gpio_lookup_lock);
78 static LIST_HEAD(gpio_lookup_list);
79 LIST_HEAD(gpio_devices);
81 static DEFINE_MUTEX(gpio_machine_hogs_mutex);
82 static LIST_HEAD(gpio_machine_hogs);
84 static void gpiochip_free_hogs(struct gpio_chip *chip);
85 static int gpiochip_add_irqchip(struct gpio_chip *gpiochip,
86 struct lock_class_key *lock_key,
87 struct lock_class_key *request_key);
88 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip);
89 static int gpiochip_irqchip_init_hw(struct gpio_chip *gpiochip);
90 static int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gpiochip);
91 static void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gpiochip);
93 static bool gpiolib_initialized;
95 static inline void desc_set_label(struct gpio_desc *d, const char *label)
97 d->label = label;
101 * gpio_to_desc - Convert a GPIO number to its descriptor
102 * @gpio: global GPIO number
104 * Returns:
105 * The GPIO descriptor associated with the given GPIO, or %NULL if no GPIO
106 * with the given number exists in the system.
108 struct gpio_desc *gpio_to_desc(unsigned gpio)
110 struct gpio_device *gdev;
111 unsigned long flags;
113 spin_lock_irqsave(&gpio_lock, flags);
115 list_for_each_entry(gdev, &gpio_devices, list) {
116 if (gdev->base <= gpio &&
117 gdev->base + gdev->ngpio > gpio) {
118 spin_unlock_irqrestore(&gpio_lock, flags);
119 return &gdev->descs[gpio - gdev->base];
123 spin_unlock_irqrestore(&gpio_lock, flags);
125 if (!gpio_is_valid(gpio))
126 WARN(1, "invalid GPIO %d\n", gpio);
128 return NULL;
130 EXPORT_SYMBOL_GPL(gpio_to_desc);
133 * gpiochip_get_desc - get the GPIO descriptor corresponding to the given
134 * hardware number for this chip
135 * @chip: GPIO chip
136 * @hwnum: hardware number of the GPIO for this chip
138 * Returns:
139 * A pointer to the GPIO descriptor or %ERR_PTR(-EINVAL) if no GPIO exists
140 * in the given chip for the specified hardware number.
142 struct gpio_desc *gpiochip_get_desc(struct gpio_chip *chip,
143 unsigned int hwnum)
145 struct gpio_device *gdev = chip->gpiodev;
147 if (hwnum >= gdev->ngpio)
148 return ERR_PTR(-EINVAL);
150 return &gdev->descs[hwnum];
154 * desc_to_gpio - convert a GPIO descriptor to the integer namespace
155 * @desc: GPIO descriptor
157 * This should disappear in the future but is needed since we still
158 * use GPIO numbers for error messages and sysfs nodes.
160 * Returns:
161 * The global GPIO number for the GPIO specified by its descriptor.
163 int desc_to_gpio(const struct gpio_desc *desc)
165 return desc->gdev->base + (desc - &desc->gdev->descs[0]);
167 EXPORT_SYMBOL_GPL(desc_to_gpio);
171 * gpiod_to_chip - Return the GPIO chip to which a GPIO descriptor belongs
172 * @desc: descriptor to return the chip of
174 struct gpio_chip *gpiod_to_chip(const struct gpio_desc *desc)
176 if (!desc || !desc->gdev)
177 return NULL;
178 return desc->gdev->chip;
180 EXPORT_SYMBOL_GPL(gpiod_to_chip);
182 /* dynamic allocation of GPIOs, e.g. on a hotplugged device */
183 static int gpiochip_find_base(int ngpio)
185 struct gpio_device *gdev;
186 int base = ARCH_NR_GPIOS - ngpio;
188 list_for_each_entry_reverse(gdev, &gpio_devices, list) {
189 /* found a free space? */
190 if (gdev->base + gdev->ngpio <= base)
191 break;
192 else
193 /* nope, check the space right before the chip */
194 base = gdev->base - ngpio;
197 if (gpio_is_valid(base)) {
198 pr_debug("%s: found new base at %d\n", __func__, base);
199 return base;
200 } else {
201 pr_err("%s: cannot find free range\n", __func__);
202 return -ENOSPC;
207 * gpiod_get_direction - return the current direction of a GPIO
208 * @desc: GPIO to get the direction of
210 * Returns 0 for output, 1 for input, or an error code in case of error.
212 * This function may sleep if gpiod_cansleep() is true.
214 int gpiod_get_direction(struct gpio_desc *desc)
216 struct gpio_chip *chip;
217 unsigned offset;
218 int ret;
220 chip = gpiod_to_chip(desc);
221 offset = gpio_chip_hwgpio(desc);
224 * Open drain emulation using input mode may incorrectly report
225 * input here, fix that up.
227 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags) &&
228 test_bit(FLAG_IS_OUT, &desc->flags))
229 return 0;
231 if (!chip->get_direction)
232 return -ENOTSUPP;
234 ret = chip->get_direction(chip, offset);
235 if (ret < 0)
236 return ret;
238 /* GPIOF_DIR_IN or other positive, otherwise GPIOF_DIR_OUT */
239 if (ret > 0)
240 ret = 1;
242 assign_bit(FLAG_IS_OUT, &desc->flags, !ret);
244 return ret;
246 EXPORT_SYMBOL_GPL(gpiod_get_direction);
249 * Add a new chip to the global chips list, keeping the list of chips sorted
250 * by range(means [base, base + ngpio - 1]) order.
252 * Return -EBUSY if the new chip overlaps with some other chip's integer
253 * space.
255 static int gpiodev_add_to_list(struct gpio_device *gdev)
257 struct gpio_device *prev, *next;
259 if (list_empty(&gpio_devices)) {
260 /* initial entry in list */
261 list_add_tail(&gdev->list, &gpio_devices);
262 return 0;
265 next = list_entry(gpio_devices.next, struct gpio_device, list);
266 if (gdev->base + gdev->ngpio <= next->base) {
267 /* add before first entry */
268 list_add(&gdev->list, &gpio_devices);
269 return 0;
272 prev = list_entry(gpio_devices.prev, struct gpio_device, list);
273 if (prev->base + prev->ngpio <= gdev->base) {
274 /* add behind last entry */
275 list_add_tail(&gdev->list, &gpio_devices);
276 return 0;
279 list_for_each_entry_safe(prev, next, &gpio_devices, list) {
280 /* at the end of the list */
281 if (&next->list == &gpio_devices)
282 break;
284 /* add between prev and next */
285 if (prev->base + prev->ngpio <= gdev->base
286 && gdev->base + gdev->ngpio <= next->base) {
287 list_add(&gdev->list, &prev->list);
288 return 0;
292 dev_err(&gdev->dev, "GPIO integer space overlap, cannot add chip\n");
293 return -EBUSY;
297 * Convert a GPIO name to its descriptor
299 static struct gpio_desc *gpio_name_to_desc(const char * const name)
301 struct gpio_device *gdev;
302 unsigned long flags;
304 spin_lock_irqsave(&gpio_lock, flags);
306 list_for_each_entry(gdev, &gpio_devices, list) {
307 int i;
309 for (i = 0; i != gdev->ngpio; ++i) {
310 struct gpio_desc *desc = &gdev->descs[i];
312 if (!desc->name || !name)
313 continue;
315 if (!strcmp(desc->name, name)) {
316 spin_unlock_irqrestore(&gpio_lock, flags);
317 return desc;
322 spin_unlock_irqrestore(&gpio_lock, flags);
324 return NULL;
328 * Takes the names from gc->names and checks if they are all unique. If they
329 * are, they are assigned to their gpio descriptors.
331 * Warning if one of the names is already used for a different GPIO.
333 static int gpiochip_set_desc_names(struct gpio_chip *gc)
335 struct gpio_device *gdev = gc->gpiodev;
336 int i;
338 if (!gc->names)
339 return 0;
341 /* First check all names if they are unique */
342 for (i = 0; i != gc->ngpio; ++i) {
343 struct gpio_desc *gpio;
345 gpio = gpio_name_to_desc(gc->names[i]);
346 if (gpio)
347 dev_warn(&gdev->dev,
348 "Detected name collision for GPIO name '%s'\n",
349 gc->names[i]);
352 /* Then add all names to the GPIO descriptors */
353 for (i = 0; i != gc->ngpio; ++i)
354 gdev->descs[i].name = gc->names[i];
356 return 0;
359 static unsigned long *gpiochip_allocate_mask(struct gpio_chip *chip)
361 unsigned long *p;
363 p = bitmap_alloc(chip->ngpio, GFP_KERNEL);
364 if (!p)
365 return NULL;
367 /* Assume by default all GPIOs are valid */
368 bitmap_fill(p, chip->ngpio);
370 return p;
373 static int gpiochip_alloc_valid_mask(struct gpio_chip *gc)
375 if (!(of_gpio_need_valid_mask(gc) || gc->init_valid_mask))
376 return 0;
378 gc->valid_mask = gpiochip_allocate_mask(gc);
379 if (!gc->valid_mask)
380 return -ENOMEM;
382 return 0;
385 static int gpiochip_init_valid_mask(struct gpio_chip *gc)
387 if (gc->init_valid_mask)
388 return gc->init_valid_mask(gc,
389 gc->valid_mask,
390 gc->ngpio);
392 return 0;
395 static void gpiochip_free_valid_mask(struct gpio_chip *gpiochip)
397 bitmap_free(gpiochip->valid_mask);
398 gpiochip->valid_mask = NULL;
401 static int gpiochip_add_pin_ranges(struct gpio_chip *gc)
403 if (gc->add_pin_ranges)
404 return gc->add_pin_ranges(gc);
406 return 0;
409 bool gpiochip_line_is_valid(const struct gpio_chip *gpiochip,
410 unsigned int offset)
412 /* No mask means all valid */
413 if (likely(!gpiochip->valid_mask))
414 return true;
415 return test_bit(offset, gpiochip->valid_mask);
417 EXPORT_SYMBOL_GPL(gpiochip_line_is_valid);
420 * GPIO line handle management
424 * struct linehandle_state - contains the state of a userspace handle
425 * @gdev: the GPIO device the handle pertains to
426 * @label: consumer label used to tag descriptors
427 * @descs: the GPIO descriptors held by this handle
428 * @numdescs: the number of descriptors held in the descs array
430 struct linehandle_state {
431 struct gpio_device *gdev;
432 const char *label;
433 struct gpio_desc *descs[GPIOHANDLES_MAX];
434 u32 numdescs;
437 #define GPIOHANDLE_REQUEST_VALID_FLAGS \
438 (GPIOHANDLE_REQUEST_INPUT | \
439 GPIOHANDLE_REQUEST_OUTPUT | \
440 GPIOHANDLE_REQUEST_ACTIVE_LOW | \
441 GPIOHANDLE_REQUEST_BIAS_PULL_UP | \
442 GPIOHANDLE_REQUEST_BIAS_PULL_DOWN | \
443 GPIOHANDLE_REQUEST_BIAS_DISABLE | \
444 GPIOHANDLE_REQUEST_OPEN_DRAIN | \
445 GPIOHANDLE_REQUEST_OPEN_SOURCE)
447 static int linehandle_validate_flags(u32 flags)
449 /* Return an error if an unknown flag is set */
450 if (flags & ~GPIOHANDLE_REQUEST_VALID_FLAGS)
451 return -EINVAL;
454 * Do not allow both INPUT & OUTPUT flags to be set as they are
455 * contradictory.
457 if ((flags & GPIOHANDLE_REQUEST_INPUT) &&
458 (flags & GPIOHANDLE_REQUEST_OUTPUT))
459 return -EINVAL;
462 * Do not allow OPEN_SOURCE & OPEN_DRAIN flags in a single request. If
463 * the hardware actually supports enabling both at the same time the
464 * electrical result would be disastrous.
466 if ((flags & GPIOHANDLE_REQUEST_OPEN_DRAIN) &&
467 (flags & GPIOHANDLE_REQUEST_OPEN_SOURCE))
468 return -EINVAL;
470 /* OPEN_DRAIN and OPEN_SOURCE flags only make sense for output mode. */
471 if (!(flags & GPIOHANDLE_REQUEST_OUTPUT) &&
472 ((flags & GPIOHANDLE_REQUEST_OPEN_DRAIN) ||
473 (flags & GPIOHANDLE_REQUEST_OPEN_SOURCE)))
474 return -EINVAL;
476 /* Bias flags only allowed for input or output mode. */
477 if (!((flags & GPIOHANDLE_REQUEST_INPUT) ||
478 (flags & GPIOHANDLE_REQUEST_OUTPUT)) &&
479 ((flags & GPIOHANDLE_REQUEST_BIAS_DISABLE) ||
480 (flags & GPIOHANDLE_REQUEST_BIAS_PULL_UP) ||
481 (flags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN)))
482 return -EINVAL;
484 /* Only one bias flag can be set. */
485 if (((flags & GPIOHANDLE_REQUEST_BIAS_DISABLE) &&
486 (flags & (GPIOHANDLE_REQUEST_BIAS_PULL_DOWN |
487 GPIOHANDLE_REQUEST_BIAS_PULL_UP))) ||
488 ((flags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN) &&
489 (flags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)))
490 return -EINVAL;
492 return 0;
495 static long linehandle_set_config(struct linehandle_state *lh,
496 void __user *ip)
498 struct gpiohandle_config gcnf;
499 struct gpio_desc *desc;
500 int i, ret;
501 u32 lflags;
502 unsigned long *flagsp;
504 if (copy_from_user(&gcnf, ip, sizeof(gcnf)))
505 return -EFAULT;
507 lflags = gcnf.flags;
508 ret = linehandle_validate_flags(lflags);
509 if (ret)
510 return ret;
512 for (i = 0; i < lh->numdescs; i++) {
513 desc = lh->descs[i];
514 flagsp = &desc->flags;
516 assign_bit(FLAG_ACTIVE_LOW, flagsp,
517 lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW);
519 assign_bit(FLAG_OPEN_DRAIN, flagsp,
520 lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN);
522 assign_bit(FLAG_OPEN_SOURCE, flagsp,
523 lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE);
525 assign_bit(FLAG_PULL_UP, flagsp,
526 lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP);
528 assign_bit(FLAG_PULL_DOWN, flagsp,
529 lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN);
531 assign_bit(FLAG_BIAS_DISABLE, flagsp,
532 lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE);
535 * Lines have to be requested explicitly for input
536 * or output, else the line will be treated "as is".
538 if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
539 int val = !!gcnf.default_values[i];
541 ret = gpiod_direction_output(desc, val);
542 if (ret)
543 return ret;
544 } else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
545 ret = gpiod_direction_input(desc);
546 if (ret)
547 return ret;
550 atomic_notifier_call_chain(&desc->gdev->notifier,
551 GPIOLINE_CHANGED_CONFIG, desc);
553 return 0;
556 static long linehandle_ioctl(struct file *filep, unsigned int cmd,
557 unsigned long arg)
559 struct linehandle_state *lh = filep->private_data;
560 void __user *ip = (void __user *)arg;
561 struct gpiohandle_data ghd;
562 DECLARE_BITMAP(vals, GPIOHANDLES_MAX);
563 int i;
565 if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
566 /* NOTE: It's ok to read values of output lines. */
567 int ret = gpiod_get_array_value_complex(false,
568 true,
569 lh->numdescs,
570 lh->descs,
571 NULL,
572 vals);
573 if (ret)
574 return ret;
576 memset(&ghd, 0, sizeof(ghd));
577 for (i = 0; i < lh->numdescs; i++)
578 ghd.values[i] = test_bit(i, vals);
580 if (copy_to_user(ip, &ghd, sizeof(ghd)))
581 return -EFAULT;
583 return 0;
584 } else if (cmd == GPIOHANDLE_SET_LINE_VALUES_IOCTL) {
586 * All line descriptors were created at once with the same
587 * flags so just check if the first one is really output.
589 if (!test_bit(FLAG_IS_OUT, &lh->descs[0]->flags))
590 return -EPERM;
592 if (copy_from_user(&ghd, ip, sizeof(ghd)))
593 return -EFAULT;
595 /* Clamp all values to [0,1] */
596 for (i = 0; i < lh->numdescs; i++)
597 __assign_bit(i, vals, ghd.values[i]);
599 /* Reuse the array setting function */
600 return gpiod_set_array_value_complex(false,
601 true,
602 lh->numdescs,
603 lh->descs,
604 NULL,
605 vals);
606 } else if (cmd == GPIOHANDLE_SET_CONFIG_IOCTL) {
607 return linehandle_set_config(lh, ip);
609 return -EINVAL;
612 #ifdef CONFIG_COMPAT
613 static long linehandle_ioctl_compat(struct file *filep, unsigned int cmd,
614 unsigned long arg)
616 return linehandle_ioctl(filep, cmd, (unsigned long)compat_ptr(arg));
618 #endif
620 static int linehandle_release(struct inode *inode, struct file *filep)
622 struct linehandle_state *lh = filep->private_data;
623 struct gpio_device *gdev = lh->gdev;
624 int i;
626 for (i = 0; i < lh->numdescs; i++)
627 gpiod_free(lh->descs[i]);
628 kfree(lh->label);
629 kfree(lh);
630 put_device(&gdev->dev);
631 return 0;
634 static const struct file_operations linehandle_fileops = {
635 .release = linehandle_release,
636 .owner = THIS_MODULE,
637 .llseek = noop_llseek,
638 .unlocked_ioctl = linehandle_ioctl,
639 #ifdef CONFIG_COMPAT
640 .compat_ioctl = linehandle_ioctl_compat,
641 #endif
644 static int linehandle_create(struct gpio_device *gdev, void __user *ip)
646 struct gpiohandle_request handlereq;
647 struct linehandle_state *lh;
648 struct file *file;
649 int fd, i, count = 0, ret;
650 u32 lflags;
652 if (copy_from_user(&handlereq, ip, sizeof(handlereq)))
653 return -EFAULT;
654 if ((handlereq.lines == 0) || (handlereq.lines > GPIOHANDLES_MAX))
655 return -EINVAL;
657 lflags = handlereq.flags;
659 ret = linehandle_validate_flags(lflags);
660 if (ret)
661 return ret;
663 lh = kzalloc(sizeof(*lh), GFP_KERNEL);
664 if (!lh)
665 return -ENOMEM;
666 lh->gdev = gdev;
667 get_device(&gdev->dev);
669 /* Make sure this is terminated */
670 handlereq.consumer_label[sizeof(handlereq.consumer_label)-1] = '\0';
671 if (strlen(handlereq.consumer_label)) {
672 lh->label = kstrdup(handlereq.consumer_label,
673 GFP_KERNEL);
674 if (!lh->label) {
675 ret = -ENOMEM;
676 goto out_free_lh;
680 /* Request each GPIO */
681 for (i = 0; i < handlereq.lines; i++) {
682 u32 offset = handlereq.lineoffsets[i];
683 struct gpio_desc *desc = gpiochip_get_desc(gdev->chip, offset);
685 if (IS_ERR(desc)) {
686 ret = PTR_ERR(desc);
687 goto out_free_descs;
690 ret = gpiod_request(desc, lh->label);
691 if (ret)
692 goto out_free_descs;
693 lh->descs[i] = desc;
694 count = i + 1;
696 if (lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW)
697 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
698 if (lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN)
699 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
700 if (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE)
701 set_bit(FLAG_OPEN_SOURCE, &desc->flags);
702 if (lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE)
703 set_bit(FLAG_BIAS_DISABLE, &desc->flags);
704 if (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN)
705 set_bit(FLAG_PULL_DOWN, &desc->flags);
706 if (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)
707 set_bit(FLAG_PULL_UP, &desc->flags);
709 ret = gpiod_set_transitory(desc, false);
710 if (ret < 0)
711 goto out_free_descs;
714 * Lines have to be requested explicitly for input
715 * or output, else the line will be treated "as is".
717 if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
718 int val = !!handlereq.default_values[i];
720 ret = gpiod_direction_output(desc, val);
721 if (ret)
722 goto out_free_descs;
723 } else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
724 ret = gpiod_direction_input(desc);
725 if (ret)
726 goto out_free_descs;
728 dev_dbg(&gdev->dev, "registered chardev handle for line %d\n",
729 offset);
731 /* Let i point at the last handle */
732 i--;
733 lh->numdescs = handlereq.lines;
735 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
736 if (fd < 0) {
737 ret = fd;
738 goto out_free_descs;
741 file = anon_inode_getfile("gpio-linehandle",
742 &linehandle_fileops,
744 O_RDONLY | O_CLOEXEC);
745 if (IS_ERR(file)) {
746 ret = PTR_ERR(file);
747 goto out_put_unused_fd;
750 handlereq.fd = fd;
751 if (copy_to_user(ip, &handlereq, sizeof(handlereq))) {
753 * fput() will trigger the release() callback, so do not go onto
754 * the regular error cleanup path here.
756 fput(file);
757 put_unused_fd(fd);
758 return -EFAULT;
761 fd_install(fd, file);
763 dev_dbg(&gdev->dev, "registered chardev handle for %d lines\n",
764 lh->numdescs);
766 return 0;
768 out_put_unused_fd:
769 put_unused_fd(fd);
770 out_free_descs:
771 for (i = 0; i < count; i++)
772 gpiod_free(lh->descs[i]);
773 kfree(lh->label);
774 out_free_lh:
775 kfree(lh);
776 put_device(&gdev->dev);
777 return ret;
781 * GPIO line event management
785 * struct lineevent_state - contains the state of a userspace event
786 * @gdev: the GPIO device the event pertains to
787 * @label: consumer label used to tag descriptors
788 * @desc: the GPIO descriptor held by this event
789 * @eflags: the event flags this line was requested with
790 * @irq: the interrupt that trigger in response to events on this GPIO
791 * @wait: wait queue that handles blocking reads of events
792 * @events: KFIFO for the GPIO events
793 * @timestamp: cache for the timestamp storing it between hardirq
794 * and IRQ thread, used to bring the timestamp close to the actual
795 * event
797 struct lineevent_state {
798 struct gpio_device *gdev;
799 const char *label;
800 struct gpio_desc *desc;
801 u32 eflags;
802 int irq;
803 wait_queue_head_t wait;
804 DECLARE_KFIFO(events, struct gpioevent_data, 16);
805 u64 timestamp;
808 #define GPIOEVENT_REQUEST_VALID_FLAGS \
809 (GPIOEVENT_REQUEST_RISING_EDGE | \
810 GPIOEVENT_REQUEST_FALLING_EDGE)
812 static __poll_t lineevent_poll(struct file *filep,
813 struct poll_table_struct *wait)
815 struct lineevent_state *le = filep->private_data;
816 __poll_t events = 0;
818 poll_wait(filep, &le->wait, wait);
820 if (!kfifo_is_empty_spinlocked_noirqsave(&le->events, &le->wait.lock))
821 events = EPOLLIN | EPOLLRDNORM;
823 return events;
827 static ssize_t lineevent_read(struct file *filep,
828 char __user *buf,
829 size_t count,
830 loff_t *f_ps)
832 struct lineevent_state *le = filep->private_data;
833 struct gpioevent_data ge;
834 ssize_t bytes_read = 0;
835 int ret;
837 if (count < sizeof(ge))
838 return -EINVAL;
840 do {
841 spin_lock(&le->wait.lock);
842 if (kfifo_is_empty(&le->events)) {
843 if (bytes_read) {
844 spin_unlock(&le->wait.lock);
845 return bytes_read;
848 if (filep->f_flags & O_NONBLOCK) {
849 spin_unlock(&le->wait.lock);
850 return -EAGAIN;
853 ret = wait_event_interruptible_locked(le->wait,
854 !kfifo_is_empty(&le->events));
855 if (ret) {
856 spin_unlock(&le->wait.lock);
857 return ret;
861 ret = kfifo_out(&le->events, &ge, 1);
862 spin_unlock(&le->wait.lock);
863 if (ret != 1) {
865 * This should never happen - we were holding the lock
866 * from the moment we learned the fifo is no longer
867 * empty until now.
869 ret = -EIO;
870 break;
873 if (copy_to_user(buf + bytes_read, &ge, sizeof(ge)))
874 return -EFAULT;
875 bytes_read += sizeof(ge);
876 } while (count >= bytes_read + sizeof(ge));
878 return bytes_read;
881 static int lineevent_release(struct inode *inode, struct file *filep)
883 struct lineevent_state *le = filep->private_data;
884 struct gpio_device *gdev = le->gdev;
886 free_irq(le->irq, le);
887 gpiod_free(le->desc);
888 kfree(le->label);
889 kfree(le);
890 put_device(&gdev->dev);
891 return 0;
894 static long lineevent_ioctl(struct file *filep, unsigned int cmd,
895 unsigned long arg)
897 struct lineevent_state *le = filep->private_data;
898 void __user *ip = (void __user *)arg;
899 struct gpiohandle_data ghd;
902 * We can get the value for an event line but not set it,
903 * because it is input by definition.
905 if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
906 int val;
908 memset(&ghd, 0, sizeof(ghd));
910 val = gpiod_get_value_cansleep(le->desc);
911 if (val < 0)
912 return val;
913 ghd.values[0] = val;
915 if (copy_to_user(ip, &ghd, sizeof(ghd)))
916 return -EFAULT;
918 return 0;
920 return -EINVAL;
923 #ifdef CONFIG_COMPAT
924 static long lineevent_ioctl_compat(struct file *filep, unsigned int cmd,
925 unsigned long arg)
927 return lineevent_ioctl(filep, cmd, (unsigned long)compat_ptr(arg));
929 #endif
931 static const struct file_operations lineevent_fileops = {
932 .release = lineevent_release,
933 .read = lineevent_read,
934 .poll = lineevent_poll,
935 .owner = THIS_MODULE,
936 .llseek = noop_llseek,
937 .unlocked_ioctl = lineevent_ioctl,
938 #ifdef CONFIG_COMPAT
939 .compat_ioctl = lineevent_ioctl_compat,
940 #endif
943 static irqreturn_t lineevent_irq_thread(int irq, void *p)
945 struct lineevent_state *le = p;
946 struct gpioevent_data ge;
947 int ret;
949 /* Do not leak kernel stack to userspace */
950 memset(&ge, 0, sizeof(ge));
953 * We may be running from a nested threaded interrupt in which case
954 * we didn't get the timestamp from lineevent_irq_handler().
956 if (!le->timestamp)
957 ge.timestamp = ktime_get_ns();
958 else
959 ge.timestamp = le->timestamp;
961 if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE
962 && le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
963 int level = gpiod_get_value_cansleep(le->desc);
964 if (level)
965 /* Emit low-to-high event */
966 ge.id = GPIOEVENT_EVENT_RISING_EDGE;
967 else
968 /* Emit high-to-low event */
969 ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
970 } else if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE) {
971 /* Emit low-to-high event */
972 ge.id = GPIOEVENT_EVENT_RISING_EDGE;
973 } else if (le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
974 /* Emit high-to-low event */
975 ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
976 } else {
977 return IRQ_NONE;
980 ret = kfifo_in_spinlocked_noirqsave(&le->events, &ge,
981 1, &le->wait.lock);
982 if (ret)
983 wake_up_poll(&le->wait, EPOLLIN);
984 else
985 pr_debug_ratelimited("event FIFO is full - event dropped\n");
987 return IRQ_HANDLED;
990 static irqreturn_t lineevent_irq_handler(int irq, void *p)
992 struct lineevent_state *le = p;
995 * Just store the timestamp in hardirq context so we get it as
996 * close in time as possible to the actual event.
998 le->timestamp = ktime_get_ns();
1000 return IRQ_WAKE_THREAD;
1003 static int lineevent_create(struct gpio_device *gdev, void __user *ip)
1005 struct gpioevent_request eventreq;
1006 struct lineevent_state *le;
1007 struct gpio_desc *desc;
1008 struct file *file;
1009 u32 offset;
1010 u32 lflags;
1011 u32 eflags;
1012 int fd;
1013 int ret;
1014 int irqflags = 0;
1016 if (copy_from_user(&eventreq, ip, sizeof(eventreq)))
1017 return -EFAULT;
1019 offset = eventreq.lineoffset;
1020 lflags = eventreq.handleflags;
1021 eflags = eventreq.eventflags;
1023 desc = gpiochip_get_desc(gdev->chip, offset);
1024 if (IS_ERR(desc))
1025 return PTR_ERR(desc);
1027 /* Return an error if a unknown flag is set */
1028 if ((lflags & ~GPIOHANDLE_REQUEST_VALID_FLAGS) ||
1029 (eflags & ~GPIOEVENT_REQUEST_VALID_FLAGS))
1030 return -EINVAL;
1032 /* This is just wrong: we don't look for events on output lines */
1033 if ((lflags & GPIOHANDLE_REQUEST_OUTPUT) ||
1034 (lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN) ||
1035 (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE))
1036 return -EINVAL;
1038 /* Only one bias flag can be set. */
1039 if (((lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE) &&
1040 (lflags & (GPIOHANDLE_REQUEST_BIAS_PULL_DOWN |
1041 GPIOHANDLE_REQUEST_BIAS_PULL_UP))) ||
1042 ((lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN) &&
1043 (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)))
1044 return -EINVAL;
1046 le = kzalloc(sizeof(*le), GFP_KERNEL);
1047 if (!le)
1048 return -ENOMEM;
1049 le->gdev = gdev;
1050 get_device(&gdev->dev);
1052 /* Make sure this is terminated */
1053 eventreq.consumer_label[sizeof(eventreq.consumer_label)-1] = '\0';
1054 if (strlen(eventreq.consumer_label)) {
1055 le->label = kstrdup(eventreq.consumer_label,
1056 GFP_KERNEL);
1057 if (!le->label) {
1058 ret = -ENOMEM;
1059 goto out_free_le;
1063 ret = gpiod_request(desc, le->label);
1064 if (ret)
1065 goto out_free_label;
1066 le->desc = desc;
1067 le->eflags = eflags;
1069 if (lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW)
1070 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
1071 if (lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE)
1072 set_bit(FLAG_BIAS_DISABLE, &desc->flags);
1073 if (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN)
1074 set_bit(FLAG_PULL_DOWN, &desc->flags);
1075 if (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)
1076 set_bit(FLAG_PULL_UP, &desc->flags);
1078 ret = gpiod_direction_input(desc);
1079 if (ret)
1080 goto out_free_desc;
1082 le->irq = gpiod_to_irq(desc);
1083 if (le->irq <= 0) {
1084 ret = -ENODEV;
1085 goto out_free_desc;
1088 if (eflags & GPIOEVENT_REQUEST_RISING_EDGE)
1089 irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
1090 IRQF_TRIGGER_FALLING : IRQF_TRIGGER_RISING;
1091 if (eflags & GPIOEVENT_REQUEST_FALLING_EDGE)
1092 irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
1093 IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING;
1094 irqflags |= IRQF_ONESHOT;
1096 INIT_KFIFO(le->events);
1097 init_waitqueue_head(&le->wait);
1099 /* Request a thread to read the events */
1100 ret = request_threaded_irq(le->irq,
1101 lineevent_irq_handler,
1102 lineevent_irq_thread,
1103 irqflags,
1104 le->label,
1105 le);
1106 if (ret)
1107 goto out_free_desc;
1109 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
1110 if (fd < 0) {
1111 ret = fd;
1112 goto out_free_irq;
1115 file = anon_inode_getfile("gpio-event",
1116 &lineevent_fileops,
1118 O_RDONLY | O_CLOEXEC);
1119 if (IS_ERR(file)) {
1120 ret = PTR_ERR(file);
1121 goto out_put_unused_fd;
1124 eventreq.fd = fd;
1125 if (copy_to_user(ip, &eventreq, sizeof(eventreq))) {
1127 * fput() will trigger the release() callback, so do not go onto
1128 * the regular error cleanup path here.
1130 fput(file);
1131 put_unused_fd(fd);
1132 return -EFAULT;
1135 fd_install(fd, file);
1137 return 0;
1139 out_put_unused_fd:
1140 put_unused_fd(fd);
1141 out_free_irq:
1142 free_irq(le->irq, le);
1143 out_free_desc:
1144 gpiod_free(le->desc);
1145 out_free_label:
1146 kfree(le->label);
1147 out_free_le:
1148 kfree(le);
1149 put_device(&gdev->dev);
1150 return ret;
1153 static void gpio_desc_to_lineinfo(struct gpio_desc *desc,
1154 struct gpioline_info *info)
1156 struct gpio_chip *chip = desc->gdev->chip;
1157 unsigned long flags;
1159 spin_lock_irqsave(&gpio_lock, flags);
1161 if (desc->name) {
1162 strncpy(info->name, desc->name, sizeof(info->name));
1163 info->name[sizeof(info->name) - 1] = '\0';
1164 } else {
1165 info->name[0] = '\0';
1168 if (desc->label) {
1169 strncpy(info->consumer, desc->label, sizeof(info->consumer));
1170 info->consumer[sizeof(info->consumer) - 1] = '\0';
1171 } else {
1172 info->consumer[0] = '\0';
1176 * Userspace only need to know that the kernel is using this GPIO so
1177 * it can't use it.
1179 info->flags = 0;
1180 if (test_bit(FLAG_REQUESTED, &desc->flags) ||
1181 test_bit(FLAG_IS_HOGGED, &desc->flags) ||
1182 test_bit(FLAG_USED_AS_IRQ, &desc->flags) ||
1183 test_bit(FLAG_EXPORT, &desc->flags) ||
1184 test_bit(FLAG_SYSFS, &desc->flags) ||
1185 !pinctrl_gpio_can_use_line(chip->base + info->line_offset))
1186 info->flags |= GPIOLINE_FLAG_KERNEL;
1187 if (test_bit(FLAG_IS_OUT, &desc->flags))
1188 info->flags |= GPIOLINE_FLAG_IS_OUT;
1189 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
1190 info->flags |= GPIOLINE_FLAG_ACTIVE_LOW;
1191 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
1192 info->flags |= (GPIOLINE_FLAG_OPEN_DRAIN |
1193 GPIOLINE_FLAG_IS_OUT);
1194 if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
1195 info->flags |= (GPIOLINE_FLAG_OPEN_SOURCE |
1196 GPIOLINE_FLAG_IS_OUT);
1197 if (test_bit(FLAG_BIAS_DISABLE, &desc->flags))
1198 info->flags |= GPIOLINE_FLAG_BIAS_DISABLE;
1199 if (test_bit(FLAG_PULL_DOWN, &desc->flags))
1200 info->flags |= GPIOLINE_FLAG_BIAS_PULL_DOWN;
1201 if (test_bit(FLAG_PULL_UP, &desc->flags))
1202 info->flags |= GPIOLINE_FLAG_BIAS_PULL_UP;
1204 spin_unlock_irqrestore(&gpio_lock, flags);
1207 struct gpio_chardev_data {
1208 struct gpio_device *gdev;
1209 wait_queue_head_t wait;
1210 DECLARE_KFIFO(events, struct gpioline_info_changed, 32);
1211 struct notifier_block lineinfo_changed_nb;
1212 unsigned long *watched_lines;
1216 * gpio_ioctl() - ioctl handler for the GPIO chardev
1218 static long gpio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1220 struct gpio_chardev_data *priv = filp->private_data;
1221 struct gpio_device *gdev = priv->gdev;
1222 struct gpio_chip *chip = gdev->chip;
1223 void __user *ip = (void __user *)arg;
1224 struct gpio_desc *desc;
1225 __u32 offset;
1227 /* We fail any subsequent ioctl():s when the chip is gone */
1228 if (!chip)
1229 return -ENODEV;
1231 /* Fill in the struct and pass to userspace */
1232 if (cmd == GPIO_GET_CHIPINFO_IOCTL) {
1233 struct gpiochip_info chipinfo;
1235 memset(&chipinfo, 0, sizeof(chipinfo));
1237 strncpy(chipinfo.name, dev_name(&gdev->dev),
1238 sizeof(chipinfo.name));
1239 chipinfo.name[sizeof(chipinfo.name)-1] = '\0';
1240 strncpy(chipinfo.label, gdev->label,
1241 sizeof(chipinfo.label));
1242 chipinfo.label[sizeof(chipinfo.label)-1] = '\0';
1243 chipinfo.lines = gdev->ngpio;
1244 if (copy_to_user(ip, &chipinfo, sizeof(chipinfo)))
1245 return -EFAULT;
1246 return 0;
1247 } else if (cmd == GPIO_GET_LINEINFO_IOCTL ||
1248 cmd == GPIO_GET_LINEINFO_WATCH_IOCTL) {
1249 struct gpioline_info lineinfo;
1251 if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
1252 return -EFAULT;
1254 desc = gpiochip_get_desc(chip, lineinfo.line_offset);
1255 if (IS_ERR(desc))
1256 return PTR_ERR(desc);
1258 gpio_desc_to_lineinfo(desc, &lineinfo);
1260 if (copy_to_user(ip, &lineinfo, sizeof(lineinfo)))
1261 return -EFAULT;
1263 if (cmd == GPIO_GET_LINEINFO_WATCH_IOCTL)
1264 set_bit(gpio_chip_hwgpio(desc), priv->watched_lines);
1266 return 0;
1267 } else if (cmd == GPIO_GET_LINEHANDLE_IOCTL) {
1268 return linehandle_create(gdev, ip);
1269 } else if (cmd == GPIO_GET_LINEEVENT_IOCTL) {
1270 return lineevent_create(gdev, ip);
1271 } else if (cmd == GPIO_GET_LINEINFO_UNWATCH_IOCTL) {
1272 if (copy_from_user(&offset, ip, sizeof(offset)))
1273 return -EFAULT;
1275 desc = gpiochip_get_desc(chip, offset);
1276 if (IS_ERR(desc))
1277 return PTR_ERR(desc);
1279 clear_bit(gpio_chip_hwgpio(desc), priv->watched_lines);
1280 return 0;
1282 return -EINVAL;
1285 #ifdef CONFIG_COMPAT
1286 static long gpio_ioctl_compat(struct file *filp, unsigned int cmd,
1287 unsigned long arg)
1289 return gpio_ioctl(filp, cmd, (unsigned long)compat_ptr(arg));
1291 #endif
1293 static struct gpio_chardev_data *
1294 to_gpio_chardev_data(struct notifier_block *nb)
1296 return container_of(nb, struct gpio_chardev_data, lineinfo_changed_nb);
1299 static int lineinfo_changed_notify(struct notifier_block *nb,
1300 unsigned long action, void *data)
1302 struct gpio_chardev_data *priv = to_gpio_chardev_data(nb);
1303 struct gpioline_info_changed chg;
1304 struct gpio_desc *desc = data;
1305 int ret;
1307 if (!test_bit(gpio_chip_hwgpio(desc), priv->watched_lines))
1308 return NOTIFY_DONE;
1310 memset(&chg, 0, sizeof(chg));
1311 chg.info.line_offset = gpio_chip_hwgpio(desc);
1312 chg.event_type = action;
1313 chg.timestamp = ktime_get_ns();
1314 gpio_desc_to_lineinfo(desc, &chg.info);
1316 ret = kfifo_in_spinlocked(&priv->events, &chg, 1, &priv->wait.lock);
1317 if (ret)
1318 wake_up_poll(&priv->wait, EPOLLIN);
1319 else
1320 pr_debug_ratelimited("lineinfo event FIFO is full - event dropped\n");
1322 return NOTIFY_OK;
1325 static __poll_t lineinfo_watch_poll(struct file *filep,
1326 struct poll_table_struct *pollt)
1328 struct gpio_chardev_data *priv = filep->private_data;
1329 __poll_t events = 0;
1331 poll_wait(filep, &priv->wait, pollt);
1333 if (!kfifo_is_empty_spinlocked_noirqsave(&priv->events,
1334 &priv->wait.lock))
1335 events = EPOLLIN | EPOLLRDNORM;
1337 return events;
1340 static ssize_t lineinfo_watch_read(struct file *filep, char __user *buf,
1341 size_t count, loff_t *off)
1343 struct gpio_chardev_data *priv = filep->private_data;
1344 struct gpioline_info_changed event;
1345 ssize_t bytes_read = 0;
1346 int ret;
1348 if (count < sizeof(event))
1349 return -EINVAL;
1351 do {
1352 spin_lock(&priv->wait.lock);
1353 if (kfifo_is_empty(&priv->events)) {
1354 if (bytes_read) {
1355 spin_unlock(&priv->wait.lock);
1356 return bytes_read;
1359 if (filep->f_flags & O_NONBLOCK) {
1360 spin_unlock(&priv->wait.lock);
1361 return -EAGAIN;
1364 ret = wait_event_interruptible_locked(priv->wait,
1365 !kfifo_is_empty(&priv->events));
1366 if (ret) {
1367 spin_unlock(&priv->wait.lock);
1368 return ret;
1372 ret = kfifo_out(&priv->events, &event, 1);
1373 spin_unlock(&priv->wait.lock);
1374 if (ret != 1) {
1375 ret = -EIO;
1376 break;
1377 /* We should never get here. See lineevent_read(). */
1380 if (copy_to_user(buf + bytes_read, &event, sizeof(event)))
1381 return -EFAULT;
1382 bytes_read += sizeof(event);
1383 } while (count >= bytes_read + sizeof(event));
1385 return bytes_read;
1389 * gpio_chrdev_open() - open the chardev for ioctl operations
1390 * @inode: inode for this chardev
1391 * @filp: file struct for storing private data
1392 * Returns 0 on success
1394 static int gpio_chrdev_open(struct inode *inode, struct file *filp)
1396 struct gpio_device *gdev = container_of(inode->i_cdev,
1397 struct gpio_device, chrdev);
1398 struct gpio_chardev_data *priv;
1399 int ret = -ENOMEM;
1401 /* Fail on open if the backing gpiochip is gone */
1402 if (!gdev->chip)
1403 return -ENODEV;
1405 priv = kzalloc(sizeof(*priv), GFP_KERNEL);
1406 if (!priv)
1407 return -ENOMEM;
1409 priv->watched_lines = bitmap_zalloc(gdev->chip->ngpio, GFP_KERNEL);
1410 if (!priv->watched_lines)
1411 goto out_free_priv;
1413 init_waitqueue_head(&priv->wait);
1414 INIT_KFIFO(priv->events);
1415 priv->gdev = gdev;
1417 priv->lineinfo_changed_nb.notifier_call = lineinfo_changed_notify;
1418 ret = atomic_notifier_chain_register(&gdev->notifier,
1419 &priv->lineinfo_changed_nb);
1420 if (ret)
1421 goto out_free_bitmap;
1423 get_device(&gdev->dev);
1424 filp->private_data = priv;
1426 ret = nonseekable_open(inode, filp);
1427 if (ret)
1428 goto out_unregister_notifier;
1430 return ret;
1432 out_unregister_notifier:
1433 atomic_notifier_chain_unregister(&gdev->notifier,
1434 &priv->lineinfo_changed_nb);
1435 out_free_bitmap:
1436 bitmap_free(priv->watched_lines);
1437 out_free_priv:
1438 kfree(priv);
1439 return ret;
1443 * gpio_chrdev_release() - close chardev after ioctl operations
1444 * @inode: inode for this chardev
1445 * @filp: file struct for storing private data
1446 * Returns 0 on success
1448 static int gpio_chrdev_release(struct inode *inode, struct file *filp)
1450 struct gpio_chardev_data *priv = filp->private_data;
1451 struct gpio_device *gdev = priv->gdev;
1453 bitmap_free(priv->watched_lines);
1454 atomic_notifier_chain_unregister(&gdev->notifier,
1455 &priv->lineinfo_changed_nb);
1456 put_device(&gdev->dev);
1457 kfree(priv);
1459 return 0;
1462 static const struct file_operations gpio_fileops = {
1463 .release = gpio_chrdev_release,
1464 .open = gpio_chrdev_open,
1465 .poll = lineinfo_watch_poll,
1466 .read = lineinfo_watch_read,
1467 .owner = THIS_MODULE,
1468 .llseek = no_llseek,
1469 .unlocked_ioctl = gpio_ioctl,
1470 #ifdef CONFIG_COMPAT
1471 .compat_ioctl = gpio_ioctl_compat,
1472 #endif
1475 static void gpiodevice_release(struct device *dev)
1477 struct gpio_device *gdev = dev_get_drvdata(dev);
1479 list_del(&gdev->list);
1480 ida_simple_remove(&gpio_ida, gdev->id);
1481 kfree_const(gdev->label);
1482 kfree(gdev->descs);
1483 kfree(gdev);
1486 static int gpiochip_setup_dev(struct gpio_device *gdev)
1488 int ret;
1490 cdev_init(&gdev->chrdev, &gpio_fileops);
1491 gdev->chrdev.owner = THIS_MODULE;
1492 gdev->dev.devt = MKDEV(MAJOR(gpio_devt), gdev->id);
1494 ret = cdev_device_add(&gdev->chrdev, &gdev->dev);
1495 if (ret)
1496 return ret;
1498 chip_dbg(gdev->chip, "added GPIO chardev (%d:%d)\n",
1499 MAJOR(gpio_devt), gdev->id);
1501 ret = gpiochip_sysfs_register(gdev);
1502 if (ret)
1503 goto err_remove_device;
1505 /* From this point, the .release() function cleans up gpio_device */
1506 gdev->dev.release = gpiodevice_release;
1507 pr_debug("%s: registered GPIOs %d to %d on device: %s (%s)\n",
1508 __func__, gdev->base, gdev->base + gdev->ngpio - 1,
1509 dev_name(&gdev->dev), gdev->chip->label ? : "generic");
1511 return 0;
1513 err_remove_device:
1514 cdev_device_del(&gdev->chrdev, &gdev->dev);
1515 return ret;
1518 static void gpiochip_machine_hog(struct gpio_chip *chip, struct gpiod_hog *hog)
1520 struct gpio_desc *desc;
1521 int rv;
1523 desc = gpiochip_get_desc(chip, hog->chip_hwnum);
1524 if (IS_ERR(desc)) {
1525 pr_err("%s: unable to get GPIO desc: %ld\n",
1526 __func__, PTR_ERR(desc));
1527 return;
1530 if (test_bit(FLAG_IS_HOGGED, &desc->flags))
1531 return;
1533 rv = gpiod_hog(desc, hog->line_name, hog->lflags, hog->dflags);
1534 if (rv)
1535 pr_err("%s: unable to hog GPIO line (%s:%u): %d\n",
1536 __func__, chip->label, hog->chip_hwnum, rv);
1539 static void machine_gpiochip_add(struct gpio_chip *chip)
1541 struct gpiod_hog *hog;
1543 mutex_lock(&gpio_machine_hogs_mutex);
1545 list_for_each_entry(hog, &gpio_machine_hogs, list) {
1546 if (!strcmp(chip->label, hog->chip_label))
1547 gpiochip_machine_hog(chip, hog);
1550 mutex_unlock(&gpio_machine_hogs_mutex);
1553 static void gpiochip_setup_devs(void)
1555 struct gpio_device *gdev;
1556 int ret;
1558 list_for_each_entry(gdev, &gpio_devices, list) {
1559 ret = gpiochip_setup_dev(gdev);
1560 if (ret)
1561 pr_err("%s: Failed to initialize gpio device (%d)\n",
1562 dev_name(&gdev->dev), ret);
1566 int gpiochip_add_data_with_key(struct gpio_chip *chip, void *data,
1567 struct lock_class_key *lock_key,
1568 struct lock_class_key *request_key)
1570 unsigned long flags;
1571 int ret = 0;
1572 unsigned i;
1573 int base = chip->base;
1574 struct gpio_device *gdev;
1577 * First: allocate and populate the internal stat container, and
1578 * set up the struct device.
1580 gdev = kzalloc(sizeof(*gdev), GFP_KERNEL);
1581 if (!gdev)
1582 return -ENOMEM;
1583 gdev->dev.bus = &gpio_bus_type;
1584 gdev->chip = chip;
1585 chip->gpiodev = gdev;
1586 if (chip->parent) {
1587 gdev->dev.parent = chip->parent;
1588 gdev->dev.of_node = chip->parent->of_node;
1591 #ifdef CONFIG_OF_GPIO
1592 /* If the gpiochip has an assigned OF node this takes precedence */
1593 if (chip->of_node)
1594 gdev->dev.of_node = chip->of_node;
1595 else
1596 chip->of_node = gdev->dev.of_node;
1597 #endif
1599 gdev->id = ida_simple_get(&gpio_ida, 0, 0, GFP_KERNEL);
1600 if (gdev->id < 0) {
1601 ret = gdev->id;
1602 goto err_free_gdev;
1604 dev_set_name(&gdev->dev, GPIOCHIP_NAME "%d", gdev->id);
1605 device_initialize(&gdev->dev);
1606 dev_set_drvdata(&gdev->dev, gdev);
1607 if (chip->parent && chip->parent->driver)
1608 gdev->owner = chip->parent->driver->owner;
1609 else if (chip->owner)
1610 /* TODO: remove chip->owner */
1611 gdev->owner = chip->owner;
1612 else
1613 gdev->owner = THIS_MODULE;
1615 gdev->descs = kcalloc(chip->ngpio, sizeof(gdev->descs[0]), GFP_KERNEL);
1616 if (!gdev->descs) {
1617 ret = -ENOMEM;
1618 goto err_free_ida;
1621 if (chip->ngpio == 0) {
1622 chip_err(chip, "tried to insert a GPIO chip with zero lines\n");
1623 ret = -EINVAL;
1624 goto err_free_descs;
1627 if (chip->ngpio > FASTPATH_NGPIO)
1628 chip_warn(chip, "line cnt %u is greater than fast path cnt %u\n",
1629 chip->ngpio, FASTPATH_NGPIO);
1631 gdev->label = kstrdup_const(chip->label ?: "unknown", GFP_KERNEL);
1632 if (!gdev->label) {
1633 ret = -ENOMEM;
1634 goto err_free_descs;
1637 gdev->ngpio = chip->ngpio;
1638 gdev->data = data;
1640 spin_lock_irqsave(&gpio_lock, flags);
1643 * TODO: this allocates a Linux GPIO number base in the global
1644 * GPIO numberspace for this chip. In the long run we want to
1645 * get *rid* of this numberspace and use only descriptors, but
1646 * it may be a pipe dream. It will not happen before we get rid
1647 * of the sysfs interface anyways.
1649 if (base < 0) {
1650 base = gpiochip_find_base(chip->ngpio);
1651 if (base < 0) {
1652 ret = base;
1653 spin_unlock_irqrestore(&gpio_lock, flags);
1654 goto err_free_label;
1657 * TODO: it should not be necessary to reflect the assigned
1658 * base outside of the GPIO subsystem. Go over drivers and
1659 * see if anyone makes use of this, else drop this and assign
1660 * a poison instead.
1662 chip->base = base;
1664 gdev->base = base;
1666 ret = gpiodev_add_to_list(gdev);
1667 if (ret) {
1668 spin_unlock_irqrestore(&gpio_lock, flags);
1669 goto err_free_label;
1672 for (i = 0; i < chip->ngpio; i++)
1673 gdev->descs[i].gdev = gdev;
1675 spin_unlock_irqrestore(&gpio_lock, flags);
1677 ATOMIC_INIT_NOTIFIER_HEAD(&gdev->notifier);
1679 #ifdef CONFIG_PINCTRL
1680 INIT_LIST_HEAD(&gdev->pin_ranges);
1681 #endif
1683 ret = gpiochip_set_desc_names(chip);
1684 if (ret)
1685 goto err_remove_from_list;
1687 ret = gpiochip_alloc_valid_mask(chip);
1688 if (ret)
1689 goto err_remove_from_list;
1691 ret = of_gpiochip_add(chip);
1692 if (ret)
1693 goto err_free_gpiochip_mask;
1695 ret = gpiochip_init_valid_mask(chip);
1696 if (ret)
1697 goto err_remove_of_chip;
1699 for (i = 0; i < chip->ngpio; i++) {
1700 struct gpio_desc *desc = &gdev->descs[i];
1702 if (chip->get_direction && gpiochip_line_is_valid(chip, i)) {
1703 assign_bit(FLAG_IS_OUT,
1704 &desc->flags, !chip->get_direction(chip, i));
1705 } else {
1706 assign_bit(FLAG_IS_OUT,
1707 &desc->flags, !chip->direction_input);
1711 ret = gpiochip_add_pin_ranges(chip);
1712 if (ret)
1713 goto err_remove_of_chip;
1715 acpi_gpiochip_add(chip);
1717 machine_gpiochip_add(chip);
1719 ret = gpiochip_irqchip_init_valid_mask(chip);
1720 if (ret)
1721 goto err_remove_acpi_chip;
1723 ret = gpiochip_irqchip_init_hw(chip);
1724 if (ret)
1725 goto err_remove_acpi_chip;
1727 ret = gpiochip_add_irqchip(chip, lock_key, request_key);
1728 if (ret)
1729 goto err_remove_irqchip_mask;
1732 * By first adding the chardev, and then adding the device,
1733 * we get a device node entry in sysfs under
1734 * /sys/bus/gpio/devices/gpiochipN/dev that can be used for
1735 * coldplug of device nodes and other udev business.
1736 * We can do this only if gpiolib has been initialized.
1737 * Otherwise, defer until later.
1739 if (gpiolib_initialized) {
1740 ret = gpiochip_setup_dev(gdev);
1741 if (ret)
1742 goto err_remove_irqchip;
1744 return 0;
1746 err_remove_irqchip:
1747 gpiochip_irqchip_remove(chip);
1748 err_remove_irqchip_mask:
1749 gpiochip_irqchip_free_valid_mask(chip);
1750 err_remove_acpi_chip:
1751 acpi_gpiochip_remove(chip);
1752 err_remove_of_chip:
1753 gpiochip_free_hogs(chip);
1754 of_gpiochip_remove(chip);
1755 err_free_gpiochip_mask:
1756 gpiochip_remove_pin_ranges(chip);
1757 gpiochip_free_valid_mask(chip);
1758 err_remove_from_list:
1759 spin_lock_irqsave(&gpio_lock, flags);
1760 list_del(&gdev->list);
1761 spin_unlock_irqrestore(&gpio_lock, flags);
1762 err_free_label:
1763 kfree_const(gdev->label);
1764 err_free_descs:
1765 kfree(gdev->descs);
1766 err_free_ida:
1767 ida_simple_remove(&gpio_ida, gdev->id);
1768 err_free_gdev:
1769 /* failures here can mean systems won't boot... */
1770 pr_err("%s: GPIOs %d..%d (%s) failed to register, %d\n", __func__,
1771 gdev->base, gdev->base + gdev->ngpio - 1,
1772 chip->label ? : "generic", ret);
1773 kfree(gdev);
1774 return ret;
1776 EXPORT_SYMBOL_GPL(gpiochip_add_data_with_key);
1779 * gpiochip_get_data() - get per-subdriver data for the chip
1780 * @chip: GPIO chip
1782 * Returns:
1783 * The per-subdriver data for the chip.
1785 void *gpiochip_get_data(struct gpio_chip *chip)
1787 return chip->gpiodev->data;
1789 EXPORT_SYMBOL_GPL(gpiochip_get_data);
1792 * gpiochip_remove() - unregister a gpio_chip
1793 * @chip: the chip to unregister
1795 * A gpio_chip with any GPIOs still requested may not be removed.
1797 void gpiochip_remove(struct gpio_chip *chip)
1799 struct gpio_device *gdev = chip->gpiodev;
1800 unsigned long flags;
1801 unsigned int i;
1803 /* FIXME: should the legacy sysfs handling be moved to gpio_device? */
1804 gpiochip_sysfs_unregister(gdev);
1805 gpiochip_free_hogs(chip);
1806 /* Numb the device, cancelling all outstanding operations */
1807 gdev->chip = NULL;
1808 gpiochip_irqchip_remove(chip);
1809 acpi_gpiochip_remove(chip);
1810 of_gpiochip_remove(chip);
1811 gpiochip_remove_pin_ranges(chip);
1812 gpiochip_free_valid_mask(chip);
1814 * We accept no more calls into the driver from this point, so
1815 * NULL the driver data pointer
1817 gdev->data = NULL;
1819 spin_lock_irqsave(&gpio_lock, flags);
1820 for (i = 0; i < gdev->ngpio; i++) {
1821 if (gpiochip_is_requested(chip, i))
1822 break;
1824 spin_unlock_irqrestore(&gpio_lock, flags);
1826 if (i == gdev->ngpio)
1827 dev_crit(&gdev->dev,
1828 "REMOVING GPIOCHIP WITH GPIOS STILL REQUESTED\n");
1831 * The gpiochip side puts its use of the device to rest here:
1832 * if there are no userspace clients, the chardev and device will
1833 * be removed, else it will be dangling until the last user is
1834 * gone.
1836 cdev_device_del(&gdev->chrdev, &gdev->dev);
1837 put_device(&gdev->dev);
1839 EXPORT_SYMBOL_GPL(gpiochip_remove);
1841 static void devm_gpio_chip_release(struct device *dev, void *res)
1843 struct gpio_chip *chip = *(struct gpio_chip **)res;
1845 gpiochip_remove(chip);
1849 * devm_gpiochip_add_data() - Resource managed gpiochip_add_data()
1850 * @dev: pointer to the device that gpio_chip belongs to.
1851 * @chip: the chip to register, with chip->base initialized
1852 * @data: driver-private data associated with this chip
1854 * Context: potentially before irqs will work
1856 * The gpio chip automatically be released when the device is unbound.
1858 * Returns:
1859 * A negative errno if the chip can't be registered, such as because the
1860 * chip->base is invalid or already associated with a different chip.
1861 * Otherwise it returns zero as a success code.
1863 int devm_gpiochip_add_data(struct device *dev, struct gpio_chip *chip,
1864 void *data)
1866 struct gpio_chip **ptr;
1867 int ret;
1869 ptr = devres_alloc(devm_gpio_chip_release, sizeof(*ptr),
1870 GFP_KERNEL);
1871 if (!ptr)
1872 return -ENOMEM;
1874 ret = gpiochip_add_data(chip, data);
1875 if (ret < 0) {
1876 devres_free(ptr);
1877 return ret;
1880 *ptr = chip;
1881 devres_add(dev, ptr);
1883 return 0;
1885 EXPORT_SYMBOL_GPL(devm_gpiochip_add_data);
1888 * gpiochip_find() - iterator for locating a specific gpio_chip
1889 * @data: data to pass to match function
1890 * @match: Callback function to check gpio_chip
1892 * Similar to bus_find_device. It returns a reference to a gpio_chip as
1893 * determined by a user supplied @match callback. The callback should return
1894 * 0 if the device doesn't match and non-zero if it does. If the callback is
1895 * non-zero, this function will return to the caller and not iterate over any
1896 * more gpio_chips.
1898 struct gpio_chip *gpiochip_find(void *data,
1899 int (*match)(struct gpio_chip *chip,
1900 void *data))
1902 struct gpio_device *gdev;
1903 struct gpio_chip *chip = NULL;
1904 unsigned long flags;
1906 spin_lock_irqsave(&gpio_lock, flags);
1907 list_for_each_entry(gdev, &gpio_devices, list)
1908 if (gdev->chip && match(gdev->chip, data)) {
1909 chip = gdev->chip;
1910 break;
1913 spin_unlock_irqrestore(&gpio_lock, flags);
1915 return chip;
1917 EXPORT_SYMBOL_GPL(gpiochip_find);
1919 static int gpiochip_match_name(struct gpio_chip *chip, void *data)
1921 const char *name = data;
1923 return !strcmp(chip->label, name);
1926 static struct gpio_chip *find_chip_by_name(const char *name)
1928 return gpiochip_find((void *)name, gpiochip_match_name);
1931 #ifdef CONFIG_GPIOLIB_IRQCHIP
1934 * The following is irqchip helper code for gpiochips.
1937 static int gpiochip_irqchip_init_hw(struct gpio_chip *gc)
1939 struct gpio_irq_chip *girq = &gc->irq;
1941 if (!girq->init_hw)
1942 return 0;
1944 return girq->init_hw(gc);
1947 static int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gc)
1949 struct gpio_irq_chip *girq = &gc->irq;
1951 if (!girq->init_valid_mask)
1952 return 0;
1954 girq->valid_mask = gpiochip_allocate_mask(gc);
1955 if (!girq->valid_mask)
1956 return -ENOMEM;
1958 girq->init_valid_mask(gc, girq->valid_mask, gc->ngpio);
1960 return 0;
1963 static void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gpiochip)
1965 bitmap_free(gpiochip->irq.valid_mask);
1966 gpiochip->irq.valid_mask = NULL;
1969 bool gpiochip_irqchip_irq_valid(const struct gpio_chip *gpiochip,
1970 unsigned int offset)
1972 if (!gpiochip_line_is_valid(gpiochip, offset))
1973 return false;
1974 /* No mask means all valid */
1975 if (likely(!gpiochip->irq.valid_mask))
1976 return true;
1977 return test_bit(offset, gpiochip->irq.valid_mask);
1979 EXPORT_SYMBOL_GPL(gpiochip_irqchip_irq_valid);
1982 * gpiochip_set_cascaded_irqchip() - connects a cascaded irqchip to a gpiochip
1983 * @gc: the gpiochip to set the irqchip chain to
1984 * @parent_irq: the irq number corresponding to the parent IRQ for this
1985 * cascaded irqchip
1986 * @parent_handler: the parent interrupt handler for the accumulated IRQ
1987 * coming out of the gpiochip. If the interrupt is nested rather than
1988 * cascaded, pass NULL in this handler argument
1990 static void gpiochip_set_cascaded_irqchip(struct gpio_chip *gc,
1991 unsigned int parent_irq,
1992 irq_flow_handler_t parent_handler)
1994 struct gpio_irq_chip *girq = &gc->irq;
1995 struct device *dev = &gc->gpiodev->dev;
1997 if (!girq->domain) {
1998 chip_err(gc, "called %s before setting up irqchip\n",
1999 __func__);
2000 return;
2003 if (parent_handler) {
2004 if (gc->can_sleep) {
2005 chip_err(gc,
2006 "you cannot have chained interrupts on a chip that may sleep\n");
2007 return;
2009 girq->parents = devm_kcalloc(dev, 1,
2010 sizeof(*girq->parents),
2011 GFP_KERNEL);
2012 if (!girq->parents) {
2013 chip_err(gc, "out of memory allocating parent IRQ\n");
2014 return;
2016 girq->parents[0] = parent_irq;
2017 girq->num_parents = 1;
2019 * The parent irqchip is already using the chip_data for this
2020 * irqchip, so our callbacks simply use the handler_data.
2022 irq_set_chained_handler_and_data(parent_irq, parent_handler,
2023 gc);
2028 * gpiochip_set_nested_irqchip() - connects a nested irqchip to a gpiochip
2029 * @gpiochip: the gpiochip to set the irqchip nested handler to
2030 * @irqchip: the irqchip to nest to the gpiochip
2031 * @parent_irq: the irq number corresponding to the parent IRQ for this
2032 * nested irqchip
2034 void gpiochip_set_nested_irqchip(struct gpio_chip *gpiochip,
2035 struct irq_chip *irqchip,
2036 unsigned int parent_irq)
2038 gpiochip_set_cascaded_irqchip(gpiochip, parent_irq, NULL);
2040 EXPORT_SYMBOL_GPL(gpiochip_set_nested_irqchip);
2042 #ifdef CONFIG_IRQ_DOMAIN_HIERARCHY
2045 * gpiochip_set_hierarchical_irqchip() - connects a hierarchical irqchip
2046 * to a gpiochip
2047 * @gc: the gpiochip to set the irqchip hierarchical handler to
2048 * @irqchip: the irqchip to handle this level of the hierarchy, the interrupt
2049 * will then percolate up to the parent
2051 static void gpiochip_set_hierarchical_irqchip(struct gpio_chip *gc,
2052 struct irq_chip *irqchip)
2054 /* DT will deal with mapping each IRQ as we go along */
2055 if (is_of_node(gc->irq.fwnode))
2056 return;
2059 * This is for legacy and boardfile "irqchip" fwnodes: allocate
2060 * irqs upfront instead of dynamically since we don't have the
2061 * dynamic type of allocation that hardware description languages
2062 * provide. Once all GPIO drivers using board files are gone from
2063 * the kernel we can delete this code, but for a transitional period
2064 * it is necessary to keep this around.
2066 if (is_fwnode_irqchip(gc->irq.fwnode)) {
2067 int i;
2068 int ret;
2070 for (i = 0; i < gc->ngpio; i++) {
2071 struct irq_fwspec fwspec;
2072 unsigned int parent_hwirq;
2073 unsigned int parent_type;
2074 struct gpio_irq_chip *girq = &gc->irq;
2077 * We call the child to parent translation function
2078 * only to check if the child IRQ is valid or not.
2079 * Just pick the rising edge type here as that is what
2080 * we likely need to support.
2082 ret = girq->child_to_parent_hwirq(gc, i,
2083 IRQ_TYPE_EDGE_RISING,
2084 &parent_hwirq,
2085 &parent_type);
2086 if (ret) {
2087 chip_err(gc, "skip set-up on hwirq %d\n",
2089 continue;
2092 fwspec.fwnode = gc->irq.fwnode;
2093 /* This is the hwirq for the GPIO line side of things */
2094 fwspec.param[0] = girq->child_offset_to_irq(gc, i);
2095 /* Just pick something */
2096 fwspec.param[1] = IRQ_TYPE_EDGE_RISING;
2097 fwspec.param_count = 2;
2098 ret = __irq_domain_alloc_irqs(gc->irq.domain,
2099 /* just pick something */
2102 NUMA_NO_NODE,
2103 &fwspec,
2104 false,
2105 NULL);
2106 if (ret < 0) {
2107 chip_err(gc,
2108 "can not allocate irq for GPIO line %d parent hwirq %d in hierarchy domain: %d\n",
2109 i, parent_hwirq,
2110 ret);
2115 chip_err(gc, "%s unknown fwnode type proceed anyway\n", __func__);
2117 return;
2120 static int gpiochip_hierarchy_irq_domain_translate(struct irq_domain *d,
2121 struct irq_fwspec *fwspec,
2122 unsigned long *hwirq,
2123 unsigned int *type)
2125 /* We support standard DT translation */
2126 if (is_of_node(fwspec->fwnode) && fwspec->param_count == 2) {
2127 return irq_domain_translate_twocell(d, fwspec, hwirq, type);
2130 /* This is for board files and others not using DT */
2131 if (is_fwnode_irqchip(fwspec->fwnode)) {
2132 int ret;
2134 ret = irq_domain_translate_twocell(d, fwspec, hwirq, type);
2135 if (ret)
2136 return ret;
2137 WARN_ON(*type == IRQ_TYPE_NONE);
2138 return 0;
2140 return -EINVAL;
2143 static int gpiochip_hierarchy_irq_domain_alloc(struct irq_domain *d,
2144 unsigned int irq,
2145 unsigned int nr_irqs,
2146 void *data)
2148 struct gpio_chip *gc = d->host_data;
2149 irq_hw_number_t hwirq;
2150 unsigned int type = IRQ_TYPE_NONE;
2151 struct irq_fwspec *fwspec = data;
2152 void *parent_arg;
2153 unsigned int parent_hwirq;
2154 unsigned int parent_type;
2155 struct gpio_irq_chip *girq = &gc->irq;
2156 int ret;
2159 * The nr_irqs parameter is always one except for PCI multi-MSI
2160 * so this should not happen.
2162 WARN_ON(nr_irqs != 1);
2164 ret = gc->irq.child_irq_domain_ops.translate(d, fwspec, &hwirq, &type);
2165 if (ret)
2166 return ret;
2168 chip_dbg(gc, "allocate IRQ %d, hwirq %lu\n", irq, hwirq);
2170 ret = girq->child_to_parent_hwirq(gc, hwirq, type,
2171 &parent_hwirq, &parent_type);
2172 if (ret) {
2173 chip_err(gc, "can't look up hwirq %lu\n", hwirq);
2174 return ret;
2176 chip_dbg(gc, "found parent hwirq %u\n", parent_hwirq);
2179 * We set handle_bad_irq because the .set_type() should
2180 * always be invoked and set the right type of handler.
2182 irq_domain_set_info(d,
2183 irq,
2184 hwirq,
2185 gc->irq.chip,
2187 girq->handler,
2188 NULL, NULL);
2189 irq_set_probe(irq);
2191 /* This parent only handles asserted level IRQs */
2192 parent_arg = girq->populate_parent_alloc_arg(gc, parent_hwirq, parent_type);
2193 if (!parent_arg)
2194 return -ENOMEM;
2196 chip_dbg(gc, "alloc_irqs_parent for %d parent hwirq %d\n",
2197 irq, parent_hwirq);
2198 irq_set_lockdep_class(irq, gc->irq.lock_key, gc->irq.request_key);
2199 ret = irq_domain_alloc_irqs_parent(d, irq, 1, parent_arg);
2201 * If the parent irqdomain is msi, the interrupts have already
2202 * been allocated, so the EEXIST is good.
2204 if (irq_domain_is_msi(d->parent) && (ret == -EEXIST))
2205 ret = 0;
2206 if (ret)
2207 chip_err(gc,
2208 "failed to allocate parent hwirq %d for hwirq %lu\n",
2209 parent_hwirq, hwirq);
2211 kfree(parent_arg);
2212 return ret;
2215 static unsigned int gpiochip_child_offset_to_irq_noop(struct gpio_chip *chip,
2216 unsigned int offset)
2218 return offset;
2221 static void gpiochip_hierarchy_setup_domain_ops(struct irq_domain_ops *ops)
2223 ops->activate = gpiochip_irq_domain_activate;
2224 ops->deactivate = gpiochip_irq_domain_deactivate;
2225 ops->alloc = gpiochip_hierarchy_irq_domain_alloc;
2226 ops->free = irq_domain_free_irqs_common;
2229 * We only allow overriding the translate() function for
2230 * hierarchical chips, and this should only be done if the user
2231 * really need something other than 1:1 translation.
2233 if (!ops->translate)
2234 ops->translate = gpiochip_hierarchy_irq_domain_translate;
2237 static int gpiochip_hierarchy_add_domain(struct gpio_chip *gc)
2239 if (!gc->irq.child_to_parent_hwirq ||
2240 !gc->irq.fwnode) {
2241 chip_err(gc, "missing irqdomain vital data\n");
2242 return -EINVAL;
2245 if (!gc->irq.child_offset_to_irq)
2246 gc->irq.child_offset_to_irq = gpiochip_child_offset_to_irq_noop;
2248 if (!gc->irq.populate_parent_alloc_arg)
2249 gc->irq.populate_parent_alloc_arg =
2250 gpiochip_populate_parent_fwspec_twocell;
2252 gpiochip_hierarchy_setup_domain_ops(&gc->irq.child_irq_domain_ops);
2254 gc->irq.domain = irq_domain_create_hierarchy(
2255 gc->irq.parent_domain,
2257 gc->ngpio,
2258 gc->irq.fwnode,
2259 &gc->irq.child_irq_domain_ops,
2260 gc);
2262 if (!gc->irq.domain)
2263 return -ENOMEM;
2265 gpiochip_set_hierarchical_irqchip(gc, gc->irq.chip);
2267 return 0;
2270 static bool gpiochip_hierarchy_is_hierarchical(struct gpio_chip *gc)
2272 return !!gc->irq.parent_domain;
2275 void *gpiochip_populate_parent_fwspec_twocell(struct gpio_chip *chip,
2276 unsigned int parent_hwirq,
2277 unsigned int parent_type)
2279 struct irq_fwspec *fwspec;
2281 fwspec = kmalloc(sizeof(*fwspec), GFP_KERNEL);
2282 if (!fwspec)
2283 return NULL;
2285 fwspec->fwnode = chip->irq.parent_domain->fwnode;
2286 fwspec->param_count = 2;
2287 fwspec->param[0] = parent_hwirq;
2288 fwspec->param[1] = parent_type;
2290 return fwspec;
2292 EXPORT_SYMBOL_GPL(gpiochip_populate_parent_fwspec_twocell);
2294 void *gpiochip_populate_parent_fwspec_fourcell(struct gpio_chip *chip,
2295 unsigned int parent_hwirq,
2296 unsigned int parent_type)
2298 struct irq_fwspec *fwspec;
2300 fwspec = kmalloc(sizeof(*fwspec), GFP_KERNEL);
2301 if (!fwspec)
2302 return NULL;
2304 fwspec->fwnode = chip->irq.parent_domain->fwnode;
2305 fwspec->param_count = 4;
2306 fwspec->param[0] = 0;
2307 fwspec->param[1] = parent_hwirq;
2308 fwspec->param[2] = 0;
2309 fwspec->param[3] = parent_type;
2311 return fwspec;
2313 EXPORT_SYMBOL_GPL(gpiochip_populate_parent_fwspec_fourcell);
2315 #else
2317 static int gpiochip_hierarchy_add_domain(struct gpio_chip *gc)
2319 return -EINVAL;
2322 static bool gpiochip_hierarchy_is_hierarchical(struct gpio_chip *gc)
2324 return false;
2327 #endif /* CONFIG_IRQ_DOMAIN_HIERARCHY */
2330 * gpiochip_irq_map() - maps an IRQ into a GPIO irqchip
2331 * @d: the irqdomain used by this irqchip
2332 * @irq: the global irq number used by this GPIO irqchip irq
2333 * @hwirq: the local IRQ/GPIO line offset on this gpiochip
2335 * This function will set up the mapping for a certain IRQ line on a
2336 * gpiochip by assigning the gpiochip as chip data, and using the irqchip
2337 * stored inside the gpiochip.
2339 int gpiochip_irq_map(struct irq_domain *d, unsigned int irq,
2340 irq_hw_number_t hwirq)
2342 struct gpio_chip *chip = d->host_data;
2343 int ret = 0;
2345 if (!gpiochip_irqchip_irq_valid(chip, hwirq))
2346 return -ENXIO;
2348 irq_set_chip_data(irq, chip);
2350 * This lock class tells lockdep that GPIO irqs are in a different
2351 * category than their parents, so it won't report false recursion.
2353 irq_set_lockdep_class(irq, chip->irq.lock_key, chip->irq.request_key);
2354 irq_set_chip_and_handler(irq, chip->irq.chip, chip->irq.handler);
2355 /* Chips that use nested thread handlers have them marked */
2356 if (chip->irq.threaded)
2357 irq_set_nested_thread(irq, 1);
2358 irq_set_noprobe(irq);
2360 if (chip->irq.num_parents == 1)
2361 ret = irq_set_parent(irq, chip->irq.parents[0]);
2362 else if (chip->irq.map)
2363 ret = irq_set_parent(irq, chip->irq.map[hwirq]);
2365 if (ret < 0)
2366 return ret;
2369 * No set-up of the hardware will happen if IRQ_TYPE_NONE
2370 * is passed as default type.
2372 if (chip->irq.default_type != IRQ_TYPE_NONE)
2373 irq_set_irq_type(irq, chip->irq.default_type);
2375 return 0;
2377 EXPORT_SYMBOL_GPL(gpiochip_irq_map);
2379 void gpiochip_irq_unmap(struct irq_domain *d, unsigned int irq)
2381 struct gpio_chip *chip = d->host_data;
2383 if (chip->irq.threaded)
2384 irq_set_nested_thread(irq, 0);
2385 irq_set_chip_and_handler(irq, NULL, NULL);
2386 irq_set_chip_data(irq, NULL);
2388 EXPORT_SYMBOL_GPL(gpiochip_irq_unmap);
2390 static const struct irq_domain_ops gpiochip_domain_ops = {
2391 .map = gpiochip_irq_map,
2392 .unmap = gpiochip_irq_unmap,
2393 /* Virtually all GPIO irqchips are twocell:ed */
2394 .xlate = irq_domain_xlate_twocell,
2398 * TODO: move these activate/deactivate in under the hierarchicial
2399 * irqchip implementation as static once SPMI and SSBI (all external
2400 * users) are phased over.
2403 * gpiochip_irq_domain_activate() - Lock a GPIO to be used as an IRQ
2404 * @domain: The IRQ domain used by this IRQ chip
2405 * @data: Outermost irq_data associated with the IRQ
2406 * @reserve: If set, only reserve an interrupt vector instead of assigning one
2408 * This function is a wrapper that calls gpiochip_lock_as_irq() and is to be
2409 * used as the activate function for the &struct irq_domain_ops. The host_data
2410 * for the IRQ domain must be the &struct gpio_chip.
2412 int gpiochip_irq_domain_activate(struct irq_domain *domain,
2413 struct irq_data *data, bool reserve)
2415 struct gpio_chip *chip = domain->host_data;
2417 return gpiochip_lock_as_irq(chip, data->hwirq);
2419 EXPORT_SYMBOL_GPL(gpiochip_irq_domain_activate);
2422 * gpiochip_irq_domain_deactivate() - Unlock a GPIO used as an IRQ
2423 * @domain: The IRQ domain used by this IRQ chip
2424 * @data: Outermost irq_data associated with the IRQ
2426 * This function is a wrapper that will call gpiochip_unlock_as_irq() and is to
2427 * be used as the deactivate function for the &struct irq_domain_ops. The
2428 * host_data for the IRQ domain must be the &struct gpio_chip.
2430 void gpiochip_irq_domain_deactivate(struct irq_domain *domain,
2431 struct irq_data *data)
2433 struct gpio_chip *chip = domain->host_data;
2435 return gpiochip_unlock_as_irq(chip, data->hwirq);
2437 EXPORT_SYMBOL_GPL(gpiochip_irq_domain_deactivate);
2439 static int gpiochip_to_irq(struct gpio_chip *chip, unsigned offset)
2441 struct irq_domain *domain = chip->irq.domain;
2443 if (!gpiochip_irqchip_irq_valid(chip, offset))
2444 return -ENXIO;
2446 #ifdef CONFIG_IRQ_DOMAIN_HIERARCHY
2447 if (irq_domain_is_hierarchy(domain)) {
2448 struct irq_fwspec spec;
2450 spec.fwnode = domain->fwnode;
2451 spec.param_count = 2;
2452 spec.param[0] = chip->irq.child_offset_to_irq(chip, offset);
2453 spec.param[1] = IRQ_TYPE_NONE;
2455 return irq_create_fwspec_mapping(&spec);
2457 #endif
2459 return irq_create_mapping(domain, offset);
2462 static int gpiochip_irq_reqres(struct irq_data *d)
2464 struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
2466 return gpiochip_reqres_irq(chip, d->hwirq);
2469 static void gpiochip_irq_relres(struct irq_data *d)
2471 struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
2473 gpiochip_relres_irq(chip, d->hwirq);
2476 static void gpiochip_irq_enable(struct irq_data *d)
2478 struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
2480 gpiochip_enable_irq(chip, d->hwirq);
2481 if (chip->irq.irq_enable)
2482 chip->irq.irq_enable(d);
2483 else
2484 chip->irq.chip->irq_unmask(d);
2487 static void gpiochip_irq_disable(struct irq_data *d)
2489 struct gpio_chip *chip = irq_data_get_irq_chip_data(d);
2491 if (chip->irq.irq_disable)
2492 chip->irq.irq_disable(d);
2493 else
2494 chip->irq.chip->irq_mask(d);
2495 gpiochip_disable_irq(chip, d->hwirq);
2498 static void gpiochip_set_irq_hooks(struct gpio_chip *gpiochip)
2500 struct irq_chip *irqchip = gpiochip->irq.chip;
2502 if (!irqchip->irq_request_resources &&
2503 !irqchip->irq_release_resources) {
2504 irqchip->irq_request_resources = gpiochip_irq_reqres;
2505 irqchip->irq_release_resources = gpiochip_irq_relres;
2507 if (WARN_ON(gpiochip->irq.irq_enable))
2508 return;
2509 /* Check if the irqchip already has this hook... */
2510 if (irqchip->irq_enable == gpiochip_irq_enable) {
2512 * ...and if so, give a gentle warning that this is bad
2513 * practice.
2515 chip_info(gpiochip,
2516 "detected irqchip that is shared with multiple gpiochips: please fix the driver.\n");
2517 return;
2519 gpiochip->irq.irq_enable = irqchip->irq_enable;
2520 gpiochip->irq.irq_disable = irqchip->irq_disable;
2521 irqchip->irq_enable = gpiochip_irq_enable;
2522 irqchip->irq_disable = gpiochip_irq_disable;
2526 * gpiochip_add_irqchip() - adds an IRQ chip to a GPIO chip
2527 * @gpiochip: the GPIO chip to add the IRQ chip to
2528 * @lock_key: lockdep class for IRQ lock
2529 * @request_key: lockdep class for IRQ request
2531 static int gpiochip_add_irqchip(struct gpio_chip *gpiochip,
2532 struct lock_class_key *lock_key,
2533 struct lock_class_key *request_key)
2535 struct irq_chip *irqchip = gpiochip->irq.chip;
2536 const struct irq_domain_ops *ops = NULL;
2537 struct device_node *np;
2538 unsigned int type;
2539 unsigned int i;
2541 if (!irqchip)
2542 return 0;
2544 if (gpiochip->irq.parent_handler && gpiochip->can_sleep) {
2545 chip_err(gpiochip, "you cannot have chained interrupts on a chip that may sleep\n");
2546 return -EINVAL;
2549 np = gpiochip->gpiodev->dev.of_node;
2550 type = gpiochip->irq.default_type;
2553 * Specifying a default trigger is a terrible idea if DT or ACPI is
2554 * used to configure the interrupts, as you may end up with
2555 * conflicting triggers. Tell the user, and reset to NONE.
2557 if (WARN(np && type != IRQ_TYPE_NONE,
2558 "%s: Ignoring %u default trigger\n", np->full_name, type))
2559 type = IRQ_TYPE_NONE;
2561 if (has_acpi_companion(gpiochip->parent) && type != IRQ_TYPE_NONE) {
2562 acpi_handle_warn(ACPI_HANDLE(gpiochip->parent),
2563 "Ignoring %u default trigger\n", type);
2564 type = IRQ_TYPE_NONE;
2567 gpiochip->to_irq = gpiochip_to_irq;
2568 gpiochip->irq.default_type = type;
2569 gpiochip->irq.lock_key = lock_key;
2570 gpiochip->irq.request_key = request_key;
2572 /* If a parent irqdomain is provided, let's build a hierarchy */
2573 if (gpiochip_hierarchy_is_hierarchical(gpiochip)) {
2574 int ret = gpiochip_hierarchy_add_domain(gpiochip);
2575 if (ret)
2576 return ret;
2577 } else {
2578 /* Some drivers provide custom irqdomain ops */
2579 if (gpiochip->irq.domain_ops)
2580 ops = gpiochip->irq.domain_ops;
2582 if (!ops)
2583 ops = &gpiochip_domain_ops;
2584 gpiochip->irq.domain = irq_domain_add_simple(np,
2585 gpiochip->ngpio,
2586 gpiochip->irq.first,
2587 ops, gpiochip);
2588 if (!gpiochip->irq.domain)
2589 return -EINVAL;
2592 if (gpiochip->irq.parent_handler) {
2593 void *data = gpiochip->irq.parent_handler_data ?: gpiochip;
2595 for (i = 0; i < gpiochip->irq.num_parents; i++) {
2597 * The parent IRQ chip is already using the chip_data
2598 * for this IRQ chip, so our callbacks simply use the
2599 * handler_data.
2601 irq_set_chained_handler_and_data(gpiochip->irq.parents[i],
2602 gpiochip->irq.parent_handler,
2603 data);
2607 gpiochip_set_irq_hooks(gpiochip);
2609 acpi_gpiochip_request_interrupts(gpiochip);
2611 return 0;
2615 * gpiochip_irqchip_remove() - removes an irqchip added to a gpiochip
2616 * @gpiochip: the gpiochip to remove the irqchip from
2618 * This is called only from gpiochip_remove()
2620 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip)
2622 struct irq_chip *irqchip = gpiochip->irq.chip;
2623 unsigned int offset;
2625 acpi_gpiochip_free_interrupts(gpiochip);
2627 if (irqchip && gpiochip->irq.parent_handler) {
2628 struct gpio_irq_chip *irq = &gpiochip->irq;
2629 unsigned int i;
2631 for (i = 0; i < irq->num_parents; i++)
2632 irq_set_chained_handler_and_data(irq->parents[i],
2633 NULL, NULL);
2636 /* Remove all IRQ mappings and delete the domain */
2637 if (gpiochip->irq.domain) {
2638 unsigned int irq;
2640 for (offset = 0; offset < gpiochip->ngpio; offset++) {
2641 if (!gpiochip_irqchip_irq_valid(gpiochip, offset))
2642 continue;
2644 irq = irq_find_mapping(gpiochip->irq.domain, offset);
2645 irq_dispose_mapping(irq);
2648 irq_domain_remove(gpiochip->irq.domain);
2651 if (irqchip) {
2652 if (irqchip->irq_request_resources == gpiochip_irq_reqres) {
2653 irqchip->irq_request_resources = NULL;
2654 irqchip->irq_release_resources = NULL;
2656 if (irqchip->irq_enable == gpiochip_irq_enable) {
2657 irqchip->irq_enable = gpiochip->irq.irq_enable;
2658 irqchip->irq_disable = gpiochip->irq.irq_disable;
2661 gpiochip->irq.irq_enable = NULL;
2662 gpiochip->irq.irq_disable = NULL;
2663 gpiochip->irq.chip = NULL;
2665 gpiochip_irqchip_free_valid_mask(gpiochip);
2669 * gpiochip_irqchip_add_key() - adds an irqchip to a gpiochip
2670 * @gpiochip: the gpiochip to add the irqchip to
2671 * @irqchip: the irqchip to add to the gpiochip
2672 * @first_irq: if not dynamically assigned, the base (first) IRQ to
2673 * allocate gpiochip irqs from
2674 * @handler: the irq handler to use (often a predefined irq core function)
2675 * @type: the default type for IRQs on this irqchip, pass IRQ_TYPE_NONE
2676 * to have the core avoid setting up any default type in the hardware.
2677 * @threaded: whether this irqchip uses a nested thread handler
2678 * @lock_key: lockdep class for IRQ lock
2679 * @request_key: lockdep class for IRQ request
2681 * This function closely associates a certain irqchip with a certain
2682 * gpiochip, providing an irq domain to translate the local IRQs to
2683 * global irqs in the gpiolib core, and making sure that the gpiochip
2684 * is passed as chip data to all related functions. Driver callbacks
2685 * need to use gpiochip_get_data() to get their local state containers back
2686 * from the gpiochip passed as chip data. An irqdomain will be stored
2687 * in the gpiochip that shall be used by the driver to handle IRQ number
2688 * translation. The gpiochip will need to be initialized and registered
2689 * before calling this function.
2691 * This function will handle two cell:ed simple IRQs and assumes all
2692 * the pins on the gpiochip can generate a unique IRQ. Everything else
2693 * need to be open coded.
2695 int gpiochip_irqchip_add_key(struct gpio_chip *gpiochip,
2696 struct irq_chip *irqchip,
2697 unsigned int first_irq,
2698 irq_flow_handler_t handler,
2699 unsigned int type,
2700 bool threaded,
2701 struct lock_class_key *lock_key,
2702 struct lock_class_key *request_key)
2704 struct device_node *of_node;
2706 if (!gpiochip || !irqchip)
2707 return -EINVAL;
2709 if (!gpiochip->parent) {
2710 pr_err("missing gpiochip .dev parent pointer\n");
2711 return -EINVAL;
2713 gpiochip->irq.threaded = threaded;
2714 of_node = gpiochip->parent->of_node;
2715 #ifdef CONFIG_OF_GPIO
2717 * If the gpiochip has an assigned OF node this takes precedence
2718 * FIXME: get rid of this and use gpiochip->parent->of_node
2719 * everywhere
2721 if (gpiochip->of_node)
2722 of_node = gpiochip->of_node;
2723 #endif
2725 * Specifying a default trigger is a terrible idea if DT or ACPI is
2726 * used to configure the interrupts, as you may end-up with
2727 * conflicting triggers. Tell the user, and reset to NONE.
2729 if (WARN(of_node && type != IRQ_TYPE_NONE,
2730 "%pOF: Ignoring %d default trigger\n", of_node, type))
2731 type = IRQ_TYPE_NONE;
2732 if (has_acpi_companion(gpiochip->parent) && type != IRQ_TYPE_NONE) {
2733 acpi_handle_warn(ACPI_HANDLE(gpiochip->parent),
2734 "Ignoring %d default trigger\n", type);
2735 type = IRQ_TYPE_NONE;
2738 gpiochip->irq.chip = irqchip;
2739 gpiochip->irq.handler = handler;
2740 gpiochip->irq.default_type = type;
2741 gpiochip->to_irq = gpiochip_to_irq;
2742 gpiochip->irq.lock_key = lock_key;
2743 gpiochip->irq.request_key = request_key;
2744 gpiochip->irq.domain = irq_domain_add_simple(of_node,
2745 gpiochip->ngpio, first_irq,
2746 &gpiochip_domain_ops, gpiochip);
2747 if (!gpiochip->irq.domain) {
2748 gpiochip->irq.chip = NULL;
2749 return -EINVAL;
2752 gpiochip_set_irq_hooks(gpiochip);
2754 acpi_gpiochip_request_interrupts(gpiochip);
2756 return 0;
2758 EXPORT_SYMBOL_GPL(gpiochip_irqchip_add_key);
2760 #else /* CONFIG_GPIOLIB_IRQCHIP */
2762 static inline int gpiochip_add_irqchip(struct gpio_chip *gpiochip,
2763 struct lock_class_key *lock_key,
2764 struct lock_class_key *request_key)
2766 return 0;
2768 static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip) {}
2770 static inline int gpiochip_irqchip_init_hw(struct gpio_chip *gpiochip)
2772 return 0;
2775 static inline int gpiochip_irqchip_init_valid_mask(struct gpio_chip *gpiochip)
2777 return 0;
2779 static inline void gpiochip_irqchip_free_valid_mask(struct gpio_chip *gpiochip)
2782 #endif /* CONFIG_GPIOLIB_IRQCHIP */
2785 * gpiochip_generic_request() - request the gpio function for a pin
2786 * @chip: the gpiochip owning the GPIO
2787 * @offset: the offset of the GPIO to request for GPIO function
2789 int gpiochip_generic_request(struct gpio_chip *chip, unsigned offset)
2791 return pinctrl_gpio_request(chip->gpiodev->base + offset);
2793 EXPORT_SYMBOL_GPL(gpiochip_generic_request);
2796 * gpiochip_generic_free() - free the gpio function from a pin
2797 * @chip: the gpiochip to request the gpio function for
2798 * @offset: the offset of the GPIO to free from GPIO function
2800 void gpiochip_generic_free(struct gpio_chip *chip, unsigned offset)
2802 pinctrl_gpio_free(chip->gpiodev->base + offset);
2804 EXPORT_SYMBOL_GPL(gpiochip_generic_free);
2807 * gpiochip_generic_config() - apply configuration for a pin
2808 * @chip: the gpiochip owning the GPIO
2809 * @offset: the offset of the GPIO to apply the configuration
2810 * @config: the configuration to be applied
2812 int gpiochip_generic_config(struct gpio_chip *chip, unsigned offset,
2813 unsigned long config)
2815 return pinctrl_gpio_set_config(chip->gpiodev->base + offset, config);
2817 EXPORT_SYMBOL_GPL(gpiochip_generic_config);
2819 #ifdef CONFIG_PINCTRL
2822 * gpiochip_add_pingroup_range() - add a range for GPIO <-> pin mapping
2823 * @chip: the gpiochip to add the range for
2824 * @pctldev: the pin controller to map to
2825 * @gpio_offset: the start offset in the current gpio_chip number space
2826 * @pin_group: name of the pin group inside the pin controller
2828 * Calling this function directly from a DeviceTree-supported
2829 * pinctrl driver is DEPRECATED. Please see Section 2.1 of
2830 * Documentation/devicetree/bindings/gpio/gpio.txt on how to
2831 * bind pinctrl and gpio drivers via the "gpio-ranges" property.
2833 int gpiochip_add_pingroup_range(struct gpio_chip *chip,
2834 struct pinctrl_dev *pctldev,
2835 unsigned int gpio_offset, const char *pin_group)
2837 struct gpio_pin_range *pin_range;
2838 struct gpio_device *gdev = chip->gpiodev;
2839 int ret;
2841 pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
2842 if (!pin_range) {
2843 chip_err(chip, "failed to allocate pin ranges\n");
2844 return -ENOMEM;
2847 /* Use local offset as range ID */
2848 pin_range->range.id = gpio_offset;
2849 pin_range->range.gc = chip;
2850 pin_range->range.name = chip->label;
2851 pin_range->range.base = gdev->base + gpio_offset;
2852 pin_range->pctldev = pctldev;
2854 ret = pinctrl_get_group_pins(pctldev, pin_group,
2855 &pin_range->range.pins,
2856 &pin_range->range.npins);
2857 if (ret < 0) {
2858 kfree(pin_range);
2859 return ret;
2862 pinctrl_add_gpio_range(pctldev, &pin_range->range);
2864 chip_dbg(chip, "created GPIO range %d->%d ==> %s PINGRP %s\n",
2865 gpio_offset, gpio_offset + pin_range->range.npins - 1,
2866 pinctrl_dev_get_devname(pctldev), pin_group);
2868 list_add_tail(&pin_range->node, &gdev->pin_ranges);
2870 return 0;
2872 EXPORT_SYMBOL_GPL(gpiochip_add_pingroup_range);
2875 * gpiochip_add_pin_range() - add a range for GPIO <-> pin mapping
2876 * @chip: the gpiochip to add the range for
2877 * @pinctl_name: the dev_name() of the pin controller to map to
2878 * @gpio_offset: the start offset in the current gpio_chip number space
2879 * @pin_offset: the start offset in the pin controller number space
2880 * @npins: the number of pins from the offset of each pin space (GPIO and
2881 * pin controller) to accumulate in this range
2883 * Returns:
2884 * 0 on success, or a negative error-code on failure.
2886 * Calling this function directly from a DeviceTree-supported
2887 * pinctrl driver is DEPRECATED. Please see Section 2.1 of
2888 * Documentation/devicetree/bindings/gpio/gpio.txt on how to
2889 * bind pinctrl and gpio drivers via the "gpio-ranges" property.
2891 int gpiochip_add_pin_range(struct gpio_chip *chip, const char *pinctl_name,
2892 unsigned int gpio_offset, unsigned int pin_offset,
2893 unsigned int npins)
2895 struct gpio_pin_range *pin_range;
2896 struct gpio_device *gdev = chip->gpiodev;
2897 int ret;
2899 pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL);
2900 if (!pin_range) {
2901 chip_err(chip, "failed to allocate pin ranges\n");
2902 return -ENOMEM;
2905 /* Use local offset as range ID */
2906 pin_range->range.id = gpio_offset;
2907 pin_range->range.gc = chip;
2908 pin_range->range.name = chip->label;
2909 pin_range->range.base = gdev->base + gpio_offset;
2910 pin_range->range.pin_base = pin_offset;
2911 pin_range->range.npins = npins;
2912 pin_range->pctldev = pinctrl_find_and_add_gpio_range(pinctl_name,
2913 &pin_range->range);
2914 if (IS_ERR(pin_range->pctldev)) {
2915 ret = PTR_ERR(pin_range->pctldev);
2916 chip_err(chip, "could not create pin range\n");
2917 kfree(pin_range);
2918 return ret;
2920 chip_dbg(chip, "created GPIO range %d->%d ==> %s PIN %d->%d\n",
2921 gpio_offset, gpio_offset + npins - 1,
2922 pinctl_name,
2923 pin_offset, pin_offset + npins - 1);
2925 list_add_tail(&pin_range->node, &gdev->pin_ranges);
2927 return 0;
2929 EXPORT_SYMBOL_GPL(gpiochip_add_pin_range);
2932 * gpiochip_remove_pin_ranges() - remove all the GPIO <-> pin mappings
2933 * @chip: the chip to remove all the mappings for
2935 void gpiochip_remove_pin_ranges(struct gpio_chip *chip)
2937 struct gpio_pin_range *pin_range, *tmp;
2938 struct gpio_device *gdev = chip->gpiodev;
2940 list_for_each_entry_safe(pin_range, tmp, &gdev->pin_ranges, node) {
2941 list_del(&pin_range->node);
2942 pinctrl_remove_gpio_range(pin_range->pctldev,
2943 &pin_range->range);
2944 kfree(pin_range);
2947 EXPORT_SYMBOL_GPL(gpiochip_remove_pin_ranges);
2949 #endif /* CONFIG_PINCTRL */
2951 /* These "optional" allocation calls help prevent drivers from stomping
2952 * on each other, and help provide better diagnostics in debugfs.
2953 * They're called even less than the "set direction" calls.
2955 static int gpiod_request_commit(struct gpio_desc *desc, const char *label)
2957 struct gpio_chip *chip = desc->gdev->chip;
2958 int ret;
2959 unsigned long flags;
2960 unsigned offset;
2962 if (label) {
2963 label = kstrdup_const(label, GFP_KERNEL);
2964 if (!label)
2965 return -ENOMEM;
2968 spin_lock_irqsave(&gpio_lock, flags);
2970 /* NOTE: gpio_request() can be called in early boot,
2971 * before IRQs are enabled, for non-sleeping (SOC) GPIOs.
2974 if (test_and_set_bit(FLAG_REQUESTED, &desc->flags) == 0) {
2975 desc_set_label(desc, label ? : "?");
2976 ret = 0;
2977 } else {
2978 kfree_const(label);
2979 ret = -EBUSY;
2980 goto done;
2983 if (chip->request) {
2984 /* chip->request may sleep */
2985 spin_unlock_irqrestore(&gpio_lock, flags);
2986 offset = gpio_chip_hwgpio(desc);
2987 if (gpiochip_line_is_valid(chip, offset))
2988 ret = chip->request(chip, offset);
2989 else
2990 ret = -EINVAL;
2991 spin_lock_irqsave(&gpio_lock, flags);
2993 if (ret < 0) {
2994 desc_set_label(desc, NULL);
2995 kfree_const(label);
2996 clear_bit(FLAG_REQUESTED, &desc->flags);
2997 goto done;
3000 if (chip->get_direction) {
3001 /* chip->get_direction may sleep */
3002 spin_unlock_irqrestore(&gpio_lock, flags);
3003 gpiod_get_direction(desc);
3004 spin_lock_irqsave(&gpio_lock, flags);
3006 done:
3007 spin_unlock_irqrestore(&gpio_lock, flags);
3008 atomic_notifier_call_chain(&desc->gdev->notifier,
3009 GPIOLINE_CHANGED_REQUESTED, desc);
3010 return ret;
3014 * This descriptor validation needs to be inserted verbatim into each
3015 * function taking a descriptor, so we need to use a preprocessor
3016 * macro to avoid endless duplication. If the desc is NULL it is an
3017 * optional GPIO and calls should just bail out.
3019 static int validate_desc(const struct gpio_desc *desc, const char *func)
3021 if (!desc)
3022 return 0;
3023 if (IS_ERR(desc)) {
3024 pr_warn("%s: invalid GPIO (errorpointer)\n", func);
3025 return PTR_ERR(desc);
3027 if (!desc->gdev) {
3028 pr_warn("%s: invalid GPIO (no device)\n", func);
3029 return -EINVAL;
3031 if (!desc->gdev->chip) {
3032 dev_warn(&desc->gdev->dev,
3033 "%s: backing chip is gone\n", func);
3034 return 0;
3036 return 1;
3039 #define VALIDATE_DESC(desc) do { \
3040 int __valid = validate_desc(desc, __func__); \
3041 if (__valid <= 0) \
3042 return __valid; \
3043 } while (0)
3045 #define VALIDATE_DESC_VOID(desc) do { \
3046 int __valid = validate_desc(desc, __func__); \
3047 if (__valid <= 0) \
3048 return; \
3049 } while (0)
3051 int gpiod_request(struct gpio_desc *desc, const char *label)
3053 int ret = -EPROBE_DEFER;
3054 struct gpio_device *gdev;
3056 VALIDATE_DESC(desc);
3057 gdev = desc->gdev;
3059 if (try_module_get(gdev->owner)) {
3060 ret = gpiod_request_commit(desc, label);
3061 if (ret < 0)
3062 module_put(gdev->owner);
3063 else
3064 get_device(&gdev->dev);
3067 if (ret)
3068 gpiod_dbg(desc, "%s: status %d\n", __func__, ret);
3070 return ret;
3073 static bool gpiod_free_commit(struct gpio_desc *desc)
3075 bool ret = false;
3076 unsigned long flags;
3077 struct gpio_chip *chip;
3079 might_sleep();
3081 gpiod_unexport(desc);
3083 spin_lock_irqsave(&gpio_lock, flags);
3085 chip = desc->gdev->chip;
3086 if (chip && test_bit(FLAG_REQUESTED, &desc->flags)) {
3087 if (chip->free) {
3088 spin_unlock_irqrestore(&gpio_lock, flags);
3089 might_sleep_if(chip->can_sleep);
3090 chip->free(chip, gpio_chip_hwgpio(desc));
3091 spin_lock_irqsave(&gpio_lock, flags);
3093 kfree_const(desc->label);
3094 desc_set_label(desc, NULL);
3095 clear_bit(FLAG_ACTIVE_LOW, &desc->flags);
3096 clear_bit(FLAG_REQUESTED, &desc->flags);
3097 clear_bit(FLAG_OPEN_DRAIN, &desc->flags);
3098 clear_bit(FLAG_OPEN_SOURCE, &desc->flags);
3099 clear_bit(FLAG_PULL_UP, &desc->flags);
3100 clear_bit(FLAG_PULL_DOWN, &desc->flags);
3101 clear_bit(FLAG_BIAS_DISABLE, &desc->flags);
3102 clear_bit(FLAG_IS_HOGGED, &desc->flags);
3103 #ifdef CONFIG_OF_DYNAMIC
3104 desc->hog = NULL;
3105 #endif
3106 ret = true;
3109 spin_unlock_irqrestore(&gpio_lock, flags);
3110 atomic_notifier_call_chain(&desc->gdev->notifier,
3111 GPIOLINE_CHANGED_RELEASED, desc);
3113 return ret;
3116 void gpiod_free(struct gpio_desc *desc)
3118 if (desc && desc->gdev && gpiod_free_commit(desc)) {
3119 module_put(desc->gdev->owner);
3120 put_device(&desc->gdev->dev);
3121 } else {
3122 WARN_ON(extra_checks);
3127 * gpiochip_is_requested - return string iff signal was requested
3128 * @chip: controller managing the signal
3129 * @offset: of signal within controller's 0..(ngpio - 1) range
3131 * Returns NULL if the GPIO is not currently requested, else a string.
3132 * The string returned is the label passed to gpio_request(); if none has been
3133 * passed it is a meaningless, non-NULL constant.
3135 * This function is for use by GPIO controller drivers. The label can
3136 * help with diagnostics, and knowing that the signal is used as a GPIO
3137 * can help avoid accidentally multiplexing it to another controller.
3139 const char *gpiochip_is_requested(struct gpio_chip *chip, unsigned offset)
3141 struct gpio_desc *desc;
3143 if (offset >= chip->ngpio)
3144 return NULL;
3146 desc = gpiochip_get_desc(chip, offset);
3147 if (IS_ERR(desc))
3148 return NULL;
3150 if (test_bit(FLAG_REQUESTED, &desc->flags) == 0)
3151 return NULL;
3152 return desc->label;
3154 EXPORT_SYMBOL_GPL(gpiochip_is_requested);
3157 * gpiochip_request_own_desc - Allow GPIO chip to request its own descriptor
3158 * @chip: GPIO chip
3159 * @hwnum: hardware number of the GPIO for which to request the descriptor
3160 * @label: label for the GPIO
3161 * @lflags: lookup flags for this GPIO or 0 if default, this can be used to
3162 * specify things like line inversion semantics with the machine flags
3163 * such as GPIO_OUT_LOW
3164 * @dflags: descriptor request flags for this GPIO or 0 if default, this
3165 * can be used to specify consumer semantics such as open drain
3167 * Function allows GPIO chip drivers to request and use their own GPIO
3168 * descriptors via gpiolib API. Difference to gpiod_request() is that this
3169 * function will not increase reference count of the GPIO chip module. This
3170 * allows the GPIO chip module to be unloaded as needed (we assume that the
3171 * GPIO chip driver handles freeing the GPIOs it has requested).
3173 * Returns:
3174 * A pointer to the GPIO descriptor, or an ERR_PTR()-encoded negative error
3175 * code on failure.
3177 struct gpio_desc *gpiochip_request_own_desc(struct gpio_chip *chip,
3178 unsigned int hwnum,
3179 const char *label,
3180 enum gpio_lookup_flags lflags,
3181 enum gpiod_flags dflags)
3183 struct gpio_desc *desc = gpiochip_get_desc(chip, hwnum);
3184 int ret;
3186 if (IS_ERR(desc)) {
3187 chip_err(chip, "failed to get GPIO descriptor\n");
3188 return desc;
3191 ret = gpiod_request_commit(desc, label);
3192 if (ret < 0)
3193 return ERR_PTR(ret);
3195 ret = gpiod_configure_flags(desc, label, lflags, dflags);
3196 if (ret) {
3197 chip_err(chip, "setup of own GPIO %s failed\n", label);
3198 gpiod_free_commit(desc);
3199 return ERR_PTR(ret);
3202 return desc;
3204 EXPORT_SYMBOL_GPL(gpiochip_request_own_desc);
3207 * gpiochip_free_own_desc - Free GPIO requested by the chip driver
3208 * @desc: GPIO descriptor to free
3210 * Function frees the given GPIO requested previously with
3211 * gpiochip_request_own_desc().
3213 void gpiochip_free_own_desc(struct gpio_desc *desc)
3215 if (desc)
3216 gpiod_free_commit(desc);
3218 EXPORT_SYMBOL_GPL(gpiochip_free_own_desc);
3221 * Drivers MUST set GPIO direction before making get/set calls. In
3222 * some cases this is done in early boot, before IRQs are enabled.
3224 * As a rule these aren't called more than once (except for drivers
3225 * using the open-drain emulation idiom) so these are natural places
3226 * to accumulate extra debugging checks. Note that we can't (yet)
3227 * rely on gpio_request() having been called beforehand.
3230 static int gpio_set_config(struct gpio_chip *gc, unsigned int offset,
3231 enum pin_config_param mode)
3233 if (!gc->set_config)
3234 return -ENOTSUPP;
3236 return gc->set_config(gc, offset, mode);
3239 static int gpio_set_bias(struct gpio_chip *chip, struct gpio_desc *desc)
3241 int bias = 0;
3242 int ret = 0;
3244 if (test_bit(FLAG_BIAS_DISABLE, &desc->flags))
3245 bias = PIN_CONFIG_BIAS_DISABLE;
3246 else if (test_bit(FLAG_PULL_UP, &desc->flags))
3247 bias = PIN_CONFIG_BIAS_PULL_UP;
3248 else if (test_bit(FLAG_PULL_DOWN, &desc->flags))
3249 bias = PIN_CONFIG_BIAS_PULL_DOWN;
3251 if (bias) {
3252 ret = gpio_set_config(chip, gpio_chip_hwgpio(desc), bias);
3253 if (ret != -ENOTSUPP)
3254 return ret;
3256 return 0;
3260 * gpiod_direction_input - set the GPIO direction to input
3261 * @desc: GPIO to set to input
3263 * Set the direction of the passed GPIO to input, such as gpiod_get_value() can
3264 * be called safely on it.
3266 * Return 0 in case of success, else an error code.
3268 int gpiod_direction_input(struct gpio_desc *desc)
3270 struct gpio_chip *chip;
3271 int ret = 0;
3273 VALIDATE_DESC(desc);
3274 chip = desc->gdev->chip;
3277 * It is legal to have no .get() and .direction_input() specified if
3278 * the chip is output-only, but you can't specify .direction_input()
3279 * and not support the .get() operation, that doesn't make sense.
3281 if (!chip->get && chip->direction_input) {
3282 gpiod_warn(desc,
3283 "%s: missing get() but have direction_input()\n",
3284 __func__);
3285 return -EIO;
3289 * If we have a .direction_input() callback, things are simple,
3290 * just call it. Else we are some input-only chip so try to check the
3291 * direction (if .get_direction() is supported) else we silently
3292 * assume we are in input mode after this.
3294 if (chip->direction_input) {
3295 ret = chip->direction_input(chip, gpio_chip_hwgpio(desc));
3296 } else if (chip->get_direction &&
3297 (chip->get_direction(chip, gpio_chip_hwgpio(desc)) != 1)) {
3298 gpiod_warn(desc,
3299 "%s: missing direction_input() operation and line is output\n",
3300 __func__);
3301 return -EIO;
3303 if (ret == 0) {
3304 clear_bit(FLAG_IS_OUT, &desc->flags);
3305 ret = gpio_set_bias(chip, desc);
3308 trace_gpio_direction(desc_to_gpio(desc), 1, ret);
3310 return ret;
3312 EXPORT_SYMBOL_GPL(gpiod_direction_input);
3314 static int gpiod_direction_output_raw_commit(struct gpio_desc *desc, int value)
3316 struct gpio_chip *gc = desc->gdev->chip;
3317 int val = !!value;
3318 int ret = 0;
3321 * It's OK not to specify .direction_output() if the gpiochip is
3322 * output-only, but if there is then not even a .set() operation it
3323 * is pretty tricky to drive the output line.
3325 if (!gc->set && !gc->direction_output) {
3326 gpiod_warn(desc,
3327 "%s: missing set() and direction_output() operations\n",
3328 __func__);
3329 return -EIO;
3332 if (gc->direction_output) {
3333 ret = gc->direction_output(gc, gpio_chip_hwgpio(desc), val);
3334 } else {
3335 /* Check that we are in output mode if we can */
3336 if (gc->get_direction &&
3337 gc->get_direction(gc, gpio_chip_hwgpio(desc))) {
3338 gpiod_warn(desc,
3339 "%s: missing direction_output() operation\n",
3340 __func__);
3341 return -EIO;
3344 * If we can't actively set the direction, we are some
3345 * output-only chip, so just drive the output as desired.
3347 gc->set(gc, gpio_chip_hwgpio(desc), val);
3350 if (!ret)
3351 set_bit(FLAG_IS_OUT, &desc->flags);
3352 trace_gpio_value(desc_to_gpio(desc), 0, val);
3353 trace_gpio_direction(desc_to_gpio(desc), 0, ret);
3354 return ret;
3358 * gpiod_direction_output_raw - set the GPIO direction to output
3359 * @desc: GPIO to set to output
3360 * @value: initial output value of the GPIO
3362 * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
3363 * be called safely on it. The initial value of the output must be specified
3364 * as raw value on the physical line without regard for the ACTIVE_LOW status.
3366 * Return 0 in case of success, else an error code.
3368 int gpiod_direction_output_raw(struct gpio_desc *desc, int value)
3370 VALIDATE_DESC(desc);
3371 return gpiod_direction_output_raw_commit(desc, value);
3373 EXPORT_SYMBOL_GPL(gpiod_direction_output_raw);
3376 * gpiod_direction_output - set the GPIO direction to output
3377 * @desc: GPIO to set to output
3378 * @value: initial output value of the GPIO
3380 * Set the direction of the passed GPIO to output, such as gpiod_set_value() can
3381 * be called safely on it. The initial value of the output must be specified
3382 * as the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
3383 * account.
3385 * Return 0 in case of success, else an error code.
3387 int gpiod_direction_output(struct gpio_desc *desc, int value)
3389 struct gpio_chip *gc;
3390 int ret;
3392 VALIDATE_DESC(desc);
3393 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3394 value = !value;
3395 else
3396 value = !!value;
3398 /* GPIOs used for enabled IRQs shall not be set as output */
3399 if (test_bit(FLAG_USED_AS_IRQ, &desc->flags) &&
3400 test_bit(FLAG_IRQ_IS_ENABLED, &desc->flags)) {
3401 gpiod_err(desc,
3402 "%s: tried to set a GPIO tied to an IRQ as output\n",
3403 __func__);
3404 return -EIO;
3407 gc = desc->gdev->chip;
3408 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags)) {
3409 /* First see if we can enable open drain in hardware */
3410 ret = gpio_set_config(gc, gpio_chip_hwgpio(desc),
3411 PIN_CONFIG_DRIVE_OPEN_DRAIN);
3412 if (!ret)
3413 goto set_output_value;
3414 /* Emulate open drain by not actively driving the line high */
3415 if (value) {
3416 ret = gpiod_direction_input(desc);
3417 goto set_output_flag;
3420 else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags)) {
3421 ret = gpio_set_config(gc, gpio_chip_hwgpio(desc),
3422 PIN_CONFIG_DRIVE_OPEN_SOURCE);
3423 if (!ret)
3424 goto set_output_value;
3425 /* Emulate open source by not actively driving the line low */
3426 if (!value) {
3427 ret = gpiod_direction_input(desc);
3428 goto set_output_flag;
3430 } else {
3431 gpio_set_config(gc, gpio_chip_hwgpio(desc),
3432 PIN_CONFIG_DRIVE_PUSH_PULL);
3435 set_output_value:
3436 ret = gpio_set_bias(gc, desc);
3437 if (ret)
3438 return ret;
3439 return gpiod_direction_output_raw_commit(desc, value);
3441 set_output_flag:
3443 * When emulating open-source or open-drain functionalities by not
3444 * actively driving the line (setting mode to input) we still need to
3445 * set the IS_OUT flag or otherwise we won't be able to set the line
3446 * value anymore.
3448 if (ret == 0)
3449 set_bit(FLAG_IS_OUT, &desc->flags);
3450 return ret;
3452 EXPORT_SYMBOL_GPL(gpiod_direction_output);
3455 * gpiod_set_debounce - sets @debounce time for a GPIO
3456 * @desc: descriptor of the GPIO for which to set debounce time
3457 * @debounce: debounce time in microseconds
3459 * Returns:
3460 * 0 on success, %-ENOTSUPP if the controller doesn't support setting the
3461 * debounce time.
3463 int gpiod_set_debounce(struct gpio_desc *desc, unsigned debounce)
3465 struct gpio_chip *chip;
3466 unsigned long config;
3468 VALIDATE_DESC(desc);
3469 chip = desc->gdev->chip;
3471 config = pinconf_to_config_packed(PIN_CONFIG_INPUT_DEBOUNCE, debounce);
3472 return gpio_set_config(chip, gpio_chip_hwgpio(desc), config);
3474 EXPORT_SYMBOL_GPL(gpiod_set_debounce);
3477 * gpiod_set_transitory - Lose or retain GPIO state on suspend or reset
3478 * @desc: descriptor of the GPIO for which to configure persistence
3479 * @transitory: True to lose state on suspend or reset, false for persistence
3481 * Returns:
3482 * 0 on success, otherwise a negative error code.
3484 int gpiod_set_transitory(struct gpio_desc *desc, bool transitory)
3486 struct gpio_chip *chip;
3487 unsigned long packed;
3488 int gpio;
3489 int rc;
3491 VALIDATE_DESC(desc);
3493 * Handle FLAG_TRANSITORY first, enabling queries to gpiolib for
3494 * persistence state.
3496 assign_bit(FLAG_TRANSITORY, &desc->flags, transitory);
3498 /* If the driver supports it, set the persistence state now */
3499 chip = desc->gdev->chip;
3500 if (!chip->set_config)
3501 return 0;
3503 packed = pinconf_to_config_packed(PIN_CONFIG_PERSIST_STATE,
3504 !transitory);
3505 gpio = gpio_chip_hwgpio(desc);
3506 rc = gpio_set_config(chip, gpio, packed);
3507 if (rc == -ENOTSUPP) {
3508 dev_dbg(&desc->gdev->dev, "Persistence not supported for GPIO %d\n",
3509 gpio);
3510 return 0;
3513 return rc;
3515 EXPORT_SYMBOL_GPL(gpiod_set_transitory);
3518 * gpiod_is_active_low - test whether a GPIO is active-low or not
3519 * @desc: the gpio descriptor to test
3521 * Returns 1 if the GPIO is active-low, 0 otherwise.
3523 int gpiod_is_active_low(const struct gpio_desc *desc)
3525 VALIDATE_DESC(desc);
3526 return test_bit(FLAG_ACTIVE_LOW, &desc->flags);
3528 EXPORT_SYMBOL_GPL(gpiod_is_active_low);
3531 * gpiod_toggle_active_low - toggle whether a GPIO is active-low or not
3532 * @desc: the gpio descriptor to change
3534 void gpiod_toggle_active_low(struct gpio_desc *desc)
3536 VALIDATE_DESC_VOID(desc);
3537 change_bit(FLAG_ACTIVE_LOW, &desc->flags);
3539 EXPORT_SYMBOL_GPL(gpiod_toggle_active_low);
3541 /* I/O calls are only valid after configuration completed; the relevant
3542 * "is this a valid GPIO" error checks should already have been done.
3544 * "Get" operations are often inlinable as reading a pin value register,
3545 * and masking the relevant bit in that register.
3547 * When "set" operations are inlinable, they involve writing that mask to
3548 * one register to set a low value, or a different register to set it high.
3549 * Otherwise locking is needed, so there may be little value to inlining.
3551 *------------------------------------------------------------------------
3553 * IMPORTANT!!! The hot paths -- get/set value -- assume that callers
3554 * have requested the GPIO. That can include implicit requesting by
3555 * a direction setting call. Marking a gpio as requested locks its chip
3556 * in memory, guaranteeing that these table lookups need no more locking
3557 * and that gpiochip_remove() will fail.
3559 * REVISIT when debugging, consider adding some instrumentation to ensure
3560 * that the GPIO was actually requested.
3563 static int gpiod_get_raw_value_commit(const struct gpio_desc *desc)
3565 struct gpio_chip *chip;
3566 int offset;
3567 int value;
3569 chip = desc->gdev->chip;
3570 offset = gpio_chip_hwgpio(desc);
3571 value = chip->get ? chip->get(chip, offset) : -EIO;
3572 value = value < 0 ? value : !!value;
3573 trace_gpio_value(desc_to_gpio(desc), 1, value);
3574 return value;
3577 static int gpio_chip_get_multiple(struct gpio_chip *chip,
3578 unsigned long *mask, unsigned long *bits)
3580 if (chip->get_multiple) {
3581 return chip->get_multiple(chip, mask, bits);
3582 } else if (chip->get) {
3583 int i, value;
3585 for_each_set_bit(i, mask, chip->ngpio) {
3586 value = chip->get(chip, i);
3587 if (value < 0)
3588 return value;
3589 __assign_bit(i, bits, value);
3591 return 0;
3593 return -EIO;
3596 int gpiod_get_array_value_complex(bool raw, bool can_sleep,
3597 unsigned int array_size,
3598 struct gpio_desc **desc_array,
3599 struct gpio_array *array_info,
3600 unsigned long *value_bitmap)
3602 int ret, i = 0;
3605 * Validate array_info against desc_array and its size.
3606 * It should immediately follow desc_array if both
3607 * have been obtained from the same gpiod_get_array() call.
3609 if (array_info && array_info->desc == desc_array &&
3610 array_size <= array_info->size &&
3611 (void *)array_info == desc_array + array_info->size) {
3612 if (!can_sleep)
3613 WARN_ON(array_info->chip->can_sleep);
3615 ret = gpio_chip_get_multiple(array_info->chip,
3616 array_info->get_mask,
3617 value_bitmap);
3618 if (ret)
3619 return ret;
3621 if (!raw && !bitmap_empty(array_info->invert_mask, array_size))
3622 bitmap_xor(value_bitmap, value_bitmap,
3623 array_info->invert_mask, array_size);
3625 if (bitmap_full(array_info->get_mask, array_size))
3626 return 0;
3628 i = find_first_zero_bit(array_info->get_mask, array_size);
3629 } else {
3630 array_info = NULL;
3633 while (i < array_size) {
3634 struct gpio_chip *chip = desc_array[i]->gdev->chip;
3635 unsigned long fastpath[2 * BITS_TO_LONGS(FASTPATH_NGPIO)];
3636 unsigned long *mask, *bits;
3637 int first, j, ret;
3639 if (likely(chip->ngpio <= FASTPATH_NGPIO)) {
3640 mask = fastpath;
3641 } else {
3642 mask = kmalloc_array(2 * BITS_TO_LONGS(chip->ngpio),
3643 sizeof(*mask),
3644 can_sleep ? GFP_KERNEL : GFP_ATOMIC);
3645 if (!mask)
3646 return -ENOMEM;
3649 bits = mask + BITS_TO_LONGS(chip->ngpio);
3650 bitmap_zero(mask, chip->ngpio);
3652 if (!can_sleep)
3653 WARN_ON(chip->can_sleep);
3655 /* collect all inputs belonging to the same chip */
3656 first = i;
3657 do {
3658 const struct gpio_desc *desc = desc_array[i];
3659 int hwgpio = gpio_chip_hwgpio(desc);
3661 __set_bit(hwgpio, mask);
3662 i++;
3664 if (array_info)
3665 i = find_next_zero_bit(array_info->get_mask,
3666 array_size, i);
3667 } while ((i < array_size) &&
3668 (desc_array[i]->gdev->chip == chip));
3670 ret = gpio_chip_get_multiple(chip, mask, bits);
3671 if (ret) {
3672 if (mask != fastpath)
3673 kfree(mask);
3674 return ret;
3677 for (j = first; j < i; ) {
3678 const struct gpio_desc *desc = desc_array[j];
3679 int hwgpio = gpio_chip_hwgpio(desc);
3680 int value = test_bit(hwgpio, bits);
3682 if (!raw && test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3683 value = !value;
3684 __assign_bit(j, value_bitmap, value);
3685 trace_gpio_value(desc_to_gpio(desc), 1, value);
3686 j++;
3688 if (array_info)
3689 j = find_next_zero_bit(array_info->get_mask, i,
3693 if (mask != fastpath)
3694 kfree(mask);
3696 return 0;
3700 * gpiod_get_raw_value() - return a gpio's raw value
3701 * @desc: gpio whose value will be returned
3703 * Return the GPIO's raw value, i.e. the value of the physical line disregarding
3704 * its ACTIVE_LOW status, or negative errno on failure.
3706 * This function can be called from contexts where we cannot sleep, and will
3707 * complain if the GPIO chip functions potentially sleep.
3709 int gpiod_get_raw_value(const struct gpio_desc *desc)
3711 VALIDATE_DESC(desc);
3712 /* Should be using gpiod_get_raw_value_cansleep() */
3713 WARN_ON(desc->gdev->chip->can_sleep);
3714 return gpiod_get_raw_value_commit(desc);
3716 EXPORT_SYMBOL_GPL(gpiod_get_raw_value);
3719 * gpiod_get_value() - return a gpio's value
3720 * @desc: gpio whose value will be returned
3722 * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
3723 * account, or negative errno on failure.
3725 * This function can be called from contexts where we cannot sleep, and will
3726 * complain if the GPIO chip functions potentially sleep.
3728 int gpiod_get_value(const struct gpio_desc *desc)
3730 int value;
3732 VALIDATE_DESC(desc);
3733 /* Should be using gpiod_get_value_cansleep() */
3734 WARN_ON(desc->gdev->chip->can_sleep);
3736 value = gpiod_get_raw_value_commit(desc);
3737 if (value < 0)
3738 return value;
3740 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3741 value = !value;
3743 return value;
3745 EXPORT_SYMBOL_GPL(gpiod_get_value);
3748 * gpiod_get_raw_array_value() - read raw values from an array of GPIOs
3749 * @array_size: number of elements in the descriptor array / value bitmap
3750 * @desc_array: array of GPIO descriptors whose values will be read
3751 * @array_info: information on applicability of fast bitmap processing path
3752 * @value_bitmap: bitmap to store the read values
3754 * Read the raw values of the GPIOs, i.e. the values of the physical lines
3755 * without regard for their ACTIVE_LOW status. Return 0 in case of success,
3756 * else an error code.
3758 * This function can be called from contexts where we cannot sleep,
3759 * and it will complain if the GPIO chip functions potentially sleep.
3761 int gpiod_get_raw_array_value(unsigned int array_size,
3762 struct gpio_desc **desc_array,
3763 struct gpio_array *array_info,
3764 unsigned long *value_bitmap)
3766 if (!desc_array)
3767 return -EINVAL;
3768 return gpiod_get_array_value_complex(true, false, array_size,
3769 desc_array, array_info,
3770 value_bitmap);
3772 EXPORT_SYMBOL_GPL(gpiod_get_raw_array_value);
3775 * gpiod_get_array_value() - read values from an array of GPIOs
3776 * @array_size: number of elements in the descriptor array / value bitmap
3777 * @desc_array: array of GPIO descriptors whose values will be read
3778 * @array_info: information on applicability of fast bitmap processing path
3779 * @value_bitmap: bitmap to store the read values
3781 * Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
3782 * into account. Return 0 in case of success, else an error code.
3784 * This function can be called from contexts where we cannot sleep,
3785 * and it will complain if the GPIO chip functions potentially sleep.
3787 int gpiod_get_array_value(unsigned int array_size,
3788 struct gpio_desc **desc_array,
3789 struct gpio_array *array_info,
3790 unsigned long *value_bitmap)
3792 if (!desc_array)
3793 return -EINVAL;
3794 return gpiod_get_array_value_complex(false, false, array_size,
3795 desc_array, array_info,
3796 value_bitmap);
3798 EXPORT_SYMBOL_GPL(gpiod_get_array_value);
3801 * gpio_set_open_drain_value_commit() - Set the open drain gpio's value.
3802 * @desc: gpio descriptor whose state need to be set.
3803 * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
3805 static void gpio_set_open_drain_value_commit(struct gpio_desc *desc, bool value)
3807 int ret = 0;
3808 struct gpio_chip *chip = desc->gdev->chip;
3809 int offset = gpio_chip_hwgpio(desc);
3811 if (value) {
3812 ret = chip->direction_input(chip, offset);
3813 } else {
3814 ret = chip->direction_output(chip, offset, 0);
3815 if (!ret)
3816 set_bit(FLAG_IS_OUT, &desc->flags);
3818 trace_gpio_direction(desc_to_gpio(desc), value, ret);
3819 if (ret < 0)
3820 gpiod_err(desc,
3821 "%s: Error in set_value for open drain err %d\n",
3822 __func__, ret);
3826 * _gpio_set_open_source_value() - Set the open source gpio's value.
3827 * @desc: gpio descriptor whose state need to be set.
3828 * @value: Non-zero for setting it HIGH otherwise it will set to LOW.
3830 static void gpio_set_open_source_value_commit(struct gpio_desc *desc, bool value)
3832 int ret = 0;
3833 struct gpio_chip *chip = desc->gdev->chip;
3834 int offset = gpio_chip_hwgpio(desc);
3836 if (value) {
3837 ret = chip->direction_output(chip, offset, 1);
3838 if (!ret)
3839 set_bit(FLAG_IS_OUT, &desc->flags);
3840 } else {
3841 ret = chip->direction_input(chip, offset);
3843 trace_gpio_direction(desc_to_gpio(desc), !value, ret);
3844 if (ret < 0)
3845 gpiod_err(desc,
3846 "%s: Error in set_value for open source err %d\n",
3847 __func__, ret);
3850 static void gpiod_set_raw_value_commit(struct gpio_desc *desc, bool value)
3852 struct gpio_chip *chip;
3854 chip = desc->gdev->chip;
3855 trace_gpio_value(desc_to_gpio(desc), 0, value);
3856 chip->set(chip, gpio_chip_hwgpio(desc), value);
3860 * set multiple outputs on the same chip;
3861 * use the chip's set_multiple function if available;
3862 * otherwise set the outputs sequentially;
3863 * @mask: bit mask array; one bit per output; BITS_PER_LONG bits per word
3864 * defines which outputs are to be changed
3865 * @bits: bit value array; one bit per output; BITS_PER_LONG bits per word
3866 * defines the values the outputs specified by mask are to be set to
3868 static void gpio_chip_set_multiple(struct gpio_chip *chip,
3869 unsigned long *mask, unsigned long *bits)
3871 if (chip->set_multiple) {
3872 chip->set_multiple(chip, mask, bits);
3873 } else {
3874 unsigned int i;
3876 /* set outputs if the corresponding mask bit is set */
3877 for_each_set_bit(i, mask, chip->ngpio)
3878 chip->set(chip, i, test_bit(i, bits));
3882 int gpiod_set_array_value_complex(bool raw, bool can_sleep,
3883 unsigned int array_size,
3884 struct gpio_desc **desc_array,
3885 struct gpio_array *array_info,
3886 unsigned long *value_bitmap)
3888 int i = 0;
3891 * Validate array_info against desc_array and its size.
3892 * It should immediately follow desc_array if both
3893 * have been obtained from the same gpiod_get_array() call.
3895 if (array_info && array_info->desc == desc_array &&
3896 array_size <= array_info->size &&
3897 (void *)array_info == desc_array + array_info->size) {
3898 if (!can_sleep)
3899 WARN_ON(array_info->chip->can_sleep);
3901 if (!raw && !bitmap_empty(array_info->invert_mask, array_size))
3902 bitmap_xor(value_bitmap, value_bitmap,
3903 array_info->invert_mask, array_size);
3905 gpio_chip_set_multiple(array_info->chip, array_info->set_mask,
3906 value_bitmap);
3908 if (bitmap_full(array_info->set_mask, array_size))
3909 return 0;
3911 i = find_first_zero_bit(array_info->set_mask, array_size);
3912 } else {
3913 array_info = NULL;
3916 while (i < array_size) {
3917 struct gpio_chip *chip = desc_array[i]->gdev->chip;
3918 unsigned long fastpath[2 * BITS_TO_LONGS(FASTPATH_NGPIO)];
3919 unsigned long *mask, *bits;
3920 int count = 0;
3922 if (likely(chip->ngpio <= FASTPATH_NGPIO)) {
3923 mask = fastpath;
3924 } else {
3925 mask = kmalloc_array(2 * BITS_TO_LONGS(chip->ngpio),
3926 sizeof(*mask),
3927 can_sleep ? GFP_KERNEL : GFP_ATOMIC);
3928 if (!mask)
3929 return -ENOMEM;
3932 bits = mask + BITS_TO_LONGS(chip->ngpio);
3933 bitmap_zero(mask, chip->ngpio);
3935 if (!can_sleep)
3936 WARN_ON(chip->can_sleep);
3938 do {
3939 struct gpio_desc *desc = desc_array[i];
3940 int hwgpio = gpio_chip_hwgpio(desc);
3941 int value = test_bit(i, value_bitmap);
3944 * Pins applicable for fast input but not for
3945 * fast output processing may have been already
3946 * inverted inside the fast path, skip them.
3948 if (!raw && !(array_info &&
3949 test_bit(i, array_info->invert_mask)) &&
3950 test_bit(FLAG_ACTIVE_LOW, &desc->flags))
3951 value = !value;
3952 trace_gpio_value(desc_to_gpio(desc), 0, value);
3954 * collect all normal outputs belonging to the same chip
3955 * open drain and open source outputs are set individually
3957 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags) && !raw) {
3958 gpio_set_open_drain_value_commit(desc, value);
3959 } else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags) && !raw) {
3960 gpio_set_open_source_value_commit(desc, value);
3961 } else {
3962 __set_bit(hwgpio, mask);
3963 __assign_bit(hwgpio, bits, value);
3964 count++;
3966 i++;
3968 if (array_info)
3969 i = find_next_zero_bit(array_info->set_mask,
3970 array_size, i);
3971 } while ((i < array_size) &&
3972 (desc_array[i]->gdev->chip == chip));
3973 /* push collected bits to outputs */
3974 if (count != 0)
3975 gpio_chip_set_multiple(chip, mask, bits);
3977 if (mask != fastpath)
3978 kfree(mask);
3980 return 0;
3984 * gpiod_set_raw_value() - assign a gpio's raw value
3985 * @desc: gpio whose value will be assigned
3986 * @value: value to assign
3988 * Set the raw value of the GPIO, i.e. the value of its physical line without
3989 * regard for its ACTIVE_LOW status.
3991 * This function can be called from contexts where we cannot sleep, and will
3992 * complain if the GPIO chip functions potentially sleep.
3994 void gpiod_set_raw_value(struct gpio_desc *desc, int value)
3996 VALIDATE_DESC_VOID(desc);
3997 /* Should be using gpiod_set_raw_value_cansleep() */
3998 WARN_ON(desc->gdev->chip->can_sleep);
3999 gpiod_set_raw_value_commit(desc, value);
4001 EXPORT_SYMBOL_GPL(gpiod_set_raw_value);
4004 * gpiod_set_value_nocheck() - set a GPIO line value without checking
4005 * @desc: the descriptor to set the value on
4006 * @value: value to set
4008 * This sets the value of a GPIO line backing a descriptor, applying
4009 * different semantic quirks like active low and open drain/source
4010 * handling.
4012 static void gpiod_set_value_nocheck(struct gpio_desc *desc, int value)
4014 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
4015 value = !value;
4016 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
4017 gpio_set_open_drain_value_commit(desc, value);
4018 else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
4019 gpio_set_open_source_value_commit(desc, value);
4020 else
4021 gpiod_set_raw_value_commit(desc, value);
4025 * gpiod_set_value() - assign a gpio's value
4026 * @desc: gpio whose value will be assigned
4027 * @value: value to assign
4029 * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW,
4030 * OPEN_DRAIN and OPEN_SOURCE flags into account.
4032 * This function can be called from contexts where we cannot sleep, and will
4033 * complain if the GPIO chip functions potentially sleep.
4035 void gpiod_set_value(struct gpio_desc *desc, int value)
4037 VALIDATE_DESC_VOID(desc);
4038 /* Should be using gpiod_set_value_cansleep() */
4039 WARN_ON(desc->gdev->chip->can_sleep);
4040 gpiod_set_value_nocheck(desc, value);
4042 EXPORT_SYMBOL_GPL(gpiod_set_value);
4045 * gpiod_set_raw_array_value() - assign values to an array of GPIOs
4046 * @array_size: number of elements in the descriptor array / value bitmap
4047 * @desc_array: array of GPIO descriptors whose values will be assigned
4048 * @array_info: information on applicability of fast bitmap processing path
4049 * @value_bitmap: bitmap of values to assign
4051 * Set the raw values of the GPIOs, i.e. the values of the physical lines
4052 * without regard for their ACTIVE_LOW status.
4054 * This function can be called from contexts where we cannot sleep, and will
4055 * complain if the GPIO chip functions potentially sleep.
4057 int gpiod_set_raw_array_value(unsigned int array_size,
4058 struct gpio_desc **desc_array,
4059 struct gpio_array *array_info,
4060 unsigned long *value_bitmap)
4062 if (!desc_array)
4063 return -EINVAL;
4064 return gpiod_set_array_value_complex(true, false, array_size,
4065 desc_array, array_info, value_bitmap);
4067 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value);
4070 * gpiod_set_array_value() - assign values to an array of GPIOs
4071 * @array_size: number of elements in the descriptor array / value bitmap
4072 * @desc_array: array of GPIO descriptors whose values will be assigned
4073 * @array_info: information on applicability of fast bitmap processing path
4074 * @value_bitmap: bitmap of values to assign
4076 * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
4077 * into account.
4079 * This function can be called from contexts where we cannot sleep, and will
4080 * complain if the GPIO chip functions potentially sleep.
4082 int gpiod_set_array_value(unsigned int array_size,
4083 struct gpio_desc **desc_array,
4084 struct gpio_array *array_info,
4085 unsigned long *value_bitmap)
4087 if (!desc_array)
4088 return -EINVAL;
4089 return gpiod_set_array_value_complex(false, false, array_size,
4090 desc_array, array_info,
4091 value_bitmap);
4093 EXPORT_SYMBOL_GPL(gpiod_set_array_value);
4096 * gpiod_cansleep() - report whether gpio value access may sleep
4097 * @desc: gpio to check
4100 int gpiod_cansleep(const struct gpio_desc *desc)
4102 VALIDATE_DESC(desc);
4103 return desc->gdev->chip->can_sleep;
4105 EXPORT_SYMBOL_GPL(gpiod_cansleep);
4108 * gpiod_set_consumer_name() - set the consumer name for the descriptor
4109 * @desc: gpio to set the consumer name on
4110 * @name: the new consumer name
4112 int gpiod_set_consumer_name(struct gpio_desc *desc, const char *name)
4114 VALIDATE_DESC(desc);
4115 if (name) {
4116 name = kstrdup_const(name, GFP_KERNEL);
4117 if (!name)
4118 return -ENOMEM;
4121 kfree_const(desc->label);
4122 desc_set_label(desc, name);
4124 return 0;
4126 EXPORT_SYMBOL_GPL(gpiod_set_consumer_name);
4129 * gpiod_to_irq() - return the IRQ corresponding to a GPIO
4130 * @desc: gpio whose IRQ will be returned (already requested)
4132 * Return the IRQ corresponding to the passed GPIO, or an error code in case of
4133 * error.
4135 int gpiod_to_irq(const struct gpio_desc *desc)
4137 struct gpio_chip *chip;
4138 int offset;
4141 * Cannot VALIDATE_DESC() here as gpiod_to_irq() consumer semantics
4142 * requires this function to not return zero on an invalid descriptor
4143 * but rather a negative error number.
4145 if (!desc || IS_ERR(desc) || !desc->gdev || !desc->gdev->chip)
4146 return -EINVAL;
4148 chip = desc->gdev->chip;
4149 offset = gpio_chip_hwgpio(desc);
4150 if (chip->to_irq) {
4151 int retirq = chip->to_irq(chip, offset);
4153 /* Zero means NO_IRQ */
4154 if (!retirq)
4155 return -ENXIO;
4157 return retirq;
4159 return -ENXIO;
4161 EXPORT_SYMBOL_GPL(gpiod_to_irq);
4164 * gpiochip_lock_as_irq() - lock a GPIO to be used as IRQ
4165 * @chip: the chip the GPIO to lock belongs to
4166 * @offset: the offset of the GPIO to lock as IRQ
4168 * This is used directly by GPIO drivers that want to lock down
4169 * a certain GPIO line to be used for IRQs.
4171 int gpiochip_lock_as_irq(struct gpio_chip *chip, unsigned int offset)
4173 struct gpio_desc *desc;
4175 desc = gpiochip_get_desc(chip, offset);
4176 if (IS_ERR(desc))
4177 return PTR_ERR(desc);
4180 * If it's fast: flush the direction setting if something changed
4181 * behind our back
4183 if (!chip->can_sleep && chip->get_direction) {
4184 int dir = gpiod_get_direction(desc);
4186 if (dir < 0) {
4187 chip_err(chip, "%s: cannot get GPIO direction\n",
4188 __func__);
4189 return dir;
4193 if (test_bit(FLAG_IS_OUT, &desc->flags)) {
4194 chip_err(chip,
4195 "%s: tried to flag a GPIO set as output for IRQ\n",
4196 __func__);
4197 return -EIO;
4200 set_bit(FLAG_USED_AS_IRQ, &desc->flags);
4201 set_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
4204 * If the consumer has not set up a label (such as when the
4205 * IRQ is referenced from .to_irq()) we set up a label here
4206 * so it is clear this is used as an interrupt.
4208 if (!desc->label)
4209 desc_set_label(desc, "interrupt");
4211 return 0;
4213 EXPORT_SYMBOL_GPL(gpiochip_lock_as_irq);
4216 * gpiochip_unlock_as_irq() - unlock a GPIO used as IRQ
4217 * @chip: the chip the GPIO to lock belongs to
4218 * @offset: the offset of the GPIO to lock as IRQ
4220 * This is used directly by GPIO drivers that want to indicate
4221 * that a certain GPIO is no longer used exclusively for IRQ.
4223 void gpiochip_unlock_as_irq(struct gpio_chip *chip, unsigned int offset)
4225 struct gpio_desc *desc;
4227 desc = gpiochip_get_desc(chip, offset);
4228 if (IS_ERR(desc))
4229 return;
4231 clear_bit(FLAG_USED_AS_IRQ, &desc->flags);
4232 clear_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
4234 /* If we only had this marking, erase it */
4235 if (desc->label && !strcmp(desc->label, "interrupt"))
4236 desc_set_label(desc, NULL);
4238 EXPORT_SYMBOL_GPL(gpiochip_unlock_as_irq);
4240 void gpiochip_disable_irq(struct gpio_chip *chip, unsigned int offset)
4242 struct gpio_desc *desc = gpiochip_get_desc(chip, offset);
4244 if (!IS_ERR(desc) &&
4245 !WARN_ON(!test_bit(FLAG_USED_AS_IRQ, &desc->flags)))
4246 clear_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
4248 EXPORT_SYMBOL_GPL(gpiochip_disable_irq);
4250 void gpiochip_enable_irq(struct gpio_chip *chip, unsigned int offset)
4252 struct gpio_desc *desc = gpiochip_get_desc(chip, offset);
4254 if (!IS_ERR(desc) &&
4255 !WARN_ON(!test_bit(FLAG_USED_AS_IRQ, &desc->flags))) {
4256 WARN_ON(test_bit(FLAG_IS_OUT, &desc->flags));
4257 set_bit(FLAG_IRQ_IS_ENABLED, &desc->flags);
4260 EXPORT_SYMBOL_GPL(gpiochip_enable_irq);
4262 bool gpiochip_line_is_irq(struct gpio_chip *chip, unsigned int offset)
4264 if (offset >= chip->ngpio)
4265 return false;
4267 return test_bit(FLAG_USED_AS_IRQ, &chip->gpiodev->descs[offset].flags);
4269 EXPORT_SYMBOL_GPL(gpiochip_line_is_irq);
4271 int gpiochip_reqres_irq(struct gpio_chip *chip, unsigned int offset)
4273 int ret;
4275 if (!try_module_get(chip->gpiodev->owner))
4276 return -ENODEV;
4278 ret = gpiochip_lock_as_irq(chip, offset);
4279 if (ret) {
4280 chip_err(chip, "unable to lock HW IRQ %u for IRQ\n", offset);
4281 module_put(chip->gpiodev->owner);
4282 return ret;
4284 return 0;
4286 EXPORT_SYMBOL_GPL(gpiochip_reqres_irq);
4288 void gpiochip_relres_irq(struct gpio_chip *chip, unsigned int offset)
4290 gpiochip_unlock_as_irq(chip, offset);
4291 module_put(chip->gpiodev->owner);
4293 EXPORT_SYMBOL_GPL(gpiochip_relres_irq);
4295 bool gpiochip_line_is_open_drain(struct gpio_chip *chip, unsigned int offset)
4297 if (offset >= chip->ngpio)
4298 return false;
4300 return test_bit(FLAG_OPEN_DRAIN, &chip->gpiodev->descs[offset].flags);
4302 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_drain);
4304 bool gpiochip_line_is_open_source(struct gpio_chip *chip, unsigned int offset)
4306 if (offset >= chip->ngpio)
4307 return false;
4309 return test_bit(FLAG_OPEN_SOURCE, &chip->gpiodev->descs[offset].flags);
4311 EXPORT_SYMBOL_GPL(gpiochip_line_is_open_source);
4313 bool gpiochip_line_is_persistent(struct gpio_chip *chip, unsigned int offset)
4315 if (offset >= chip->ngpio)
4316 return false;
4318 return !test_bit(FLAG_TRANSITORY, &chip->gpiodev->descs[offset].flags);
4320 EXPORT_SYMBOL_GPL(gpiochip_line_is_persistent);
4323 * gpiod_get_raw_value_cansleep() - return a gpio's raw value
4324 * @desc: gpio whose value will be returned
4326 * Return the GPIO's raw value, i.e. the value of the physical line disregarding
4327 * its ACTIVE_LOW status, or negative errno on failure.
4329 * This function is to be called from contexts that can sleep.
4331 int gpiod_get_raw_value_cansleep(const struct gpio_desc *desc)
4333 might_sleep_if(extra_checks);
4334 VALIDATE_DESC(desc);
4335 return gpiod_get_raw_value_commit(desc);
4337 EXPORT_SYMBOL_GPL(gpiod_get_raw_value_cansleep);
4340 * gpiod_get_value_cansleep() - return a gpio's value
4341 * @desc: gpio whose value will be returned
4343 * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into
4344 * account, or negative errno on failure.
4346 * This function is to be called from contexts that can sleep.
4348 int gpiod_get_value_cansleep(const struct gpio_desc *desc)
4350 int value;
4352 might_sleep_if(extra_checks);
4353 VALIDATE_DESC(desc);
4354 value = gpiod_get_raw_value_commit(desc);
4355 if (value < 0)
4356 return value;
4358 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
4359 value = !value;
4361 return value;
4363 EXPORT_SYMBOL_GPL(gpiod_get_value_cansleep);
4366 * gpiod_get_raw_array_value_cansleep() - read raw values from an array of GPIOs
4367 * @array_size: number of elements in the descriptor array / value bitmap
4368 * @desc_array: array of GPIO descriptors whose values will be read
4369 * @array_info: information on applicability of fast bitmap processing path
4370 * @value_bitmap: bitmap to store the read values
4372 * Read the raw values of the GPIOs, i.e. the values of the physical lines
4373 * without regard for their ACTIVE_LOW status. Return 0 in case of success,
4374 * else an error code.
4376 * This function is to be called from contexts that can sleep.
4378 int gpiod_get_raw_array_value_cansleep(unsigned int array_size,
4379 struct gpio_desc **desc_array,
4380 struct gpio_array *array_info,
4381 unsigned long *value_bitmap)
4383 might_sleep_if(extra_checks);
4384 if (!desc_array)
4385 return -EINVAL;
4386 return gpiod_get_array_value_complex(true, true, array_size,
4387 desc_array, array_info,
4388 value_bitmap);
4390 EXPORT_SYMBOL_GPL(gpiod_get_raw_array_value_cansleep);
4393 * gpiod_get_array_value_cansleep() - read values from an array of GPIOs
4394 * @array_size: number of elements in the descriptor array / value bitmap
4395 * @desc_array: array of GPIO descriptors whose values will be read
4396 * @array_info: information on applicability of fast bitmap processing path
4397 * @value_bitmap: bitmap to store the read values
4399 * Read the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
4400 * into account. Return 0 in case of success, else an error code.
4402 * This function is to be called from contexts that can sleep.
4404 int gpiod_get_array_value_cansleep(unsigned int array_size,
4405 struct gpio_desc **desc_array,
4406 struct gpio_array *array_info,
4407 unsigned long *value_bitmap)
4409 might_sleep_if(extra_checks);
4410 if (!desc_array)
4411 return -EINVAL;
4412 return gpiod_get_array_value_complex(false, true, array_size,
4413 desc_array, array_info,
4414 value_bitmap);
4416 EXPORT_SYMBOL_GPL(gpiod_get_array_value_cansleep);
4419 * gpiod_set_raw_value_cansleep() - assign a gpio's raw value
4420 * @desc: gpio whose value will be assigned
4421 * @value: value to assign
4423 * Set the raw value of the GPIO, i.e. the value of its physical line without
4424 * regard for its ACTIVE_LOW status.
4426 * This function is to be called from contexts that can sleep.
4428 void gpiod_set_raw_value_cansleep(struct gpio_desc *desc, int value)
4430 might_sleep_if(extra_checks);
4431 VALIDATE_DESC_VOID(desc);
4432 gpiod_set_raw_value_commit(desc, value);
4434 EXPORT_SYMBOL_GPL(gpiod_set_raw_value_cansleep);
4437 * gpiod_set_value_cansleep() - assign a gpio's value
4438 * @desc: gpio whose value will be assigned
4439 * @value: value to assign
4441 * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into
4442 * account
4444 * This function is to be called from contexts that can sleep.
4446 void gpiod_set_value_cansleep(struct gpio_desc *desc, int value)
4448 might_sleep_if(extra_checks);
4449 VALIDATE_DESC_VOID(desc);
4450 gpiod_set_value_nocheck(desc, value);
4452 EXPORT_SYMBOL_GPL(gpiod_set_value_cansleep);
4455 * gpiod_set_raw_array_value_cansleep() - assign values to an array of GPIOs
4456 * @array_size: number of elements in the descriptor array / value bitmap
4457 * @desc_array: array of GPIO descriptors whose values will be assigned
4458 * @array_info: information on applicability of fast bitmap processing path
4459 * @value_bitmap: bitmap of values to assign
4461 * Set the raw values of the GPIOs, i.e. the values of the physical lines
4462 * without regard for their ACTIVE_LOW status.
4464 * This function is to be called from contexts that can sleep.
4466 int gpiod_set_raw_array_value_cansleep(unsigned int array_size,
4467 struct gpio_desc **desc_array,
4468 struct gpio_array *array_info,
4469 unsigned long *value_bitmap)
4471 might_sleep_if(extra_checks);
4472 if (!desc_array)
4473 return -EINVAL;
4474 return gpiod_set_array_value_complex(true, true, array_size, desc_array,
4475 array_info, value_bitmap);
4477 EXPORT_SYMBOL_GPL(gpiod_set_raw_array_value_cansleep);
4480 * gpiod_add_lookup_tables() - register GPIO device consumers
4481 * @tables: list of tables of consumers to register
4482 * @n: number of tables in the list
4484 void gpiod_add_lookup_tables(struct gpiod_lookup_table **tables, size_t n)
4486 unsigned int i;
4488 mutex_lock(&gpio_lookup_lock);
4490 for (i = 0; i < n; i++)
4491 list_add_tail(&tables[i]->list, &gpio_lookup_list);
4493 mutex_unlock(&gpio_lookup_lock);
4497 * gpiod_set_array_value_cansleep() - assign values to an array of GPIOs
4498 * @array_size: number of elements in the descriptor array / value bitmap
4499 * @desc_array: array of GPIO descriptors whose values will be assigned
4500 * @array_info: information on applicability of fast bitmap processing path
4501 * @value_bitmap: bitmap of values to assign
4503 * Set the logical values of the GPIOs, i.e. taking their ACTIVE_LOW status
4504 * into account.
4506 * This function is to be called from contexts that can sleep.
4508 int gpiod_set_array_value_cansleep(unsigned int array_size,
4509 struct gpio_desc **desc_array,
4510 struct gpio_array *array_info,
4511 unsigned long *value_bitmap)
4513 might_sleep_if(extra_checks);
4514 if (!desc_array)
4515 return -EINVAL;
4516 return gpiod_set_array_value_complex(false, true, array_size,
4517 desc_array, array_info,
4518 value_bitmap);
4520 EXPORT_SYMBOL_GPL(gpiod_set_array_value_cansleep);
4523 * gpiod_add_lookup_table() - register GPIO device consumers
4524 * @table: table of consumers to register
4526 void gpiod_add_lookup_table(struct gpiod_lookup_table *table)
4528 mutex_lock(&gpio_lookup_lock);
4530 list_add_tail(&table->list, &gpio_lookup_list);
4532 mutex_unlock(&gpio_lookup_lock);
4534 EXPORT_SYMBOL_GPL(gpiod_add_lookup_table);
4537 * gpiod_remove_lookup_table() - unregister GPIO device consumers
4538 * @table: table of consumers to unregister
4540 void gpiod_remove_lookup_table(struct gpiod_lookup_table *table)
4542 mutex_lock(&gpio_lookup_lock);
4544 list_del(&table->list);
4546 mutex_unlock(&gpio_lookup_lock);
4548 EXPORT_SYMBOL_GPL(gpiod_remove_lookup_table);
4551 * gpiod_add_hogs() - register a set of GPIO hogs from machine code
4552 * @hogs: table of gpio hog entries with a zeroed sentinel at the end
4554 void gpiod_add_hogs(struct gpiod_hog *hogs)
4556 struct gpio_chip *chip;
4557 struct gpiod_hog *hog;
4559 mutex_lock(&gpio_machine_hogs_mutex);
4561 for (hog = &hogs[0]; hog->chip_label; hog++) {
4562 list_add_tail(&hog->list, &gpio_machine_hogs);
4565 * The chip may have been registered earlier, so check if it
4566 * exists and, if so, try to hog the line now.
4568 chip = find_chip_by_name(hog->chip_label);
4569 if (chip)
4570 gpiochip_machine_hog(chip, hog);
4573 mutex_unlock(&gpio_machine_hogs_mutex);
4575 EXPORT_SYMBOL_GPL(gpiod_add_hogs);
4577 static struct gpiod_lookup_table *gpiod_find_lookup_table(struct device *dev)
4579 const char *dev_id = dev ? dev_name(dev) : NULL;
4580 struct gpiod_lookup_table *table;
4582 mutex_lock(&gpio_lookup_lock);
4584 list_for_each_entry(table, &gpio_lookup_list, list) {
4585 if (table->dev_id && dev_id) {
4587 * Valid strings on both ends, must be identical to have
4588 * a match
4590 if (!strcmp(table->dev_id, dev_id))
4591 goto found;
4592 } else {
4594 * One of the pointers is NULL, so both must be to have
4595 * a match
4597 if (dev_id == table->dev_id)
4598 goto found;
4601 table = NULL;
4603 found:
4604 mutex_unlock(&gpio_lookup_lock);
4605 return table;
4608 static struct gpio_desc *gpiod_find(struct device *dev, const char *con_id,
4609 unsigned int idx, unsigned long *flags)
4611 struct gpio_desc *desc = ERR_PTR(-ENOENT);
4612 struct gpiod_lookup_table *table;
4613 struct gpiod_lookup *p;
4615 table = gpiod_find_lookup_table(dev);
4616 if (!table)
4617 return desc;
4619 for (p = &table->table[0]; p->chip_label; p++) {
4620 struct gpio_chip *chip;
4622 /* idx must always match exactly */
4623 if (p->idx != idx)
4624 continue;
4626 /* If the lookup entry has a con_id, require exact match */
4627 if (p->con_id && (!con_id || strcmp(p->con_id, con_id)))
4628 continue;
4630 chip = find_chip_by_name(p->chip_label);
4632 if (!chip) {
4634 * As the lookup table indicates a chip with
4635 * p->chip_label should exist, assume it may
4636 * still appear later and let the interested
4637 * consumer be probed again or let the Deferred
4638 * Probe infrastructure handle the error.
4640 dev_warn(dev, "cannot find GPIO chip %s, deferring\n",
4641 p->chip_label);
4642 return ERR_PTR(-EPROBE_DEFER);
4645 if (chip->ngpio <= p->chip_hwnum) {
4646 dev_err(dev,
4647 "requested GPIO %u (%u) is out of range [0..%u] for chip %s\n",
4648 idx, p->chip_hwnum, chip->ngpio - 1,
4649 chip->label);
4650 return ERR_PTR(-EINVAL);
4653 desc = gpiochip_get_desc(chip, p->chip_hwnum);
4654 *flags = p->flags;
4656 return desc;
4659 return desc;
4662 static int platform_gpio_count(struct device *dev, const char *con_id)
4664 struct gpiod_lookup_table *table;
4665 struct gpiod_lookup *p;
4666 unsigned int count = 0;
4668 table = gpiod_find_lookup_table(dev);
4669 if (!table)
4670 return -ENOENT;
4672 for (p = &table->table[0]; p->chip_label; p++) {
4673 if ((con_id && p->con_id && !strcmp(con_id, p->con_id)) ||
4674 (!con_id && !p->con_id))
4675 count++;
4677 if (!count)
4678 return -ENOENT;
4680 return count;
4684 * fwnode_gpiod_get_index - obtain a GPIO from firmware node
4685 * @fwnode: handle of the firmware node
4686 * @con_id: function within the GPIO consumer
4687 * @index: index of the GPIO to obtain for the consumer
4688 * @flags: GPIO initialization flags
4689 * @label: label to attach to the requested GPIO
4691 * This function can be used for drivers that get their configuration
4692 * from opaque firmware.
4694 * The function properly finds the corresponding GPIO using whatever is the
4695 * underlying firmware interface and then makes sure that the GPIO
4696 * descriptor is requested before it is returned to the caller.
4698 * Returns:
4699 * On successful request the GPIO pin is configured in accordance with
4700 * provided @flags.
4702 * In case of error an ERR_PTR() is returned.
4704 struct gpio_desc *fwnode_gpiod_get_index(struct fwnode_handle *fwnode,
4705 const char *con_id, int index,
4706 enum gpiod_flags flags,
4707 const char *label)
4709 struct gpio_desc *desc;
4710 char prop_name[32]; /* 32 is max size of property name */
4711 unsigned int i;
4713 for (i = 0; i < ARRAY_SIZE(gpio_suffixes); i++) {
4714 if (con_id)
4715 snprintf(prop_name, sizeof(prop_name), "%s-%s",
4716 con_id, gpio_suffixes[i]);
4717 else
4718 snprintf(prop_name, sizeof(prop_name), "%s",
4719 gpio_suffixes[i]);
4721 desc = fwnode_get_named_gpiod(fwnode, prop_name, index, flags,
4722 label);
4723 if (!IS_ERR(desc) || (PTR_ERR(desc) != -ENOENT))
4724 break;
4727 return desc;
4729 EXPORT_SYMBOL_GPL(fwnode_gpiod_get_index);
4732 * gpiod_count - return the number of GPIOs associated with a device / function
4733 * or -ENOENT if no GPIO has been assigned to the requested function
4734 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4735 * @con_id: function within the GPIO consumer
4737 int gpiod_count(struct device *dev, const char *con_id)
4739 int count = -ENOENT;
4741 if (IS_ENABLED(CONFIG_OF) && dev && dev->of_node)
4742 count = of_gpio_get_count(dev, con_id);
4743 else if (IS_ENABLED(CONFIG_ACPI) && dev && ACPI_HANDLE(dev))
4744 count = acpi_gpio_count(dev, con_id);
4746 if (count < 0)
4747 count = platform_gpio_count(dev, con_id);
4749 return count;
4751 EXPORT_SYMBOL_GPL(gpiod_count);
4754 * gpiod_get - obtain a GPIO for a given GPIO function
4755 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4756 * @con_id: function within the GPIO consumer
4757 * @flags: optional GPIO initialization flags
4759 * Return the GPIO descriptor corresponding to the function con_id of device
4760 * dev, -ENOENT if no GPIO has been assigned to the requested function, or
4761 * another IS_ERR() code if an error occurred while trying to acquire the GPIO.
4763 struct gpio_desc *__must_check gpiod_get(struct device *dev, const char *con_id,
4764 enum gpiod_flags flags)
4766 return gpiod_get_index(dev, con_id, 0, flags);
4768 EXPORT_SYMBOL_GPL(gpiod_get);
4771 * gpiod_get_optional - obtain an optional GPIO for a given GPIO function
4772 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4773 * @con_id: function within the GPIO consumer
4774 * @flags: optional GPIO initialization flags
4776 * This is equivalent to gpiod_get(), except that when no GPIO was assigned to
4777 * the requested function it will return NULL. This is convenient for drivers
4778 * that need to handle optional GPIOs.
4780 struct gpio_desc *__must_check gpiod_get_optional(struct device *dev,
4781 const char *con_id,
4782 enum gpiod_flags flags)
4784 return gpiod_get_index_optional(dev, con_id, 0, flags);
4786 EXPORT_SYMBOL_GPL(gpiod_get_optional);
4790 * gpiod_configure_flags - helper function to configure a given GPIO
4791 * @desc: gpio whose value will be assigned
4792 * @con_id: function within the GPIO consumer
4793 * @lflags: bitmask of gpio_lookup_flags GPIO_* values - returned from
4794 * of_find_gpio() or of_get_gpio_hog()
4795 * @dflags: gpiod_flags - optional GPIO initialization flags
4797 * Return 0 on success, -ENOENT if no GPIO has been assigned to the
4798 * requested function and/or index, or another IS_ERR() code if an error
4799 * occurred while trying to acquire the GPIO.
4801 int gpiod_configure_flags(struct gpio_desc *desc, const char *con_id,
4802 unsigned long lflags, enum gpiod_flags dflags)
4804 int ret;
4806 if (lflags & GPIO_ACTIVE_LOW)
4807 set_bit(FLAG_ACTIVE_LOW, &desc->flags);
4809 if (lflags & GPIO_OPEN_DRAIN)
4810 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
4811 else if (dflags & GPIOD_FLAGS_BIT_OPEN_DRAIN) {
4813 * This enforces open drain mode from the consumer side.
4814 * This is necessary for some busses like I2C, but the lookup
4815 * should *REALLY* have specified them as open drain in the
4816 * first place, so print a little warning here.
4818 set_bit(FLAG_OPEN_DRAIN, &desc->flags);
4819 gpiod_warn(desc,
4820 "enforced open drain please flag it properly in DT/ACPI DSDT/board file\n");
4823 if (lflags & GPIO_OPEN_SOURCE)
4824 set_bit(FLAG_OPEN_SOURCE, &desc->flags);
4826 if ((lflags & GPIO_PULL_UP) && (lflags & GPIO_PULL_DOWN)) {
4827 gpiod_err(desc,
4828 "both pull-up and pull-down enabled, invalid configuration\n");
4829 return -EINVAL;
4832 if (lflags & GPIO_PULL_UP)
4833 set_bit(FLAG_PULL_UP, &desc->flags);
4834 else if (lflags & GPIO_PULL_DOWN)
4835 set_bit(FLAG_PULL_DOWN, &desc->flags);
4837 ret = gpiod_set_transitory(desc, (lflags & GPIO_TRANSITORY));
4838 if (ret < 0)
4839 return ret;
4841 /* No particular flag request, return here... */
4842 if (!(dflags & GPIOD_FLAGS_BIT_DIR_SET)) {
4843 pr_debug("no flags found for %s\n", con_id);
4844 return 0;
4847 /* Process flags */
4848 if (dflags & GPIOD_FLAGS_BIT_DIR_OUT)
4849 ret = gpiod_direction_output(desc,
4850 !!(dflags & GPIOD_FLAGS_BIT_DIR_VAL));
4851 else
4852 ret = gpiod_direction_input(desc);
4854 return ret;
4858 * gpiod_get_index - obtain a GPIO from a multi-index GPIO function
4859 * @dev: GPIO consumer, can be NULL for system-global GPIOs
4860 * @con_id: function within the GPIO consumer
4861 * @idx: index of the GPIO to obtain in the consumer
4862 * @flags: optional GPIO initialization flags
4864 * This variant of gpiod_get() allows to access GPIOs other than the first
4865 * defined one for functions that define several GPIOs.
4867 * Return a valid GPIO descriptor, -ENOENT if no GPIO has been assigned to the
4868 * requested function and/or index, or another IS_ERR() code if an error
4869 * occurred while trying to acquire the GPIO.
4871 struct gpio_desc *__must_check gpiod_get_index(struct device *dev,
4872 const char *con_id,
4873 unsigned int idx,
4874 enum gpiod_flags flags)
4876 unsigned long lookupflags = GPIO_LOOKUP_FLAGS_DEFAULT;
4877 struct gpio_desc *desc = NULL;
4878 int ret;
4879 /* Maybe we have a device name, maybe not */
4880 const char *devname = dev ? dev_name(dev) : "?";
4882 dev_dbg(dev, "GPIO lookup for consumer %s\n", con_id);
4884 if (dev) {
4885 /* Using device tree? */
4886 if (IS_ENABLED(CONFIG_OF) && dev->of_node) {
4887 dev_dbg(dev, "using device tree for GPIO lookup\n");
4888 desc = of_find_gpio(dev, con_id, idx, &lookupflags);
4889 } else if (ACPI_COMPANION(dev)) {
4890 dev_dbg(dev, "using ACPI for GPIO lookup\n");
4891 desc = acpi_find_gpio(dev, con_id, idx, &flags, &lookupflags);
4896 * Either we are not using DT or ACPI, or their lookup did not return
4897 * a result. In that case, use platform lookup as a fallback.
4899 if (!desc || desc == ERR_PTR(-ENOENT)) {
4900 dev_dbg(dev, "using lookup tables for GPIO lookup\n");
4901 desc = gpiod_find(dev, con_id, idx, &lookupflags);
4904 if (IS_ERR(desc)) {
4905 dev_dbg(dev, "No GPIO consumer %s found\n", con_id);
4906 return desc;
4910 * If a connection label was passed use that, else attempt to use
4911 * the device name as label
4913 ret = gpiod_request(desc, con_id ? con_id : devname);
4914 if (ret < 0) {
4915 if (ret == -EBUSY && flags & GPIOD_FLAGS_BIT_NONEXCLUSIVE) {
4917 * This happens when there are several consumers for
4918 * the same GPIO line: we just return here without
4919 * further initialization. It is a bit if a hack.
4920 * This is necessary to support fixed regulators.
4922 * FIXME: Make this more sane and safe.
4924 dev_info(dev, "nonexclusive access to GPIO for %s\n",
4925 con_id ? con_id : devname);
4926 return desc;
4927 } else {
4928 return ERR_PTR(ret);
4932 ret = gpiod_configure_flags(desc, con_id, lookupflags, flags);
4933 if (ret < 0) {
4934 dev_dbg(dev, "setup of GPIO %s failed\n", con_id);
4935 gpiod_put(desc);
4936 return ERR_PTR(ret);
4939 return desc;
4941 EXPORT_SYMBOL_GPL(gpiod_get_index);
4944 * fwnode_get_named_gpiod - obtain a GPIO from firmware node
4945 * @fwnode: handle of the firmware node
4946 * @propname: name of the firmware property representing the GPIO
4947 * @index: index of the GPIO to obtain for the consumer
4948 * @dflags: GPIO initialization flags
4949 * @label: label to attach to the requested GPIO
4951 * This function can be used for drivers that get their configuration
4952 * from opaque firmware.
4954 * The function properly finds the corresponding GPIO using whatever is the
4955 * underlying firmware interface and then makes sure that the GPIO
4956 * descriptor is requested before it is returned to the caller.
4958 * Returns:
4959 * On successful request the GPIO pin is configured in accordance with
4960 * provided @dflags.
4962 * In case of error an ERR_PTR() is returned.
4964 struct gpio_desc *fwnode_get_named_gpiod(struct fwnode_handle *fwnode,
4965 const char *propname, int index,
4966 enum gpiod_flags dflags,
4967 const char *label)
4969 unsigned long lflags = GPIO_LOOKUP_FLAGS_DEFAULT;
4970 struct gpio_desc *desc = ERR_PTR(-ENODEV);
4971 int ret;
4973 if (!fwnode)
4974 return ERR_PTR(-EINVAL);
4976 if (is_of_node(fwnode)) {
4977 desc = gpiod_get_from_of_node(to_of_node(fwnode),
4978 propname, index,
4979 dflags,
4980 label);
4981 return desc;
4982 } else if (is_acpi_node(fwnode)) {
4983 struct acpi_gpio_info info;
4985 desc = acpi_node_get_gpiod(fwnode, propname, index, &info);
4986 if (IS_ERR(desc))
4987 return desc;
4989 acpi_gpio_update_gpiod_flags(&dflags, &info);
4990 acpi_gpio_update_gpiod_lookup_flags(&lflags, &info);
4993 /* Currently only ACPI takes this path */
4994 ret = gpiod_request(desc, label);
4995 if (ret)
4996 return ERR_PTR(ret);
4998 ret = gpiod_configure_flags(desc, propname, lflags, dflags);
4999 if (ret < 0) {
5000 gpiod_put(desc);
5001 return ERR_PTR(ret);
5004 return desc;
5006 EXPORT_SYMBOL_GPL(fwnode_get_named_gpiod);
5009 * gpiod_get_index_optional - obtain an optional GPIO from a multi-index GPIO
5010 * function
5011 * @dev: GPIO consumer, can be NULL for system-global GPIOs
5012 * @con_id: function within the GPIO consumer
5013 * @index: index of the GPIO to obtain in the consumer
5014 * @flags: optional GPIO initialization flags
5016 * This is equivalent to gpiod_get_index(), except that when no GPIO with the
5017 * specified index was assigned to the requested function it will return NULL.
5018 * This is convenient for drivers that need to handle optional GPIOs.
5020 struct gpio_desc *__must_check gpiod_get_index_optional(struct device *dev,
5021 const char *con_id,
5022 unsigned int index,
5023 enum gpiod_flags flags)
5025 struct gpio_desc *desc;
5027 desc = gpiod_get_index(dev, con_id, index, flags);
5028 if (IS_ERR(desc)) {
5029 if (PTR_ERR(desc) == -ENOENT)
5030 return NULL;
5033 return desc;
5035 EXPORT_SYMBOL_GPL(gpiod_get_index_optional);
5038 * gpiod_hog - Hog the specified GPIO desc given the provided flags
5039 * @desc: gpio whose value will be assigned
5040 * @name: gpio line name
5041 * @lflags: bitmask of gpio_lookup_flags GPIO_* values - returned from
5042 * of_find_gpio() or of_get_gpio_hog()
5043 * @dflags: gpiod_flags - optional GPIO initialization flags
5045 int gpiod_hog(struct gpio_desc *desc, const char *name,
5046 unsigned long lflags, enum gpiod_flags dflags)
5048 struct gpio_chip *chip;
5049 struct gpio_desc *local_desc;
5050 int hwnum;
5051 int ret;
5053 chip = gpiod_to_chip(desc);
5054 hwnum = gpio_chip_hwgpio(desc);
5056 local_desc = gpiochip_request_own_desc(chip, hwnum, name,
5057 lflags, dflags);
5058 if (IS_ERR(local_desc)) {
5059 ret = PTR_ERR(local_desc);
5060 pr_err("requesting hog GPIO %s (chip %s, offset %d) failed, %d\n",
5061 name, chip->label, hwnum, ret);
5062 return ret;
5065 /* Mark GPIO as hogged so it can be identified and removed later */
5066 set_bit(FLAG_IS_HOGGED, &desc->flags);
5068 pr_info("GPIO line %d (%s) hogged as %s%s\n",
5069 desc_to_gpio(desc), name,
5070 (dflags & GPIOD_FLAGS_BIT_DIR_OUT) ? "output" : "input",
5071 (dflags & GPIOD_FLAGS_BIT_DIR_OUT) ?
5072 (dflags & GPIOD_FLAGS_BIT_DIR_VAL) ? "/high" : "/low" : "");
5074 return 0;
5078 * gpiochip_free_hogs - Scan gpio-controller chip and release GPIO hog
5079 * @chip: gpio chip to act on
5081 static void gpiochip_free_hogs(struct gpio_chip *chip)
5083 int id;
5085 for (id = 0; id < chip->ngpio; id++) {
5086 if (test_bit(FLAG_IS_HOGGED, &chip->gpiodev->descs[id].flags))
5087 gpiochip_free_own_desc(&chip->gpiodev->descs[id]);
5092 * gpiod_get_array - obtain multiple GPIOs from a multi-index GPIO function
5093 * @dev: GPIO consumer, can be NULL for system-global GPIOs
5094 * @con_id: function within the GPIO consumer
5095 * @flags: optional GPIO initialization flags
5097 * This function acquires all the GPIOs defined under a given function.
5099 * Return a struct gpio_descs containing an array of descriptors, -ENOENT if
5100 * no GPIO has been assigned to the requested function, or another IS_ERR()
5101 * code if an error occurred while trying to acquire the GPIOs.
5103 struct gpio_descs *__must_check gpiod_get_array(struct device *dev,
5104 const char *con_id,
5105 enum gpiod_flags flags)
5107 struct gpio_desc *desc;
5108 struct gpio_descs *descs;
5109 struct gpio_array *array_info = NULL;
5110 struct gpio_chip *chip;
5111 int count, bitmap_size;
5113 count = gpiod_count(dev, con_id);
5114 if (count < 0)
5115 return ERR_PTR(count);
5117 descs = kzalloc(struct_size(descs, desc, count), GFP_KERNEL);
5118 if (!descs)
5119 return ERR_PTR(-ENOMEM);
5121 for (descs->ndescs = 0; descs->ndescs < count; ) {
5122 desc = gpiod_get_index(dev, con_id, descs->ndescs, flags);
5123 if (IS_ERR(desc)) {
5124 gpiod_put_array(descs);
5125 return ERR_CAST(desc);
5128 descs->desc[descs->ndescs] = desc;
5130 chip = gpiod_to_chip(desc);
5132 * If pin hardware number of array member 0 is also 0, select
5133 * its chip as a candidate for fast bitmap processing path.
5135 if (descs->ndescs == 0 && gpio_chip_hwgpio(desc) == 0) {
5136 struct gpio_descs *array;
5138 bitmap_size = BITS_TO_LONGS(chip->ngpio > count ?
5139 chip->ngpio : count);
5141 array = kzalloc(struct_size(descs, desc, count) +
5142 struct_size(array_info, invert_mask,
5143 3 * bitmap_size), GFP_KERNEL);
5144 if (!array) {
5145 gpiod_put_array(descs);
5146 return ERR_PTR(-ENOMEM);
5149 memcpy(array, descs,
5150 struct_size(descs, desc, descs->ndescs + 1));
5151 kfree(descs);
5153 descs = array;
5154 array_info = (void *)(descs->desc + count);
5155 array_info->get_mask = array_info->invert_mask +
5156 bitmap_size;
5157 array_info->set_mask = array_info->get_mask +
5158 bitmap_size;
5160 array_info->desc = descs->desc;
5161 array_info->size = count;
5162 array_info->chip = chip;
5163 bitmap_set(array_info->get_mask, descs->ndescs,
5164 count - descs->ndescs);
5165 bitmap_set(array_info->set_mask, descs->ndescs,
5166 count - descs->ndescs);
5167 descs->info = array_info;
5169 /* Unmark array members which don't belong to the 'fast' chip */
5170 if (array_info && array_info->chip != chip) {
5171 __clear_bit(descs->ndescs, array_info->get_mask);
5172 __clear_bit(descs->ndescs, array_info->set_mask);
5175 * Detect array members which belong to the 'fast' chip
5176 * but their pins are not in hardware order.
5178 else if (array_info &&
5179 gpio_chip_hwgpio(desc) != descs->ndescs) {
5181 * Don't use fast path if all array members processed so
5182 * far belong to the same chip as this one but its pin
5183 * hardware number is different from its array index.
5185 if (bitmap_full(array_info->get_mask, descs->ndescs)) {
5186 array_info = NULL;
5187 } else {
5188 __clear_bit(descs->ndescs,
5189 array_info->get_mask);
5190 __clear_bit(descs->ndescs,
5191 array_info->set_mask);
5193 } else if (array_info) {
5194 /* Exclude open drain or open source from fast output */
5195 if (gpiochip_line_is_open_drain(chip, descs->ndescs) ||
5196 gpiochip_line_is_open_source(chip, descs->ndescs))
5197 __clear_bit(descs->ndescs,
5198 array_info->set_mask);
5199 /* Identify 'fast' pins which require invertion */
5200 if (gpiod_is_active_low(desc))
5201 __set_bit(descs->ndescs,
5202 array_info->invert_mask);
5205 descs->ndescs++;
5207 if (array_info)
5208 dev_dbg(dev,
5209 "GPIO array info: chip=%s, size=%d, get_mask=%lx, set_mask=%lx, invert_mask=%lx\n",
5210 array_info->chip->label, array_info->size,
5211 *array_info->get_mask, *array_info->set_mask,
5212 *array_info->invert_mask);
5213 return descs;
5215 EXPORT_SYMBOL_GPL(gpiod_get_array);
5218 * gpiod_get_array_optional - obtain multiple GPIOs from a multi-index GPIO
5219 * function
5220 * @dev: GPIO consumer, can be NULL for system-global GPIOs
5221 * @con_id: function within the GPIO consumer
5222 * @flags: optional GPIO initialization flags
5224 * This is equivalent to gpiod_get_array(), except that when no GPIO was
5225 * assigned to the requested function it will return NULL.
5227 struct gpio_descs *__must_check gpiod_get_array_optional(struct device *dev,
5228 const char *con_id,
5229 enum gpiod_flags flags)
5231 struct gpio_descs *descs;
5233 descs = gpiod_get_array(dev, con_id, flags);
5234 if (PTR_ERR(descs) == -ENOENT)
5235 return NULL;
5237 return descs;
5239 EXPORT_SYMBOL_GPL(gpiod_get_array_optional);
5242 * gpiod_put - dispose of a GPIO descriptor
5243 * @desc: GPIO descriptor to dispose of
5245 * No descriptor can be used after gpiod_put() has been called on it.
5247 void gpiod_put(struct gpio_desc *desc)
5249 if (desc)
5250 gpiod_free(desc);
5252 EXPORT_SYMBOL_GPL(gpiod_put);
5255 * gpiod_put_array - dispose of multiple GPIO descriptors
5256 * @descs: struct gpio_descs containing an array of descriptors
5258 void gpiod_put_array(struct gpio_descs *descs)
5260 unsigned int i;
5262 for (i = 0; i < descs->ndescs; i++)
5263 gpiod_put(descs->desc[i]);
5265 kfree(descs);
5267 EXPORT_SYMBOL_GPL(gpiod_put_array);
5269 static int __init gpiolib_dev_init(void)
5271 int ret;
5273 /* Register GPIO sysfs bus */
5274 ret = bus_register(&gpio_bus_type);
5275 if (ret < 0) {
5276 pr_err("gpiolib: could not register GPIO bus type\n");
5277 return ret;
5280 ret = alloc_chrdev_region(&gpio_devt, 0, GPIO_DEV_MAX, GPIOCHIP_NAME);
5281 if (ret < 0) {
5282 pr_err("gpiolib: failed to allocate char dev region\n");
5283 bus_unregister(&gpio_bus_type);
5284 return ret;
5287 gpiolib_initialized = true;
5288 gpiochip_setup_devs();
5290 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
5291 WARN_ON(of_reconfig_notifier_register(&gpio_of_notifier));
5293 return ret;
5295 core_initcall(gpiolib_dev_init);
5297 #ifdef CONFIG_DEBUG_FS
5299 static void gpiolib_dbg_show(struct seq_file *s, struct gpio_device *gdev)
5301 unsigned i;
5302 struct gpio_chip *chip = gdev->chip;
5303 unsigned gpio = gdev->base;
5304 struct gpio_desc *gdesc = &gdev->descs[0];
5305 bool is_out;
5306 bool is_irq;
5307 bool active_low;
5309 for (i = 0; i < gdev->ngpio; i++, gpio++, gdesc++) {
5310 if (!test_bit(FLAG_REQUESTED, &gdesc->flags)) {
5311 if (gdesc->name) {
5312 seq_printf(s, " gpio-%-3d (%-20.20s)\n",
5313 gpio, gdesc->name);
5315 continue;
5318 gpiod_get_direction(gdesc);
5319 is_out = test_bit(FLAG_IS_OUT, &gdesc->flags);
5320 is_irq = test_bit(FLAG_USED_AS_IRQ, &gdesc->flags);
5321 active_low = test_bit(FLAG_ACTIVE_LOW, &gdesc->flags);
5322 seq_printf(s, " gpio-%-3d (%-20.20s|%-20.20s) %s %s %s%s",
5323 gpio, gdesc->name ? gdesc->name : "", gdesc->label,
5324 is_out ? "out" : "in ",
5325 chip->get ? (chip->get(chip, i) ? "hi" : "lo") : "? ",
5326 is_irq ? "IRQ " : "",
5327 active_low ? "ACTIVE LOW" : "");
5328 seq_printf(s, "\n");
5332 static void *gpiolib_seq_start(struct seq_file *s, loff_t *pos)
5334 unsigned long flags;
5335 struct gpio_device *gdev = NULL;
5336 loff_t index = *pos;
5338 s->private = "";
5340 spin_lock_irqsave(&gpio_lock, flags);
5341 list_for_each_entry(gdev, &gpio_devices, list)
5342 if (index-- == 0) {
5343 spin_unlock_irqrestore(&gpio_lock, flags);
5344 return gdev;
5346 spin_unlock_irqrestore(&gpio_lock, flags);
5348 return NULL;
5351 static void *gpiolib_seq_next(struct seq_file *s, void *v, loff_t *pos)
5353 unsigned long flags;
5354 struct gpio_device *gdev = v;
5355 void *ret = NULL;
5357 spin_lock_irqsave(&gpio_lock, flags);
5358 if (list_is_last(&gdev->list, &gpio_devices))
5359 ret = NULL;
5360 else
5361 ret = list_entry(gdev->list.next, struct gpio_device, list);
5362 spin_unlock_irqrestore(&gpio_lock, flags);
5364 s->private = "\n";
5365 ++*pos;
5367 return ret;
5370 static void gpiolib_seq_stop(struct seq_file *s, void *v)
5374 static int gpiolib_seq_show(struct seq_file *s, void *v)
5376 struct gpio_device *gdev = v;
5377 struct gpio_chip *chip = gdev->chip;
5378 struct device *parent;
5380 if (!chip) {
5381 seq_printf(s, "%s%s: (dangling chip)", (char *)s->private,
5382 dev_name(&gdev->dev));
5383 return 0;
5386 seq_printf(s, "%s%s: GPIOs %d-%d", (char *)s->private,
5387 dev_name(&gdev->dev),
5388 gdev->base, gdev->base + gdev->ngpio - 1);
5389 parent = chip->parent;
5390 if (parent)
5391 seq_printf(s, ", parent: %s/%s",
5392 parent->bus ? parent->bus->name : "no-bus",
5393 dev_name(parent));
5394 if (chip->label)
5395 seq_printf(s, ", %s", chip->label);
5396 if (chip->can_sleep)
5397 seq_printf(s, ", can sleep");
5398 seq_printf(s, ":\n");
5400 if (chip->dbg_show)
5401 chip->dbg_show(s, chip);
5402 else
5403 gpiolib_dbg_show(s, gdev);
5405 return 0;
5408 static const struct seq_operations gpiolib_seq_ops = {
5409 .start = gpiolib_seq_start,
5410 .next = gpiolib_seq_next,
5411 .stop = gpiolib_seq_stop,
5412 .show = gpiolib_seq_show,
5415 static int gpiolib_open(struct inode *inode, struct file *file)
5417 return seq_open(file, &gpiolib_seq_ops);
5420 static const struct file_operations gpiolib_operations = {
5421 .owner = THIS_MODULE,
5422 .open = gpiolib_open,
5423 .read = seq_read,
5424 .llseek = seq_lseek,
5425 .release = seq_release,
5428 static int __init gpiolib_debugfs_init(void)
5430 /* /sys/kernel/debug/gpio */
5431 debugfs_create_file("gpio", S_IFREG | S_IRUGO, NULL, NULL,
5432 &gpiolib_operations);
5433 return 0;
5435 subsys_initcall(gpiolib_debugfs_init);
5437 #endif /* DEBUG_FS */