1 // SPDX-License-Identifier: GPL-2.0
3 #include <linux/anon_inodes.h>
4 #include <linux/atomic.h>
5 #include <linux/bitmap.h>
6 #include <linux/build_bug.h>
7 #include <linux/cdev.h>
8 #include <linux/compat.h>
9 #include <linux/compiler.h>
10 #include <linux/device.h>
11 #include <linux/err.h>
12 #include <linux/file.h>
13 #include <linux/gpio.h>
14 #include <linux/gpio/driver.h>
15 #include <linux/interrupt.h>
16 #include <linux/irqreturn.h>
17 #include <linux/kernel.h>
18 #include <linux/kfifo.h>
19 #include <linux/module.h>
20 #include <linux/mutex.h>
21 #include <linux/pinctrl/consumer.h>
22 #include <linux/poll.h>
23 #include <linux/spinlock.h>
24 #include <linux/timekeeping.h>
25 #include <linux/uaccess.h>
26 #include <linux/workqueue.h>
27 #include <uapi/linux/gpio.h>
30 #include "gpiolib-cdev.h"
33 * Array sizes must ensure 64-bit alignment and not create holes in the
36 static_assert(IS_ALIGNED(GPIO_V2_LINES_MAX, 2));
37 static_assert(IS_ALIGNED(GPIO_MAX_NAME_SIZE, 8));
40 * Check that uAPI structs are 64-bit aligned for 32/64-bit compatibility
42 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_attribute), 8));
43 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_config_attribute), 8));
44 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_config), 8));
45 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_request), 8));
46 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_info), 8));
47 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_info_changed), 8));
48 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_event), 8));
49 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_values), 8));
51 /* Character device interface to GPIO.
53 * The GPIO character device, /dev/gpiochipN, provides userspace an
54 * interface to gpiolib GPIOs via ioctl()s.
58 * GPIO line handle management
61 #ifdef CONFIG_GPIO_CDEV_V1
63 * struct linehandle_state - contains the state of a userspace handle
64 * @gdev: the GPIO device the handle pertains to
65 * @label: consumer label used to tag descriptors
66 * @descs: the GPIO descriptors held by this handle
67 * @num_descs: the number of descriptors held in the descs array
69 struct linehandle_state {
70 struct gpio_device *gdev;
72 struct gpio_desc *descs[GPIOHANDLES_MAX];
76 #define GPIOHANDLE_REQUEST_VALID_FLAGS \
77 (GPIOHANDLE_REQUEST_INPUT | \
78 GPIOHANDLE_REQUEST_OUTPUT | \
79 GPIOHANDLE_REQUEST_ACTIVE_LOW | \
80 GPIOHANDLE_REQUEST_BIAS_PULL_UP | \
81 GPIOHANDLE_REQUEST_BIAS_PULL_DOWN | \
82 GPIOHANDLE_REQUEST_BIAS_DISABLE | \
83 GPIOHANDLE_REQUEST_OPEN_DRAIN | \
84 GPIOHANDLE_REQUEST_OPEN_SOURCE)
86 static int linehandle_validate_flags(u32 flags)
88 /* Return an error if an unknown flag is set */
89 if (flags & ~GPIOHANDLE_REQUEST_VALID_FLAGS)
93 * Do not allow both INPUT & OUTPUT flags to be set as they are
96 if ((flags & GPIOHANDLE_REQUEST_INPUT) &&
97 (flags & GPIOHANDLE_REQUEST_OUTPUT))
101 * Do not allow OPEN_SOURCE & OPEN_DRAIN flags in a single request. If
102 * the hardware actually supports enabling both at the same time the
103 * electrical result would be disastrous.
105 if ((flags & GPIOHANDLE_REQUEST_OPEN_DRAIN) &&
106 (flags & GPIOHANDLE_REQUEST_OPEN_SOURCE))
109 /* OPEN_DRAIN and OPEN_SOURCE flags only make sense for output mode. */
110 if (!(flags & GPIOHANDLE_REQUEST_OUTPUT) &&
111 ((flags & GPIOHANDLE_REQUEST_OPEN_DRAIN) ||
112 (flags & GPIOHANDLE_REQUEST_OPEN_SOURCE)))
115 /* Bias flags only allowed for input or output mode. */
116 if (!((flags & GPIOHANDLE_REQUEST_INPUT) ||
117 (flags & GPIOHANDLE_REQUEST_OUTPUT)) &&
118 ((flags & GPIOHANDLE_REQUEST_BIAS_DISABLE) ||
119 (flags & GPIOHANDLE_REQUEST_BIAS_PULL_UP) ||
120 (flags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN)))
123 /* Only one bias flag can be set. */
124 if (((flags & GPIOHANDLE_REQUEST_BIAS_DISABLE) &&
125 (flags & (GPIOHANDLE_REQUEST_BIAS_PULL_DOWN |
126 GPIOHANDLE_REQUEST_BIAS_PULL_UP))) ||
127 ((flags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN) &&
128 (flags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)))
134 static void linehandle_flags_to_desc_flags(u32 lflags, unsigned long *flagsp)
136 assign_bit(FLAG_ACTIVE_LOW, flagsp,
137 lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW);
138 assign_bit(FLAG_OPEN_DRAIN, flagsp,
139 lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN);
140 assign_bit(FLAG_OPEN_SOURCE, flagsp,
141 lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE);
142 assign_bit(FLAG_PULL_UP, flagsp,
143 lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP);
144 assign_bit(FLAG_PULL_DOWN, flagsp,
145 lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN);
146 assign_bit(FLAG_BIAS_DISABLE, flagsp,
147 lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE);
150 static long linehandle_set_config(struct linehandle_state *lh,
153 struct gpiohandle_config gcnf;
154 struct gpio_desc *desc;
158 if (copy_from_user(&gcnf, ip, sizeof(gcnf)))
162 ret = linehandle_validate_flags(lflags);
166 for (i = 0; i < lh->num_descs; i++) {
168 linehandle_flags_to_desc_flags(gcnf.flags, &desc->flags);
171 * Lines have to be requested explicitly for input
172 * or output, else the line will be treated "as is".
174 if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
175 int val = !!gcnf.default_values[i];
177 ret = gpiod_direction_output(desc, val);
180 } else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
181 ret = gpiod_direction_input(desc);
186 blocking_notifier_call_chain(&desc->gdev->notifier,
187 GPIO_V2_LINE_CHANGED_CONFIG,
193 static long linehandle_ioctl(struct file *file, unsigned int cmd,
196 struct linehandle_state *lh = file->private_data;
197 void __user *ip = (void __user *)arg;
198 struct gpiohandle_data ghd;
199 DECLARE_BITMAP(vals, GPIOHANDLES_MAX);
207 case GPIOHANDLE_GET_LINE_VALUES_IOCTL:
208 /* NOTE: It's okay to read values of output lines */
209 ret = gpiod_get_array_value_complex(false, true,
210 lh->num_descs, lh->descs,
215 memset(&ghd, 0, sizeof(ghd));
216 for (i = 0; i < lh->num_descs; i++)
217 ghd.values[i] = test_bit(i, vals);
219 if (copy_to_user(ip, &ghd, sizeof(ghd)))
223 case GPIOHANDLE_SET_LINE_VALUES_IOCTL:
225 * All line descriptors were created at once with the same
226 * flags so just check if the first one is really output.
228 if (!test_bit(FLAG_IS_OUT, &lh->descs[0]->flags))
231 if (copy_from_user(&ghd, ip, sizeof(ghd)))
234 /* Clamp all values to [0,1] */
235 for (i = 0; i < lh->num_descs; i++)
236 __assign_bit(i, vals, ghd.values[i]);
238 /* Reuse the array setting function */
239 return gpiod_set_array_value_complex(false,
245 case GPIOHANDLE_SET_CONFIG_IOCTL:
246 return linehandle_set_config(lh, ip);
253 static long linehandle_ioctl_compat(struct file *file, unsigned int cmd,
256 return linehandle_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
260 static void linehandle_free(struct linehandle_state *lh)
264 for (i = 0; i < lh->num_descs; i++)
266 gpiod_free(lh->descs[i]);
268 put_device(&lh->gdev->dev);
272 static int linehandle_release(struct inode *inode, struct file *file)
274 linehandle_free(file->private_data);
278 static const struct file_operations linehandle_fileops = {
279 .release = linehandle_release,
280 .owner = THIS_MODULE,
281 .llseek = noop_llseek,
282 .unlocked_ioctl = linehandle_ioctl,
284 .compat_ioctl = linehandle_ioctl_compat,
288 static int linehandle_create(struct gpio_device *gdev, void __user *ip)
290 struct gpiohandle_request handlereq;
291 struct linehandle_state *lh;
296 if (copy_from_user(&handlereq, ip, sizeof(handlereq)))
298 if ((handlereq.lines == 0) || (handlereq.lines > GPIOHANDLES_MAX))
301 lflags = handlereq.flags;
303 ret = linehandle_validate_flags(lflags);
307 lh = kzalloc(sizeof(*lh), GFP_KERNEL);
311 get_device(&gdev->dev);
313 if (handlereq.consumer_label[0] != '\0') {
314 /* label is only initialized if consumer_label is set */
315 lh->label = kstrndup(handlereq.consumer_label,
316 sizeof(handlereq.consumer_label) - 1,
324 lh->num_descs = handlereq.lines;
326 /* Request each GPIO */
327 for (i = 0; i < handlereq.lines; i++) {
328 u32 offset = handlereq.lineoffsets[i];
329 struct gpio_desc *desc = gpiochip_get_desc(gdev->chip, offset);
336 ret = gpiod_request(desc, lh->label);
340 linehandle_flags_to_desc_flags(handlereq.flags, &desc->flags);
342 ret = gpiod_set_transitory(desc, false);
347 * Lines have to be requested explicitly for input
348 * or output, else the line will be treated "as is".
350 if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
351 int val = !!handlereq.default_values[i];
353 ret = gpiod_direction_output(desc, val);
356 } else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
357 ret = gpiod_direction_input(desc);
362 blocking_notifier_call_chain(&desc->gdev->notifier,
363 GPIO_V2_LINE_CHANGED_REQUESTED, desc);
365 dev_dbg(&gdev->dev, "registered chardev handle for line %d\n",
369 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
375 file = anon_inode_getfile("gpio-linehandle",
378 O_RDONLY | O_CLOEXEC);
381 goto out_put_unused_fd;
385 if (copy_to_user(ip, &handlereq, sizeof(handlereq))) {
387 * fput() will trigger the release() callback, so do not go onto
388 * the regular error cleanup path here.
395 fd_install(fd, file);
397 dev_dbg(&gdev->dev, "registered chardev handle for %d lines\n",
408 #endif /* CONFIG_GPIO_CDEV_V1 */
411 * struct line - contains the state of a requested line
412 * @desc: the GPIO descriptor for this line.
413 * @req: the corresponding line request
414 * @irq: the interrupt triggered in response to events on this GPIO
415 * @eflags: the edge flags, GPIO_V2_LINE_FLAG_EDGE_RISING and/or
416 * GPIO_V2_LINE_FLAG_EDGE_FALLING, indicating the edge detection applied
417 * @timestamp_ns: cache for the timestamp storing it between hardirq and
418 * IRQ thread, used to bring the timestamp close to the actual event
419 * @req_seqno: the seqno for the current edge event in the sequence of
420 * events for the corresponding line request. This is drawn from the @req.
421 * @line_seqno: the seqno for the current edge event in the sequence of
422 * events for this line.
423 * @work: the worker that implements software debouncing
424 * @sw_debounced: flag indicating if the software debouncer is active
425 * @level: the current debounced physical level of the line
428 struct gpio_desc *desc;
430 * -- edge detector specific fields --
436 * timestamp_ns and req_seqno are accessed only by
437 * edge_irq_handler() and edge_irq_thread(), which are themselves
438 * mutually exclusive, so no additional protection is necessary.
443 * line_seqno is accessed by either edge_irq_thread() or
444 * debounce_work_func(), which are themselves mutually exclusive,
445 * so no additional protection is necessary.
449 * -- debouncer specific fields --
451 struct delayed_work work;
453 * sw_debounce is accessed by linereq_set_config(), which is the
454 * only setter, and linereq_get_values(), which can live with a
455 * slightly stale value.
457 unsigned int sw_debounced;
459 * level is accessed by debounce_work_func(), which is the only
460 * setter, and linereq_get_values() which can live with a slightly
467 * struct linereq - contains the state of a userspace line request
468 * @gdev: the GPIO device the line request pertains to
469 * @label: consumer label used to tag GPIO descriptors
470 * @num_lines: the number of lines in the lines array
471 * @wait: wait queue that handles blocking reads of events
472 * @event_buffer_size: the number of elements allocated in @events
473 * @events: KFIFO for the GPIO events
474 * @seqno: the sequence number for edge events generated on all lines in
475 * this line request. Note that this is not used when @num_lines is 1, as
476 * the line_seqno is then the same and is cheaper to calculate.
477 * @config_mutex: mutex for serializing ioctl() calls to ensure consistency
478 * of configuration, particularly multi-step accesses to desc flags.
479 * @lines: the lines held by this line request, with @num_lines elements.
482 struct gpio_device *gdev;
485 wait_queue_head_t wait;
486 u32 event_buffer_size;
487 DECLARE_KFIFO_PTR(events, struct gpio_v2_line_event);
489 struct mutex config_mutex;
493 #define GPIO_V2_LINE_BIAS_FLAGS \
494 (GPIO_V2_LINE_FLAG_BIAS_PULL_UP | \
495 GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN | \
496 GPIO_V2_LINE_FLAG_BIAS_DISABLED)
498 #define GPIO_V2_LINE_DIRECTION_FLAGS \
499 (GPIO_V2_LINE_FLAG_INPUT | \
500 GPIO_V2_LINE_FLAG_OUTPUT)
502 #define GPIO_V2_LINE_DRIVE_FLAGS \
503 (GPIO_V2_LINE_FLAG_OPEN_DRAIN | \
504 GPIO_V2_LINE_FLAG_OPEN_SOURCE)
506 #define GPIO_V2_LINE_EDGE_FLAGS \
507 (GPIO_V2_LINE_FLAG_EDGE_RISING | \
508 GPIO_V2_LINE_FLAG_EDGE_FALLING)
510 #define GPIO_V2_LINE_VALID_FLAGS \
511 (GPIO_V2_LINE_FLAG_ACTIVE_LOW | \
512 GPIO_V2_LINE_DIRECTION_FLAGS | \
513 GPIO_V2_LINE_DRIVE_FLAGS | \
514 GPIO_V2_LINE_EDGE_FLAGS | \
515 GPIO_V2_LINE_BIAS_FLAGS)
517 static void linereq_put_event(struct linereq *lr,
518 struct gpio_v2_line_event *le)
520 bool overflow = false;
522 spin_lock(&lr->wait.lock);
523 if (kfifo_is_full(&lr->events)) {
525 kfifo_skip(&lr->events);
527 kfifo_in(&lr->events, le, 1);
528 spin_unlock(&lr->wait.lock);
530 wake_up_poll(&lr->wait, EPOLLIN);
532 pr_debug_ratelimited("event FIFO is full - event dropped\n");
535 static irqreturn_t edge_irq_thread(int irq, void *p)
537 struct line *line = p;
538 struct linereq *lr = line->req;
539 struct gpio_v2_line_event le;
541 /* Do not leak kernel stack to userspace */
542 memset(&le, 0, sizeof(le));
544 if (line->timestamp_ns) {
545 le.timestamp_ns = line->timestamp_ns;
548 * We may be running from a nested threaded interrupt in
549 * which case we didn't get the timestamp from
550 * edge_irq_handler().
552 le.timestamp_ns = ktime_get_ns();
553 if (lr->num_lines != 1)
554 line->req_seqno = atomic_inc_return(&lr->seqno);
556 line->timestamp_ns = 0;
558 if (line->eflags == (GPIO_V2_LINE_FLAG_EDGE_RISING |
559 GPIO_V2_LINE_FLAG_EDGE_FALLING)) {
560 int level = gpiod_get_value_cansleep(line->desc);
563 /* Emit low-to-high event */
564 le.id = GPIO_V2_LINE_EVENT_RISING_EDGE;
566 /* Emit high-to-low event */
567 le.id = GPIO_V2_LINE_EVENT_FALLING_EDGE;
568 } else if (line->eflags == GPIO_V2_LINE_FLAG_EDGE_RISING) {
569 /* Emit low-to-high event */
570 le.id = GPIO_V2_LINE_EVENT_RISING_EDGE;
571 } else if (line->eflags == GPIO_V2_LINE_FLAG_EDGE_FALLING) {
572 /* Emit high-to-low event */
573 le.id = GPIO_V2_LINE_EVENT_FALLING_EDGE;
578 le.line_seqno = line->line_seqno;
579 le.seqno = (lr->num_lines == 1) ? le.line_seqno : line->req_seqno;
580 le.offset = gpio_chip_hwgpio(line->desc);
582 linereq_put_event(lr, &le);
587 static irqreturn_t edge_irq_handler(int irq, void *p)
589 struct line *line = p;
590 struct linereq *lr = line->req;
593 * Just store the timestamp in hardirq context so we get it as
594 * close in time as possible to the actual event.
596 line->timestamp_ns = ktime_get_ns();
598 if (lr->num_lines != 1)
599 line->req_seqno = atomic_inc_return(&lr->seqno);
601 return IRQ_WAKE_THREAD;
605 * returns the current debounced logical value.
607 static bool debounced_value(struct line *line)
612 * minor race - debouncer may be stopped here, so edge_detector_stop()
613 * must leave the value unchanged so the following will read the level
614 * from when the debouncer was last running.
616 value = READ_ONCE(line->level);
618 if (test_bit(FLAG_ACTIVE_LOW, &line->desc->flags))
624 static irqreturn_t debounce_irq_handler(int irq, void *p)
626 struct line *line = p;
628 mod_delayed_work(system_wq, &line->work,
629 usecs_to_jiffies(READ_ONCE(line->desc->debounce_period_us)));
634 static void debounce_work_func(struct work_struct *work)
636 struct gpio_v2_line_event le;
637 struct line *line = container_of(work, struct line, work.work);
641 level = gpiod_get_raw_value_cansleep(line->desc);
643 pr_debug_ratelimited("debouncer failed to read line value\n");
647 if (READ_ONCE(line->level) == level)
650 WRITE_ONCE(line->level, level);
652 /* -- edge detection -- */
656 /* switch from physical level to logical - if they differ */
657 if (test_bit(FLAG_ACTIVE_LOW, &line->desc->flags))
660 /* ignore edges that are not being monitored */
661 if (((line->eflags == GPIO_V2_LINE_FLAG_EDGE_RISING) && !level) ||
662 ((line->eflags == GPIO_V2_LINE_FLAG_EDGE_FALLING) && level))
665 /* Do not leak kernel stack to userspace */
666 memset(&le, 0, sizeof(le));
669 le.timestamp_ns = ktime_get_ns();
670 le.offset = gpio_chip_hwgpio(line->desc);
672 le.line_seqno = line->line_seqno;
673 le.seqno = (lr->num_lines == 1) ?
674 le.line_seqno : atomic_inc_return(&lr->seqno);
677 /* Emit low-to-high event */
678 le.id = GPIO_V2_LINE_EVENT_RISING_EDGE;
680 /* Emit high-to-low event */
681 le.id = GPIO_V2_LINE_EVENT_FALLING_EDGE;
683 linereq_put_event(lr, &le);
686 static int debounce_setup(struct line *line,
687 unsigned int debounce_period_us)
689 unsigned long irqflags;
693 ret = gpiod_set_debounce(line->desc, debounce_period_us);
695 WRITE_ONCE(line->desc->debounce_period_us, debounce_period_us);
698 if (ret != -ENOTSUPP)
701 if (debounce_period_us) {
702 /* setup software debounce */
703 level = gpiod_get_raw_value_cansleep(line->desc);
707 irq = gpiod_to_irq(line->desc);
711 WRITE_ONCE(line->level, level);
712 irqflags = IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING;
713 ret = request_irq(irq, debounce_irq_handler, irqflags,
714 line->req->label, line);
718 WRITE_ONCE(line->sw_debounced, 1);
724 static bool gpio_v2_line_config_debounced(struct gpio_v2_line_config *lc,
725 unsigned int line_idx)
728 u64 mask = BIT_ULL(line_idx);
730 for (i = 0; i < lc->num_attrs; i++) {
731 if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_DEBOUNCE) &&
732 (lc->attrs[i].mask & mask))
738 static u32 gpio_v2_line_config_debounce_period(struct gpio_v2_line_config *lc,
739 unsigned int line_idx)
742 u64 mask = BIT_ULL(line_idx);
744 for (i = 0; i < lc->num_attrs; i++) {
745 if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_DEBOUNCE) &&
746 (lc->attrs[i].mask & mask))
747 return lc->attrs[i].attr.debounce_period_us;
752 static void edge_detector_stop(struct line *line)
755 free_irq(line->irq, line);
759 cancel_delayed_work_sync(&line->work);
760 WRITE_ONCE(line->sw_debounced, 0);
763 WRITE_ONCE(line->desc->debounce_period_us, 0);
764 /* do not change line->level - see comment in debounced_value() */
767 static int edge_detector_setup(struct line *line,
768 struct gpio_v2_line_config *lc,
769 unsigned int line_idx,
772 u32 debounce_period_us;
773 unsigned long irqflags = 0;
776 if (eflags && !kfifo_initialized(&line->req->events)) {
777 ret = kfifo_alloc(&line->req->events,
778 line->req->event_buffer_size, GFP_KERNEL);
782 line->eflags = eflags;
783 if (gpio_v2_line_config_debounced(lc, line_idx)) {
784 debounce_period_us = gpio_v2_line_config_debounce_period(lc, line_idx);
785 ret = debounce_setup(line, debounce_period_us);
788 WRITE_ONCE(line->desc->debounce_period_us, debounce_period_us);
791 /* detection disabled or sw debouncer will provide edge detection */
792 if (!eflags || READ_ONCE(line->sw_debounced))
795 irq = gpiod_to_irq(line->desc);
799 if (eflags & GPIO_V2_LINE_FLAG_EDGE_RISING)
800 irqflags |= test_bit(FLAG_ACTIVE_LOW, &line->desc->flags) ?
801 IRQF_TRIGGER_FALLING : IRQF_TRIGGER_RISING;
802 if (eflags & GPIO_V2_LINE_FLAG_EDGE_FALLING)
803 irqflags |= test_bit(FLAG_ACTIVE_LOW, &line->desc->flags) ?
804 IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING;
805 irqflags |= IRQF_ONESHOT;
807 /* Request a thread to read the events */
808 ret = request_threaded_irq(irq, edge_irq_handler, edge_irq_thread,
809 irqflags, line->req->label, line);
817 static int edge_detector_update(struct line *line,
818 struct gpio_v2_line_config *lc,
819 unsigned int line_idx,
820 u64 eflags, bool polarity_change)
822 unsigned int debounce_period_us =
823 gpio_v2_line_config_debounce_period(lc, line_idx);
825 if ((line->eflags == eflags) && !polarity_change &&
826 (READ_ONCE(line->desc->debounce_period_us) == debounce_period_us))
829 /* sw debounced and still will be...*/
830 if (debounce_period_us && READ_ONCE(line->sw_debounced)) {
831 line->eflags = eflags;
832 WRITE_ONCE(line->desc->debounce_period_us, debounce_period_us);
836 /* reconfiguring edge detection or sw debounce being disabled */
837 if ((line->irq && !READ_ONCE(line->sw_debounced)) ||
838 (!debounce_period_us && READ_ONCE(line->sw_debounced)))
839 edge_detector_stop(line);
841 return edge_detector_setup(line, lc, line_idx, eflags);
844 static u64 gpio_v2_line_config_flags(struct gpio_v2_line_config *lc,
845 unsigned int line_idx)
848 u64 mask = BIT_ULL(line_idx);
850 for (i = 0; i < lc->num_attrs; i++) {
851 if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_FLAGS) &&
852 (lc->attrs[i].mask & mask))
853 return lc->attrs[i].attr.flags;
858 static int gpio_v2_line_config_output_value(struct gpio_v2_line_config *lc,
859 unsigned int line_idx)
862 u64 mask = BIT_ULL(line_idx);
864 for (i = 0; i < lc->num_attrs; i++) {
865 if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_OUTPUT_VALUES) &&
866 (lc->attrs[i].mask & mask))
867 return !!(lc->attrs[i].attr.values & mask);
872 static int gpio_v2_line_flags_validate(u64 flags)
874 /* Return an error if an unknown flag is set */
875 if (flags & ~GPIO_V2_LINE_VALID_FLAGS)
879 * Do not allow both INPUT and OUTPUT flags to be set as they are
882 if ((flags & GPIO_V2_LINE_FLAG_INPUT) &&
883 (flags & GPIO_V2_LINE_FLAG_OUTPUT))
886 /* Edge detection requires explicit input. */
887 if ((flags & GPIO_V2_LINE_EDGE_FLAGS) &&
888 !(flags & GPIO_V2_LINE_FLAG_INPUT))
892 * Do not allow OPEN_SOURCE and OPEN_DRAIN flags in a single
893 * request. If the hardware actually supports enabling both at the
894 * same time the electrical result would be disastrous.
896 if ((flags & GPIO_V2_LINE_FLAG_OPEN_DRAIN) &&
897 (flags & GPIO_V2_LINE_FLAG_OPEN_SOURCE))
900 /* Drive requires explicit output direction. */
901 if ((flags & GPIO_V2_LINE_DRIVE_FLAGS) &&
902 !(flags & GPIO_V2_LINE_FLAG_OUTPUT))
905 /* Bias requires explicit direction. */
906 if ((flags & GPIO_V2_LINE_BIAS_FLAGS) &&
907 !(flags & GPIO_V2_LINE_DIRECTION_FLAGS))
910 /* Only one bias flag can be set. */
911 if (((flags & GPIO_V2_LINE_FLAG_BIAS_DISABLED) &&
912 (flags & (GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN |
913 GPIO_V2_LINE_FLAG_BIAS_PULL_UP))) ||
914 ((flags & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN) &&
915 (flags & GPIO_V2_LINE_FLAG_BIAS_PULL_UP)))
921 static int gpio_v2_line_config_validate(struct gpio_v2_line_config *lc,
922 unsigned int num_lines)
928 if (lc->num_attrs > GPIO_V2_LINE_NUM_ATTRS_MAX)
931 if (memchr_inv(lc->padding, 0, sizeof(lc->padding)))
934 for (i = 0; i < num_lines; i++) {
935 flags = gpio_v2_line_config_flags(lc, i);
936 ret = gpio_v2_line_flags_validate(flags);
940 /* debounce requires explicit input */
941 if (gpio_v2_line_config_debounced(lc, i) &&
942 !(flags & GPIO_V2_LINE_FLAG_INPUT))
948 static void gpio_v2_line_config_flags_to_desc_flags(u64 flags,
949 unsigned long *flagsp)
951 assign_bit(FLAG_ACTIVE_LOW, flagsp,
952 flags & GPIO_V2_LINE_FLAG_ACTIVE_LOW);
954 if (flags & GPIO_V2_LINE_FLAG_OUTPUT)
955 set_bit(FLAG_IS_OUT, flagsp);
956 else if (flags & GPIO_V2_LINE_FLAG_INPUT)
957 clear_bit(FLAG_IS_OUT, flagsp);
959 assign_bit(FLAG_EDGE_RISING, flagsp,
960 flags & GPIO_V2_LINE_FLAG_EDGE_RISING);
961 assign_bit(FLAG_EDGE_FALLING, flagsp,
962 flags & GPIO_V2_LINE_FLAG_EDGE_FALLING);
964 assign_bit(FLAG_OPEN_DRAIN, flagsp,
965 flags & GPIO_V2_LINE_FLAG_OPEN_DRAIN);
966 assign_bit(FLAG_OPEN_SOURCE, flagsp,
967 flags & GPIO_V2_LINE_FLAG_OPEN_SOURCE);
969 assign_bit(FLAG_PULL_UP, flagsp,
970 flags & GPIO_V2_LINE_FLAG_BIAS_PULL_UP);
971 assign_bit(FLAG_PULL_DOWN, flagsp,
972 flags & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN);
973 assign_bit(FLAG_BIAS_DISABLE, flagsp,
974 flags & GPIO_V2_LINE_FLAG_BIAS_DISABLED);
977 static long linereq_get_values(struct linereq *lr, void __user *ip)
979 struct gpio_v2_line_values lv;
980 DECLARE_BITMAP(vals, GPIO_V2_LINES_MAX);
981 struct gpio_desc **descs;
982 unsigned int i, didx, num_get;
986 /* NOTE: It's ok to read values of output lines. */
987 if (copy_from_user(&lv, ip, sizeof(lv)))
990 for (num_get = 0, i = 0; i < lr->num_lines; i++) {
991 if (lv.mask & BIT_ULL(i)) {
993 descs = &lr->lines[i].desc;
1001 descs = kmalloc_array(num_get, sizeof(*descs), GFP_KERNEL);
1004 for (didx = 0, i = 0; i < lr->num_lines; i++) {
1005 if (lv.mask & BIT_ULL(i)) {
1006 descs[didx] = lr->lines[i].desc;
1011 ret = gpiod_get_array_value_complex(false, true, num_get,
1020 for (didx = 0, i = 0; i < lr->num_lines; i++) {
1021 if (lv.mask & BIT_ULL(i)) {
1022 if (lr->lines[i].sw_debounced)
1023 val = debounced_value(&lr->lines[i]);
1025 val = test_bit(didx, vals);
1027 lv.bits |= BIT_ULL(i);
1032 if (copy_to_user(ip, &lv, sizeof(lv)))
1038 static long linereq_set_values_unlocked(struct linereq *lr,
1039 struct gpio_v2_line_values *lv)
1041 DECLARE_BITMAP(vals, GPIO_V2_LINES_MAX);
1042 struct gpio_desc **descs;
1043 unsigned int i, didx, num_set;
1046 bitmap_zero(vals, GPIO_V2_LINES_MAX);
1047 for (num_set = 0, i = 0; i < lr->num_lines; i++) {
1048 if (lv->mask & BIT_ULL(i)) {
1049 if (!test_bit(FLAG_IS_OUT, &lr->lines[i].desc->flags))
1051 if (lv->bits & BIT_ULL(i))
1052 __set_bit(num_set, vals);
1054 descs = &lr->lines[i].desc;
1061 /* build compacted desc array and values */
1062 descs = kmalloc_array(num_set, sizeof(*descs), GFP_KERNEL);
1065 for (didx = 0, i = 0; i < lr->num_lines; i++) {
1066 if (lv->mask & BIT_ULL(i)) {
1067 descs[didx] = lr->lines[i].desc;
1072 ret = gpiod_set_array_value_complex(false, true, num_set,
1080 static long linereq_set_values(struct linereq *lr, void __user *ip)
1082 struct gpio_v2_line_values lv;
1085 if (copy_from_user(&lv, ip, sizeof(lv)))
1088 mutex_lock(&lr->config_mutex);
1090 ret = linereq_set_values_unlocked(lr, &lv);
1092 mutex_unlock(&lr->config_mutex);
1097 static long linereq_set_config_unlocked(struct linereq *lr,
1098 struct gpio_v2_line_config *lc)
1100 struct gpio_desc *desc;
1103 bool polarity_change;
1106 for (i = 0; i < lr->num_lines; i++) {
1107 desc = lr->lines[i].desc;
1108 flags = gpio_v2_line_config_flags(lc, i);
1110 (!!test_bit(FLAG_ACTIVE_LOW, &desc->flags) !=
1111 ((flags & GPIO_V2_LINE_FLAG_ACTIVE_LOW) != 0));
1113 gpio_v2_line_config_flags_to_desc_flags(flags, &desc->flags);
1115 * Lines have to be requested explicitly for input
1116 * or output, else the line will be treated "as is".
1118 if (flags & GPIO_V2_LINE_FLAG_OUTPUT) {
1119 int val = gpio_v2_line_config_output_value(lc, i);
1121 edge_detector_stop(&lr->lines[i]);
1122 ret = gpiod_direction_output(desc, val);
1125 } else if (flags & GPIO_V2_LINE_FLAG_INPUT) {
1126 ret = gpiod_direction_input(desc);
1130 ret = edge_detector_update(&lr->lines[i], lc, i,
1131 flags & GPIO_V2_LINE_EDGE_FLAGS,
1137 blocking_notifier_call_chain(&desc->gdev->notifier,
1138 GPIO_V2_LINE_CHANGED_CONFIG,
1144 static long linereq_set_config(struct linereq *lr, void __user *ip)
1146 struct gpio_v2_line_config lc;
1149 if (copy_from_user(&lc, ip, sizeof(lc)))
1152 ret = gpio_v2_line_config_validate(&lc, lr->num_lines);
1156 mutex_lock(&lr->config_mutex);
1158 ret = linereq_set_config_unlocked(lr, &lc);
1160 mutex_unlock(&lr->config_mutex);
1165 static long linereq_ioctl(struct file *file, unsigned int cmd,
1168 struct linereq *lr = file->private_data;
1169 void __user *ip = (void __user *)arg;
1171 if (!lr->gdev->chip)
1175 case GPIO_V2_LINE_GET_VALUES_IOCTL:
1176 return linereq_get_values(lr, ip);
1177 case GPIO_V2_LINE_SET_VALUES_IOCTL:
1178 return linereq_set_values(lr, ip);
1179 case GPIO_V2_LINE_SET_CONFIG_IOCTL:
1180 return linereq_set_config(lr, ip);
1186 #ifdef CONFIG_COMPAT
1187 static long linereq_ioctl_compat(struct file *file, unsigned int cmd,
1190 return linereq_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
1194 static __poll_t linereq_poll(struct file *file,
1195 struct poll_table_struct *wait)
1197 struct linereq *lr = file->private_data;
1198 __poll_t events = 0;
1200 if (!lr->gdev->chip)
1201 return EPOLLHUP | EPOLLERR;
1203 poll_wait(file, &lr->wait, wait);
1205 if (!kfifo_is_empty_spinlocked_noirqsave(&lr->events,
1207 events = EPOLLIN | EPOLLRDNORM;
1212 static ssize_t linereq_read(struct file *file,
1217 struct linereq *lr = file->private_data;
1218 struct gpio_v2_line_event le;
1219 ssize_t bytes_read = 0;
1222 if (!lr->gdev->chip)
1225 if (count < sizeof(le))
1229 spin_lock(&lr->wait.lock);
1230 if (kfifo_is_empty(&lr->events)) {
1232 spin_unlock(&lr->wait.lock);
1236 if (file->f_flags & O_NONBLOCK) {
1237 spin_unlock(&lr->wait.lock);
1241 ret = wait_event_interruptible_locked(lr->wait,
1242 !kfifo_is_empty(&lr->events));
1244 spin_unlock(&lr->wait.lock);
1249 ret = kfifo_out(&lr->events, &le, 1);
1250 spin_unlock(&lr->wait.lock);
1253 * This should never happen - we were holding the
1254 * lock from the moment we learned the fifo is no
1255 * longer empty until now.
1261 if (copy_to_user(buf + bytes_read, &le, sizeof(le)))
1263 bytes_read += sizeof(le);
1264 } while (count >= bytes_read + sizeof(le));
1269 static void linereq_free(struct linereq *lr)
1273 for (i = 0; i < lr->num_lines; i++) {
1274 edge_detector_stop(&lr->lines[i]);
1275 if (lr->lines[i].desc)
1276 gpiod_free(lr->lines[i].desc);
1278 kfifo_free(&lr->events);
1280 put_device(&lr->gdev->dev);
1284 static int linereq_release(struct inode *inode, struct file *file)
1286 struct linereq *lr = file->private_data;
1292 static const struct file_operations line_fileops = {
1293 .release = linereq_release,
1294 .read = linereq_read,
1295 .poll = linereq_poll,
1296 .owner = THIS_MODULE,
1297 .llseek = noop_llseek,
1298 .unlocked_ioctl = linereq_ioctl,
1299 #ifdef CONFIG_COMPAT
1300 .compat_ioctl = linereq_ioctl_compat,
1304 static int linereq_create(struct gpio_device *gdev, void __user *ip)
1306 struct gpio_v2_line_request ulr;
1307 struct gpio_v2_line_config *lc;
1314 if (copy_from_user(&ulr, ip, sizeof(ulr)))
1317 if ((ulr.num_lines == 0) || (ulr.num_lines > GPIO_V2_LINES_MAX))
1320 if (memchr_inv(ulr.padding, 0, sizeof(ulr.padding)))
1324 ret = gpio_v2_line_config_validate(lc, ulr.num_lines);
1328 lr = kzalloc(struct_size(lr, lines, ulr.num_lines), GFP_KERNEL);
1333 get_device(&gdev->dev);
1335 for (i = 0; i < ulr.num_lines; i++) {
1336 lr->lines[i].req = lr;
1337 WRITE_ONCE(lr->lines[i].sw_debounced, 0);
1338 INIT_DELAYED_WORK(&lr->lines[i].work, debounce_work_func);
1341 if (ulr.consumer[0] != '\0') {
1342 /* label is only initialized if consumer is set */
1343 lr->label = kstrndup(ulr.consumer, sizeof(ulr.consumer) - 1,
1347 goto out_free_linereq;
1351 mutex_init(&lr->config_mutex);
1352 init_waitqueue_head(&lr->wait);
1353 lr->event_buffer_size = ulr.event_buffer_size;
1354 if (lr->event_buffer_size == 0)
1355 lr->event_buffer_size = ulr.num_lines * 16;
1356 else if (lr->event_buffer_size > GPIO_V2_LINES_MAX * 16)
1357 lr->event_buffer_size = GPIO_V2_LINES_MAX * 16;
1359 atomic_set(&lr->seqno, 0);
1360 lr->num_lines = ulr.num_lines;
1362 /* Request each GPIO */
1363 for (i = 0; i < ulr.num_lines; i++) {
1364 u32 offset = ulr.offsets[i];
1365 struct gpio_desc *desc = gpiochip_get_desc(gdev->chip, offset);
1368 ret = PTR_ERR(desc);
1369 goto out_free_linereq;
1372 ret = gpiod_request(desc, lr->label);
1374 goto out_free_linereq;
1376 lr->lines[i].desc = desc;
1377 flags = gpio_v2_line_config_flags(lc, i);
1378 gpio_v2_line_config_flags_to_desc_flags(flags, &desc->flags);
1380 ret = gpiod_set_transitory(desc, false);
1382 goto out_free_linereq;
1385 * Lines have to be requested explicitly for input
1386 * or output, else the line will be treated "as is".
1388 if (flags & GPIO_V2_LINE_FLAG_OUTPUT) {
1389 int val = gpio_v2_line_config_output_value(lc, i);
1391 ret = gpiod_direction_output(desc, val);
1393 goto out_free_linereq;
1394 } else if (flags & GPIO_V2_LINE_FLAG_INPUT) {
1395 ret = gpiod_direction_input(desc);
1397 goto out_free_linereq;
1399 ret = edge_detector_setup(&lr->lines[i], lc, i,
1400 flags & GPIO_V2_LINE_EDGE_FLAGS);
1402 goto out_free_linereq;
1405 blocking_notifier_call_chain(&desc->gdev->notifier,
1406 GPIO_V2_LINE_CHANGED_REQUESTED, desc);
1408 dev_dbg(&gdev->dev, "registered chardev handle for line %d\n",
1412 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
1415 goto out_free_linereq;
1418 file = anon_inode_getfile("gpio-line", &line_fileops, lr,
1419 O_RDONLY | O_CLOEXEC);
1421 ret = PTR_ERR(file);
1422 goto out_put_unused_fd;
1426 if (copy_to_user(ip, &ulr, sizeof(ulr))) {
1428 * fput() will trigger the release() callback, so do not go onto
1429 * the regular error cleanup path here.
1436 fd_install(fd, file);
1438 dev_dbg(&gdev->dev, "registered chardev handle for %d lines\n",
1450 #ifdef CONFIG_GPIO_CDEV_V1
1453 * GPIO line event management
1457 * struct lineevent_state - contains the state of a userspace event
1458 * @gdev: the GPIO device the event pertains to
1459 * @label: consumer label used to tag descriptors
1460 * @desc: the GPIO descriptor held by this event
1461 * @eflags: the event flags this line was requested with
1462 * @irq: the interrupt that trigger in response to events on this GPIO
1463 * @wait: wait queue that handles blocking reads of events
1464 * @events: KFIFO for the GPIO events
1465 * @timestamp: cache for the timestamp storing it between hardirq
1466 * and IRQ thread, used to bring the timestamp close to the actual
1469 struct lineevent_state {
1470 struct gpio_device *gdev;
1472 struct gpio_desc *desc;
1475 wait_queue_head_t wait;
1476 DECLARE_KFIFO(events, struct gpioevent_data, 16);
1480 #define GPIOEVENT_REQUEST_VALID_FLAGS \
1481 (GPIOEVENT_REQUEST_RISING_EDGE | \
1482 GPIOEVENT_REQUEST_FALLING_EDGE)
1484 static __poll_t lineevent_poll(struct file *file,
1485 struct poll_table_struct *wait)
1487 struct lineevent_state *le = file->private_data;
1488 __poll_t events = 0;
1490 if (!le->gdev->chip)
1491 return EPOLLHUP | EPOLLERR;
1493 poll_wait(file, &le->wait, wait);
1495 if (!kfifo_is_empty_spinlocked_noirqsave(&le->events, &le->wait.lock))
1496 events = EPOLLIN | EPOLLRDNORM;
1501 static ssize_t lineevent_get_size(void)
1503 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML)
1504 /* i386 has no padding after 'id' */
1505 if (in_ia32_syscall()) {
1506 struct compat_gpioeevent_data {
1507 compat_u64 timestamp;
1511 return sizeof(struct compat_gpioeevent_data);
1514 return sizeof(struct gpioevent_data);
1517 static ssize_t lineevent_read(struct file *file,
1522 struct lineevent_state *le = file->private_data;
1523 struct gpioevent_data ge;
1524 ssize_t bytes_read = 0;
1528 if (!le->gdev->chip)
1532 * When compatible system call is being used the struct gpioevent_data,
1533 * in case of at least ia32, has different size due to the alignment
1534 * differences. Because we have first member 64 bits followed by one of
1535 * 32 bits there is no gap between them. The only difference is the
1536 * padding at the end of the data structure. Hence, we calculate the
1537 * actual sizeof() and pass this as an argument to copy_to_user() to
1538 * drop unneeded bytes from the output.
1540 ge_size = lineevent_get_size();
1541 if (count < ge_size)
1545 spin_lock(&le->wait.lock);
1546 if (kfifo_is_empty(&le->events)) {
1548 spin_unlock(&le->wait.lock);
1552 if (file->f_flags & O_NONBLOCK) {
1553 spin_unlock(&le->wait.lock);
1557 ret = wait_event_interruptible_locked(le->wait,
1558 !kfifo_is_empty(&le->events));
1560 spin_unlock(&le->wait.lock);
1565 ret = kfifo_out(&le->events, &ge, 1);
1566 spin_unlock(&le->wait.lock);
1569 * This should never happen - we were holding the lock
1570 * from the moment we learned the fifo is no longer
1577 if (copy_to_user(buf + bytes_read, &ge, ge_size))
1579 bytes_read += ge_size;
1580 } while (count >= bytes_read + ge_size);
1585 static void lineevent_free(struct lineevent_state *le)
1588 free_irq(le->irq, le);
1590 gpiod_free(le->desc);
1592 put_device(&le->gdev->dev);
1596 static int lineevent_release(struct inode *inode, struct file *file)
1598 lineevent_free(file->private_data);
1602 static long lineevent_ioctl(struct file *file, unsigned int cmd,
1605 struct lineevent_state *le = file->private_data;
1606 void __user *ip = (void __user *)arg;
1607 struct gpiohandle_data ghd;
1609 if (!le->gdev->chip)
1613 * We can get the value for an event line but not set it,
1614 * because it is input by definition.
1616 if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
1619 memset(&ghd, 0, sizeof(ghd));
1621 val = gpiod_get_value_cansleep(le->desc);
1624 ghd.values[0] = val;
1626 if (copy_to_user(ip, &ghd, sizeof(ghd)))
1634 #ifdef CONFIG_COMPAT
1635 static long lineevent_ioctl_compat(struct file *file, unsigned int cmd,
1638 return lineevent_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
1642 static const struct file_operations lineevent_fileops = {
1643 .release = lineevent_release,
1644 .read = lineevent_read,
1645 .poll = lineevent_poll,
1646 .owner = THIS_MODULE,
1647 .llseek = noop_llseek,
1648 .unlocked_ioctl = lineevent_ioctl,
1649 #ifdef CONFIG_COMPAT
1650 .compat_ioctl = lineevent_ioctl_compat,
1654 static irqreturn_t lineevent_irq_thread(int irq, void *p)
1656 struct lineevent_state *le = p;
1657 struct gpioevent_data ge;
1660 /* Do not leak kernel stack to userspace */
1661 memset(&ge, 0, sizeof(ge));
1664 * We may be running from a nested threaded interrupt in which case
1665 * we didn't get the timestamp from lineevent_irq_handler().
1668 ge.timestamp = ktime_get_ns();
1670 ge.timestamp = le->timestamp;
1672 if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE
1673 && le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
1674 int level = gpiod_get_value_cansleep(le->desc);
1677 /* Emit low-to-high event */
1678 ge.id = GPIOEVENT_EVENT_RISING_EDGE;
1680 /* Emit high-to-low event */
1681 ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
1682 } else if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE) {
1683 /* Emit low-to-high event */
1684 ge.id = GPIOEVENT_EVENT_RISING_EDGE;
1685 } else if (le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
1686 /* Emit high-to-low event */
1687 ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
1692 ret = kfifo_in_spinlocked_noirqsave(&le->events, &ge,
1695 wake_up_poll(&le->wait, EPOLLIN);
1697 pr_debug_ratelimited("event FIFO is full - event dropped\n");
1702 static irqreturn_t lineevent_irq_handler(int irq, void *p)
1704 struct lineevent_state *le = p;
1707 * Just store the timestamp in hardirq context so we get it as
1708 * close in time as possible to the actual event.
1710 le->timestamp = ktime_get_ns();
1712 return IRQ_WAKE_THREAD;
1715 static int lineevent_create(struct gpio_device *gdev, void __user *ip)
1717 struct gpioevent_request eventreq;
1718 struct lineevent_state *le;
1719 struct gpio_desc *desc;
1726 int irq, irqflags = 0;
1728 if (copy_from_user(&eventreq, ip, sizeof(eventreq)))
1731 offset = eventreq.lineoffset;
1732 lflags = eventreq.handleflags;
1733 eflags = eventreq.eventflags;
1735 desc = gpiochip_get_desc(gdev->chip, offset);
1737 return PTR_ERR(desc);
1739 /* Return an error if a unknown flag is set */
1740 if ((lflags & ~GPIOHANDLE_REQUEST_VALID_FLAGS) ||
1741 (eflags & ~GPIOEVENT_REQUEST_VALID_FLAGS))
1744 /* This is just wrong: we don't look for events on output lines */
1745 if ((lflags & GPIOHANDLE_REQUEST_OUTPUT) ||
1746 (lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN) ||
1747 (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE))
1750 /* Only one bias flag can be set. */
1751 if (((lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE) &&
1752 (lflags & (GPIOHANDLE_REQUEST_BIAS_PULL_DOWN |
1753 GPIOHANDLE_REQUEST_BIAS_PULL_UP))) ||
1754 ((lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN) &&
1755 (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)))
1758 le = kzalloc(sizeof(*le), GFP_KERNEL);
1762 get_device(&gdev->dev);
1764 if (eventreq.consumer_label[0] != '\0') {
1765 /* label is only initialized if consumer_label is set */
1766 le->label = kstrndup(eventreq.consumer_label,
1767 sizeof(eventreq.consumer_label) - 1,
1775 ret = gpiod_request(desc, le->label);
1779 le->eflags = eflags;
1781 linehandle_flags_to_desc_flags(lflags, &desc->flags);
1783 ret = gpiod_direction_input(desc);
1787 blocking_notifier_call_chain(&desc->gdev->notifier,
1788 GPIO_V2_LINE_CHANGED_REQUESTED, desc);
1790 irq = gpiod_to_irq(desc);
1796 if (eflags & GPIOEVENT_REQUEST_RISING_EDGE)
1797 irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
1798 IRQF_TRIGGER_FALLING : IRQF_TRIGGER_RISING;
1799 if (eflags & GPIOEVENT_REQUEST_FALLING_EDGE)
1800 irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
1801 IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING;
1802 irqflags |= IRQF_ONESHOT;
1804 INIT_KFIFO(le->events);
1805 init_waitqueue_head(&le->wait);
1807 /* Request a thread to read the events */
1808 ret = request_threaded_irq(irq,
1809 lineevent_irq_handler,
1810 lineevent_irq_thread,
1819 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
1825 file = anon_inode_getfile("gpio-event",
1828 O_RDONLY | O_CLOEXEC);
1830 ret = PTR_ERR(file);
1831 goto out_put_unused_fd;
1835 if (copy_to_user(ip, &eventreq, sizeof(eventreq))) {
1837 * fput() will trigger the release() callback, so do not go onto
1838 * the regular error cleanup path here.
1845 fd_install(fd, file);
1856 static void gpio_v2_line_info_to_v1(struct gpio_v2_line_info *info_v2,
1857 struct gpioline_info *info_v1)
1859 u64 flagsv2 = info_v2->flags;
1861 memcpy(info_v1->name, info_v2->name, sizeof(info_v1->name));
1862 memcpy(info_v1->consumer, info_v2->consumer, sizeof(info_v1->consumer));
1863 info_v1->line_offset = info_v2->offset;
1866 if (flagsv2 & GPIO_V2_LINE_FLAG_USED)
1867 info_v1->flags |= GPIOLINE_FLAG_KERNEL;
1869 if (flagsv2 & GPIO_V2_LINE_FLAG_OUTPUT)
1870 info_v1->flags |= GPIOLINE_FLAG_IS_OUT;
1872 if (flagsv2 & GPIO_V2_LINE_FLAG_ACTIVE_LOW)
1873 info_v1->flags |= GPIOLINE_FLAG_ACTIVE_LOW;
1875 if (flagsv2 & GPIO_V2_LINE_FLAG_OPEN_DRAIN)
1876 info_v1->flags |= GPIOLINE_FLAG_OPEN_DRAIN;
1877 if (flagsv2 & GPIO_V2_LINE_FLAG_OPEN_SOURCE)
1878 info_v1->flags |= GPIOLINE_FLAG_OPEN_SOURCE;
1880 if (flagsv2 & GPIO_V2_LINE_FLAG_BIAS_PULL_UP)
1881 info_v1->flags |= GPIOLINE_FLAG_BIAS_PULL_UP;
1882 if (flagsv2 & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN)
1883 info_v1->flags |= GPIOLINE_FLAG_BIAS_PULL_DOWN;
1884 if (flagsv2 & GPIO_V2_LINE_FLAG_BIAS_DISABLED)
1885 info_v1->flags |= GPIOLINE_FLAG_BIAS_DISABLE;
1888 static void gpio_v2_line_info_changed_to_v1(
1889 struct gpio_v2_line_info_changed *lic_v2,
1890 struct gpioline_info_changed *lic_v1)
1892 memset(lic_v1, 0, sizeof(*lic_v1));
1893 gpio_v2_line_info_to_v1(&lic_v2->info, &lic_v1->info);
1894 lic_v1->timestamp = lic_v2->timestamp_ns;
1895 lic_v1->event_type = lic_v2->event_type;
1898 #endif /* CONFIG_GPIO_CDEV_V1 */
1900 static void gpio_desc_to_lineinfo(struct gpio_desc *desc,
1901 struct gpio_v2_line_info *info)
1903 struct gpio_chip *gc = desc->gdev->chip;
1904 bool ok_for_pinctrl;
1905 unsigned long flags;
1906 u32 debounce_period_us;
1907 unsigned int num_attrs = 0;
1909 memset(info, 0, sizeof(*info));
1910 info->offset = gpio_chip_hwgpio(desc);
1913 * This function takes a mutex so we must check this before taking
1916 * FIXME: find a non-racy way to retrieve this information. Maybe a
1917 * lock common to both frameworks?
1920 pinctrl_gpio_can_use_line(gc->base + info->offset);
1922 spin_lock_irqsave(&gpio_lock, flags);
1925 strscpy(info->name, desc->name, sizeof(info->name));
1928 strscpy(info->consumer, desc->label, sizeof(info->consumer));
1931 * Userspace only need to know that the kernel is using this GPIO so
1935 if (test_bit(FLAG_REQUESTED, &desc->flags) ||
1936 test_bit(FLAG_IS_HOGGED, &desc->flags) ||
1937 test_bit(FLAG_USED_AS_IRQ, &desc->flags) ||
1938 test_bit(FLAG_EXPORT, &desc->flags) ||
1939 test_bit(FLAG_SYSFS, &desc->flags) ||
1941 info->flags |= GPIO_V2_LINE_FLAG_USED;
1943 if (test_bit(FLAG_IS_OUT, &desc->flags))
1944 info->flags |= GPIO_V2_LINE_FLAG_OUTPUT;
1946 info->flags |= GPIO_V2_LINE_FLAG_INPUT;
1948 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
1949 info->flags |= GPIO_V2_LINE_FLAG_ACTIVE_LOW;
1951 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
1952 info->flags |= GPIO_V2_LINE_FLAG_OPEN_DRAIN;
1953 if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
1954 info->flags |= GPIO_V2_LINE_FLAG_OPEN_SOURCE;
1956 if (test_bit(FLAG_BIAS_DISABLE, &desc->flags))
1957 info->flags |= GPIO_V2_LINE_FLAG_BIAS_DISABLED;
1958 if (test_bit(FLAG_PULL_DOWN, &desc->flags))
1959 info->flags |= GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN;
1960 if (test_bit(FLAG_PULL_UP, &desc->flags))
1961 info->flags |= GPIO_V2_LINE_FLAG_BIAS_PULL_UP;
1963 if (test_bit(FLAG_EDGE_RISING, &desc->flags))
1964 info->flags |= GPIO_V2_LINE_FLAG_EDGE_RISING;
1965 if (test_bit(FLAG_EDGE_FALLING, &desc->flags))
1966 info->flags |= GPIO_V2_LINE_FLAG_EDGE_FALLING;
1968 debounce_period_us = READ_ONCE(desc->debounce_period_us);
1969 if (debounce_period_us) {
1970 info->attrs[num_attrs].id = GPIO_V2_LINE_ATTR_ID_DEBOUNCE;
1971 info->attrs[num_attrs].debounce_period_us = debounce_period_us;
1974 info->num_attrs = num_attrs;
1976 spin_unlock_irqrestore(&gpio_lock, flags);
1979 struct gpio_chardev_data {
1980 struct gpio_device *gdev;
1981 wait_queue_head_t wait;
1982 DECLARE_KFIFO(events, struct gpio_v2_line_info_changed, 32);
1983 struct notifier_block lineinfo_changed_nb;
1984 unsigned long *watched_lines;
1985 #ifdef CONFIG_GPIO_CDEV_V1
1986 atomic_t watch_abi_version;
1990 static int chipinfo_get(struct gpio_chardev_data *cdev, void __user *ip)
1992 struct gpio_device *gdev = cdev->gdev;
1993 struct gpiochip_info chipinfo;
1995 memset(&chipinfo, 0, sizeof(chipinfo));
1997 strscpy(chipinfo.name, dev_name(&gdev->dev), sizeof(chipinfo.name));
1998 strscpy(chipinfo.label, gdev->label, sizeof(chipinfo.label));
1999 chipinfo.lines = gdev->ngpio;
2000 if (copy_to_user(ip, &chipinfo, sizeof(chipinfo)))
2005 #ifdef CONFIG_GPIO_CDEV_V1
2007 * returns 0 if the versions match, else the previously selected ABI version
2009 static int lineinfo_ensure_abi_version(struct gpio_chardev_data *cdata,
2010 unsigned int version)
2012 int abiv = atomic_cmpxchg(&cdata->watch_abi_version, 0, version);
2014 if (abiv == version)
2020 static int lineinfo_get_v1(struct gpio_chardev_data *cdev, void __user *ip,
2023 struct gpio_desc *desc;
2024 struct gpioline_info lineinfo;
2025 struct gpio_v2_line_info lineinfo_v2;
2027 if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
2030 /* this doubles as a range check on line_offset */
2031 desc = gpiochip_get_desc(cdev->gdev->chip, lineinfo.line_offset);
2033 return PTR_ERR(desc);
2036 if (lineinfo_ensure_abi_version(cdev, 1))
2039 if (test_and_set_bit(lineinfo.line_offset, cdev->watched_lines))
2043 gpio_desc_to_lineinfo(desc, &lineinfo_v2);
2044 gpio_v2_line_info_to_v1(&lineinfo_v2, &lineinfo);
2046 if (copy_to_user(ip, &lineinfo, sizeof(lineinfo))) {
2048 clear_bit(lineinfo.line_offset, cdev->watched_lines);
2056 static int lineinfo_get(struct gpio_chardev_data *cdev, void __user *ip,
2059 struct gpio_desc *desc;
2060 struct gpio_v2_line_info lineinfo;
2062 if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
2065 if (memchr_inv(lineinfo.padding, 0, sizeof(lineinfo.padding)))
2068 desc = gpiochip_get_desc(cdev->gdev->chip, lineinfo.offset);
2070 return PTR_ERR(desc);
2073 #ifdef CONFIG_GPIO_CDEV_V1
2074 if (lineinfo_ensure_abi_version(cdev, 2))
2077 if (test_and_set_bit(lineinfo.offset, cdev->watched_lines))
2080 gpio_desc_to_lineinfo(desc, &lineinfo);
2082 if (copy_to_user(ip, &lineinfo, sizeof(lineinfo))) {
2084 clear_bit(lineinfo.offset, cdev->watched_lines);
2091 static int lineinfo_unwatch(struct gpio_chardev_data *cdev, void __user *ip)
2095 if (copy_from_user(&offset, ip, sizeof(offset)))
2098 if (offset >= cdev->gdev->ngpio)
2101 if (!test_and_clear_bit(offset, cdev->watched_lines))
2108 * gpio_ioctl() - ioctl handler for the GPIO chardev
2110 static long gpio_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
2112 struct gpio_chardev_data *cdev = file->private_data;
2113 struct gpio_device *gdev = cdev->gdev;
2114 void __user *ip = (void __user *)arg;
2116 /* We fail any subsequent ioctl():s when the chip is gone */
2120 /* Fill in the struct and pass to userspace */
2122 case GPIO_GET_CHIPINFO_IOCTL:
2123 return chipinfo_get(cdev, ip);
2124 #ifdef CONFIG_GPIO_CDEV_V1
2125 case GPIO_GET_LINEHANDLE_IOCTL:
2126 return linehandle_create(gdev, ip);
2127 case GPIO_GET_LINEEVENT_IOCTL:
2128 return lineevent_create(gdev, ip);
2129 case GPIO_GET_LINEINFO_IOCTL:
2130 return lineinfo_get_v1(cdev, ip, false);
2131 case GPIO_GET_LINEINFO_WATCH_IOCTL:
2132 return lineinfo_get_v1(cdev, ip, true);
2133 #endif /* CONFIG_GPIO_CDEV_V1 */
2134 case GPIO_V2_GET_LINEINFO_IOCTL:
2135 return lineinfo_get(cdev, ip, false);
2136 case GPIO_V2_GET_LINEINFO_WATCH_IOCTL:
2137 return lineinfo_get(cdev, ip, true);
2138 case GPIO_V2_GET_LINE_IOCTL:
2139 return linereq_create(gdev, ip);
2140 case GPIO_GET_LINEINFO_UNWATCH_IOCTL:
2141 return lineinfo_unwatch(cdev, ip);
2147 #ifdef CONFIG_COMPAT
2148 static long gpio_ioctl_compat(struct file *file, unsigned int cmd,
2151 return gpio_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
2155 static struct gpio_chardev_data *
2156 to_gpio_chardev_data(struct notifier_block *nb)
2158 return container_of(nb, struct gpio_chardev_data, lineinfo_changed_nb);
2161 static int lineinfo_changed_notify(struct notifier_block *nb,
2162 unsigned long action, void *data)
2164 struct gpio_chardev_data *cdev = to_gpio_chardev_data(nb);
2165 struct gpio_v2_line_info_changed chg;
2166 struct gpio_desc *desc = data;
2169 if (!test_bit(gpio_chip_hwgpio(desc), cdev->watched_lines))
2172 memset(&chg, 0, sizeof(chg));
2173 chg.event_type = action;
2174 chg.timestamp_ns = ktime_get_ns();
2175 gpio_desc_to_lineinfo(desc, &chg.info);
2177 ret = kfifo_in_spinlocked(&cdev->events, &chg, 1, &cdev->wait.lock);
2179 wake_up_poll(&cdev->wait, EPOLLIN);
2181 pr_debug_ratelimited("lineinfo event FIFO is full - event dropped\n");
2186 static __poll_t lineinfo_watch_poll(struct file *file,
2187 struct poll_table_struct *pollt)
2189 struct gpio_chardev_data *cdev = file->private_data;
2190 __poll_t events = 0;
2192 if (!cdev->gdev->chip)
2193 return EPOLLHUP | EPOLLERR;
2195 poll_wait(file, &cdev->wait, pollt);
2197 if (!kfifo_is_empty_spinlocked_noirqsave(&cdev->events,
2199 events = EPOLLIN | EPOLLRDNORM;
2204 static ssize_t lineinfo_watch_read(struct file *file, char __user *buf,
2205 size_t count, loff_t *off)
2207 struct gpio_chardev_data *cdev = file->private_data;
2208 struct gpio_v2_line_info_changed event;
2209 ssize_t bytes_read = 0;
2213 if (!cdev->gdev->chip)
2216 #ifndef CONFIG_GPIO_CDEV_V1
2217 event_size = sizeof(struct gpio_v2_line_info_changed);
2218 if (count < event_size)
2223 spin_lock(&cdev->wait.lock);
2224 if (kfifo_is_empty(&cdev->events)) {
2226 spin_unlock(&cdev->wait.lock);
2230 if (file->f_flags & O_NONBLOCK) {
2231 spin_unlock(&cdev->wait.lock);
2235 ret = wait_event_interruptible_locked(cdev->wait,
2236 !kfifo_is_empty(&cdev->events));
2238 spin_unlock(&cdev->wait.lock);
2242 #ifdef CONFIG_GPIO_CDEV_V1
2243 /* must be after kfifo check so watch_abi_version is set */
2244 if (atomic_read(&cdev->watch_abi_version) == 2)
2245 event_size = sizeof(struct gpio_v2_line_info_changed);
2247 event_size = sizeof(struct gpioline_info_changed);
2248 if (count < event_size) {
2249 spin_unlock(&cdev->wait.lock);
2253 ret = kfifo_out(&cdev->events, &event, 1);
2254 spin_unlock(&cdev->wait.lock);
2258 /* We should never get here. See lineevent_read(). */
2261 #ifdef CONFIG_GPIO_CDEV_V1
2262 if (event_size == sizeof(struct gpio_v2_line_info_changed)) {
2263 if (copy_to_user(buf + bytes_read, &event, event_size))
2266 struct gpioline_info_changed event_v1;
2268 gpio_v2_line_info_changed_to_v1(&event, &event_v1);
2269 if (copy_to_user(buf + bytes_read, &event_v1,
2274 if (copy_to_user(buf + bytes_read, &event, event_size))
2277 bytes_read += event_size;
2278 } while (count >= bytes_read + sizeof(event));
2284 * gpio_chrdev_open() - open the chardev for ioctl operations
2285 * @inode: inode for this chardev
2286 * @file: file struct for storing private data
2287 * Returns 0 on success
2289 static int gpio_chrdev_open(struct inode *inode, struct file *file)
2291 struct gpio_device *gdev = container_of(inode->i_cdev,
2292 struct gpio_device, chrdev);
2293 struct gpio_chardev_data *cdev;
2296 /* Fail on open if the backing gpiochip is gone */
2300 cdev = kzalloc(sizeof(*cdev), GFP_KERNEL);
2304 cdev->watched_lines = bitmap_zalloc(gdev->chip->ngpio, GFP_KERNEL);
2305 if (!cdev->watched_lines)
2308 init_waitqueue_head(&cdev->wait);
2309 INIT_KFIFO(cdev->events);
2312 cdev->lineinfo_changed_nb.notifier_call = lineinfo_changed_notify;
2313 ret = blocking_notifier_chain_register(&gdev->notifier,
2314 &cdev->lineinfo_changed_nb);
2316 goto out_free_bitmap;
2318 get_device(&gdev->dev);
2319 file->private_data = cdev;
2321 ret = nonseekable_open(inode, file);
2323 goto out_unregister_notifier;
2327 out_unregister_notifier:
2328 blocking_notifier_chain_unregister(&gdev->notifier,
2329 &cdev->lineinfo_changed_nb);
2331 bitmap_free(cdev->watched_lines);
2338 * gpio_chrdev_release() - close chardev after ioctl operations
2339 * @inode: inode for this chardev
2340 * @file: file struct for storing private data
2341 * Returns 0 on success
2343 static int gpio_chrdev_release(struct inode *inode, struct file *file)
2345 struct gpio_chardev_data *cdev = file->private_data;
2346 struct gpio_device *gdev = cdev->gdev;
2348 bitmap_free(cdev->watched_lines);
2349 blocking_notifier_chain_unregister(&gdev->notifier,
2350 &cdev->lineinfo_changed_nb);
2351 put_device(&gdev->dev);
2357 static const struct file_operations gpio_fileops = {
2358 .release = gpio_chrdev_release,
2359 .open = gpio_chrdev_open,
2360 .poll = lineinfo_watch_poll,
2361 .read = lineinfo_watch_read,
2362 .owner = THIS_MODULE,
2363 .llseek = no_llseek,
2364 .unlocked_ioctl = gpio_ioctl,
2365 #ifdef CONFIG_COMPAT
2366 .compat_ioctl = gpio_ioctl_compat,
2370 int gpiolib_cdev_register(struct gpio_device *gdev, dev_t devt)
2374 cdev_init(&gdev->chrdev, &gpio_fileops);
2375 gdev->chrdev.owner = THIS_MODULE;
2376 gdev->dev.devt = MKDEV(MAJOR(devt), gdev->id);
2378 ret = cdev_device_add(&gdev->chrdev, &gdev->dev);
2382 chip_dbg(gdev->chip, "added GPIO chardev (%d:%d)\n",
2383 MAJOR(devt), gdev->id);
2388 void gpiolib_cdev_unregister(struct gpio_device *gdev)
2390 cdev_device_del(&gdev->chrdev, &gdev->dev);