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);
202 if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
203 /* NOTE: It's ok to read values of output lines. */
204 int ret = gpiod_get_array_value_complex(false,
213 memset(&ghd, 0, sizeof(ghd));
214 for (i = 0; i < lh->num_descs; i++)
215 ghd.values[i] = test_bit(i, vals);
217 if (copy_to_user(ip, &ghd, sizeof(ghd)))
221 } else if (cmd == GPIOHANDLE_SET_LINE_VALUES_IOCTL) {
223 * All line descriptors were created at once with the same
224 * flags so just check if the first one is really output.
226 if (!test_bit(FLAG_IS_OUT, &lh->descs[0]->flags))
229 if (copy_from_user(&ghd, ip, sizeof(ghd)))
232 /* Clamp all values to [0,1] */
233 for (i = 0; i < lh->num_descs; i++)
234 __assign_bit(i, vals, ghd.values[i]);
236 /* Reuse the array setting function */
237 return gpiod_set_array_value_complex(false,
243 } else if (cmd == GPIOHANDLE_SET_CONFIG_IOCTL) {
244 return linehandle_set_config(lh, ip);
250 static long linehandle_ioctl_compat(struct file *file, unsigned int cmd,
253 return linehandle_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
257 static void linehandle_free(struct linehandle_state *lh)
261 for (i = 0; i < lh->num_descs; i++)
263 gpiod_free(lh->descs[i]);
265 put_device(&lh->gdev->dev);
269 static int linehandle_release(struct inode *inode, struct file *file)
271 linehandle_free(file->private_data);
275 static const struct file_operations linehandle_fileops = {
276 .release = linehandle_release,
277 .owner = THIS_MODULE,
278 .llseek = noop_llseek,
279 .unlocked_ioctl = linehandle_ioctl,
281 .compat_ioctl = linehandle_ioctl_compat,
285 static int linehandle_create(struct gpio_device *gdev, void __user *ip)
287 struct gpiohandle_request handlereq;
288 struct linehandle_state *lh;
293 if (copy_from_user(&handlereq, ip, sizeof(handlereq)))
295 if ((handlereq.lines == 0) || (handlereq.lines > GPIOHANDLES_MAX))
298 lflags = handlereq.flags;
300 ret = linehandle_validate_flags(lflags);
304 lh = kzalloc(sizeof(*lh), GFP_KERNEL);
308 get_device(&gdev->dev);
310 if (handlereq.consumer_label[0] != '\0') {
311 /* label is only initialized if consumer_label is set */
312 lh->label = kstrndup(handlereq.consumer_label,
313 sizeof(handlereq.consumer_label) - 1,
321 lh->num_descs = handlereq.lines;
323 /* Request each GPIO */
324 for (i = 0; i < handlereq.lines; i++) {
325 u32 offset = handlereq.lineoffsets[i];
326 struct gpio_desc *desc = gpiochip_get_desc(gdev->chip, offset);
333 ret = gpiod_request(desc, lh->label);
337 linehandle_flags_to_desc_flags(handlereq.flags, &desc->flags);
339 ret = gpiod_set_transitory(desc, false);
344 * Lines have to be requested explicitly for input
345 * or output, else the line will be treated "as is".
347 if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
348 int val = !!handlereq.default_values[i];
350 ret = gpiod_direction_output(desc, val);
353 } else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
354 ret = gpiod_direction_input(desc);
359 blocking_notifier_call_chain(&desc->gdev->notifier,
360 GPIO_V2_LINE_CHANGED_REQUESTED, desc);
362 dev_dbg(&gdev->dev, "registered chardev handle for line %d\n",
366 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
372 file = anon_inode_getfile("gpio-linehandle",
375 O_RDONLY | O_CLOEXEC);
378 goto out_put_unused_fd;
382 if (copy_to_user(ip, &handlereq, sizeof(handlereq))) {
384 * fput() will trigger the release() callback, so do not go onto
385 * the regular error cleanup path here.
392 fd_install(fd, file);
394 dev_dbg(&gdev->dev, "registered chardev handle for %d lines\n",
405 #endif /* CONFIG_GPIO_CDEV_V1 */
408 * struct line - contains the state of a requested line
409 * @desc: the GPIO descriptor for this line.
410 * @req: the corresponding line request
411 * @irq: the interrupt triggered in response to events on this GPIO
412 * @eflags: the edge flags, GPIO_V2_LINE_FLAG_EDGE_RISING and/or
413 * GPIO_V2_LINE_FLAG_EDGE_FALLING, indicating the edge detection applied
414 * @timestamp_ns: cache for the timestamp storing it between hardirq and
415 * IRQ thread, used to bring the timestamp close to the actual event
416 * @req_seqno: the seqno for the current edge event in the sequence of
417 * events for the corresponding line request. This is drawn from the @req.
418 * @line_seqno: the seqno for the current edge event in the sequence of
419 * events for this line.
420 * @work: the worker that implements software debouncing
421 * @sw_debounced: flag indicating if the software debouncer is active
422 * @level: the current debounced physical level of the line
425 struct gpio_desc *desc;
427 * -- edge detector specific fields --
433 * timestamp_ns and req_seqno are accessed only by
434 * edge_irq_handler() and edge_irq_thread(), which are themselves
435 * mutually exclusive, so no additional protection is necessary.
440 * line_seqno is accessed by either edge_irq_thread() or
441 * debounce_work_func(), which are themselves mutually exclusive,
442 * so no additional protection is necessary.
446 * -- debouncer specific fields --
448 struct delayed_work work;
450 * sw_debounce is accessed by linereq_set_config(), which is the
451 * only setter, and linereq_get_values(), which can live with a
452 * slightly stale value.
454 unsigned int sw_debounced;
456 * level is accessed by debounce_work_func(), which is the only
457 * setter, and linereq_get_values() which can live with a slightly
464 * struct linereq - contains the state of a userspace line request
465 * @gdev: the GPIO device the line request pertains to
466 * @label: consumer label used to tag GPIO descriptors
467 * @num_lines: the number of lines in the lines array
468 * @wait: wait queue that handles blocking reads of events
469 * @event_buffer_size: the number of elements allocated in @events
470 * @events: KFIFO for the GPIO events
471 * @seqno: the sequence number for edge events generated on all lines in
472 * this line request. Note that this is not used when @num_lines is 1, as
473 * the line_seqno is then the same and is cheaper to calculate.
474 * @config_mutex: mutex for serializing ioctl() calls to ensure consistency
475 * of configuration, particularly multi-step accesses to desc flags.
476 * @lines: the lines held by this line request, with @num_lines elements.
479 struct gpio_device *gdev;
482 wait_queue_head_t wait;
483 u32 event_buffer_size;
484 DECLARE_KFIFO_PTR(events, struct gpio_v2_line_event);
486 struct mutex config_mutex;
490 #define GPIO_V2_LINE_BIAS_FLAGS \
491 (GPIO_V2_LINE_FLAG_BIAS_PULL_UP | \
492 GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN | \
493 GPIO_V2_LINE_FLAG_BIAS_DISABLED)
495 #define GPIO_V2_LINE_DIRECTION_FLAGS \
496 (GPIO_V2_LINE_FLAG_INPUT | \
497 GPIO_V2_LINE_FLAG_OUTPUT)
499 #define GPIO_V2_LINE_DRIVE_FLAGS \
500 (GPIO_V2_LINE_FLAG_OPEN_DRAIN | \
501 GPIO_V2_LINE_FLAG_OPEN_SOURCE)
503 #define GPIO_V2_LINE_EDGE_FLAGS \
504 (GPIO_V2_LINE_FLAG_EDGE_RISING | \
505 GPIO_V2_LINE_FLAG_EDGE_FALLING)
507 #define GPIO_V2_LINE_VALID_FLAGS \
508 (GPIO_V2_LINE_FLAG_ACTIVE_LOW | \
509 GPIO_V2_LINE_DIRECTION_FLAGS | \
510 GPIO_V2_LINE_DRIVE_FLAGS | \
511 GPIO_V2_LINE_EDGE_FLAGS | \
512 GPIO_V2_LINE_BIAS_FLAGS)
514 static void linereq_put_event(struct linereq *lr,
515 struct gpio_v2_line_event *le)
517 bool overflow = false;
519 spin_lock(&lr->wait.lock);
520 if (kfifo_is_full(&lr->events)) {
522 kfifo_skip(&lr->events);
524 kfifo_in(&lr->events, le, 1);
525 spin_unlock(&lr->wait.lock);
527 wake_up_poll(&lr->wait, EPOLLIN);
529 pr_debug_ratelimited("event FIFO is full - event dropped\n");
532 static irqreturn_t edge_irq_thread(int irq, void *p)
534 struct line *line = p;
535 struct linereq *lr = line->req;
536 struct gpio_v2_line_event le;
538 /* Do not leak kernel stack to userspace */
539 memset(&le, 0, sizeof(le));
541 if (line->timestamp_ns) {
542 le.timestamp_ns = line->timestamp_ns;
545 * We may be running from a nested threaded interrupt in
546 * which case we didn't get the timestamp from
547 * edge_irq_handler().
549 le.timestamp_ns = ktime_get_ns();
550 if (lr->num_lines != 1)
551 line->req_seqno = atomic_inc_return(&lr->seqno);
553 line->timestamp_ns = 0;
555 if (line->eflags == (GPIO_V2_LINE_FLAG_EDGE_RISING |
556 GPIO_V2_LINE_FLAG_EDGE_FALLING)) {
557 int level = gpiod_get_value_cansleep(line->desc);
560 /* Emit low-to-high event */
561 le.id = GPIO_V2_LINE_EVENT_RISING_EDGE;
563 /* Emit high-to-low event */
564 le.id = GPIO_V2_LINE_EVENT_FALLING_EDGE;
565 } else if (line->eflags == GPIO_V2_LINE_FLAG_EDGE_RISING) {
566 /* Emit low-to-high event */
567 le.id = GPIO_V2_LINE_EVENT_RISING_EDGE;
568 } else if (line->eflags == GPIO_V2_LINE_FLAG_EDGE_FALLING) {
569 /* Emit high-to-low event */
570 le.id = GPIO_V2_LINE_EVENT_FALLING_EDGE;
575 le.line_seqno = line->line_seqno;
576 le.seqno = (lr->num_lines == 1) ? le.line_seqno : line->req_seqno;
577 le.offset = gpio_chip_hwgpio(line->desc);
579 linereq_put_event(lr, &le);
584 static irqreturn_t edge_irq_handler(int irq, void *p)
586 struct line *line = p;
587 struct linereq *lr = line->req;
590 * Just store the timestamp in hardirq context so we get it as
591 * close in time as possible to the actual event.
593 line->timestamp_ns = ktime_get_ns();
595 if (lr->num_lines != 1)
596 line->req_seqno = atomic_inc_return(&lr->seqno);
598 return IRQ_WAKE_THREAD;
602 * returns the current debounced logical value.
604 static bool debounced_value(struct line *line)
609 * minor race - debouncer may be stopped here, so edge_detector_stop()
610 * must leave the value unchanged so the following will read the level
611 * from when the debouncer was last running.
613 value = READ_ONCE(line->level);
615 if (test_bit(FLAG_ACTIVE_LOW, &line->desc->flags))
621 static irqreturn_t debounce_irq_handler(int irq, void *p)
623 struct line *line = p;
625 mod_delayed_work(system_wq, &line->work,
626 usecs_to_jiffies(READ_ONCE(line->desc->debounce_period_us)));
631 static void debounce_work_func(struct work_struct *work)
633 struct gpio_v2_line_event le;
634 struct line *line = container_of(work, struct line, work.work);
638 level = gpiod_get_raw_value_cansleep(line->desc);
640 pr_debug_ratelimited("debouncer failed to read line value\n");
644 if (READ_ONCE(line->level) == level)
647 WRITE_ONCE(line->level, level);
649 /* -- edge detection -- */
653 /* switch from physical level to logical - if they differ */
654 if (test_bit(FLAG_ACTIVE_LOW, &line->desc->flags))
657 /* ignore edges that are not being monitored */
658 if (((line->eflags == GPIO_V2_LINE_FLAG_EDGE_RISING) && !level) ||
659 ((line->eflags == GPIO_V2_LINE_FLAG_EDGE_FALLING) && level))
662 /* Do not leak kernel stack to userspace */
663 memset(&le, 0, sizeof(le));
666 le.timestamp_ns = ktime_get_ns();
667 le.offset = gpio_chip_hwgpio(line->desc);
669 le.line_seqno = line->line_seqno;
670 le.seqno = (lr->num_lines == 1) ?
671 le.line_seqno : atomic_inc_return(&lr->seqno);
674 /* Emit low-to-high event */
675 le.id = GPIO_V2_LINE_EVENT_RISING_EDGE;
677 /* Emit high-to-low event */
678 le.id = GPIO_V2_LINE_EVENT_FALLING_EDGE;
680 linereq_put_event(lr, &le);
683 static int debounce_setup(struct line *line,
684 unsigned int debounce_period_us)
686 unsigned long irqflags;
690 ret = gpiod_set_debounce(line->desc, debounce_period_us);
692 WRITE_ONCE(line->desc->debounce_period_us, debounce_period_us);
695 if (ret != -ENOTSUPP)
698 if (debounce_period_us) {
699 /* setup software debounce */
700 level = gpiod_get_raw_value_cansleep(line->desc);
704 irq = gpiod_to_irq(line->desc);
708 WRITE_ONCE(line->level, level);
709 irqflags = IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING;
710 ret = request_irq(irq, debounce_irq_handler, irqflags,
711 line->req->label, line);
715 WRITE_ONCE(line->sw_debounced, 1);
721 static bool gpio_v2_line_config_debounced(struct gpio_v2_line_config *lc,
722 unsigned int line_idx)
725 u64 mask = BIT_ULL(line_idx);
727 for (i = 0; i < lc->num_attrs; i++) {
728 if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_DEBOUNCE) &&
729 (lc->attrs[i].mask & mask))
735 static u32 gpio_v2_line_config_debounce_period(struct gpio_v2_line_config *lc,
736 unsigned int line_idx)
739 u64 mask = BIT_ULL(line_idx);
741 for (i = 0; i < lc->num_attrs; i++) {
742 if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_DEBOUNCE) &&
743 (lc->attrs[i].mask & mask))
744 return lc->attrs[i].attr.debounce_period_us;
749 static void edge_detector_stop(struct line *line)
752 free_irq(line->irq, line);
756 cancel_delayed_work_sync(&line->work);
757 WRITE_ONCE(line->sw_debounced, 0);
760 WRITE_ONCE(line->desc->debounce_period_us, 0);
761 /* do not change line->level - see comment in debounced_value() */
764 static int edge_detector_setup(struct line *line,
765 struct gpio_v2_line_config *lc,
766 unsigned int line_idx,
769 u32 debounce_period_us;
770 unsigned long irqflags = 0;
773 if (eflags && !kfifo_initialized(&line->req->events)) {
774 ret = kfifo_alloc(&line->req->events,
775 line->req->event_buffer_size, GFP_KERNEL);
779 line->eflags = eflags;
780 if (gpio_v2_line_config_debounced(lc, line_idx)) {
781 debounce_period_us = gpio_v2_line_config_debounce_period(lc, line_idx);
782 ret = debounce_setup(line, debounce_period_us);
785 WRITE_ONCE(line->desc->debounce_period_us, debounce_period_us);
788 /* detection disabled or sw debouncer will provide edge detection */
789 if (!eflags || READ_ONCE(line->sw_debounced))
792 irq = gpiod_to_irq(line->desc);
796 if (eflags & GPIO_V2_LINE_FLAG_EDGE_RISING)
797 irqflags |= test_bit(FLAG_ACTIVE_LOW, &line->desc->flags) ?
798 IRQF_TRIGGER_FALLING : IRQF_TRIGGER_RISING;
799 if (eflags & GPIO_V2_LINE_FLAG_EDGE_FALLING)
800 irqflags |= test_bit(FLAG_ACTIVE_LOW, &line->desc->flags) ?
801 IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING;
802 irqflags |= IRQF_ONESHOT;
804 /* Request a thread to read the events */
805 ret = request_threaded_irq(irq, edge_irq_handler, edge_irq_thread,
806 irqflags, line->req->label, line);
814 static int edge_detector_update(struct line *line,
815 struct gpio_v2_line_config *lc,
816 unsigned int line_idx,
817 u64 eflags, bool polarity_change)
819 unsigned int debounce_period_us =
820 gpio_v2_line_config_debounce_period(lc, line_idx);
822 if ((line->eflags == eflags) && !polarity_change &&
823 (READ_ONCE(line->desc->debounce_period_us) == debounce_period_us))
826 /* sw debounced and still will be...*/
827 if (debounce_period_us && READ_ONCE(line->sw_debounced)) {
828 line->eflags = eflags;
829 WRITE_ONCE(line->desc->debounce_period_us, debounce_period_us);
833 /* reconfiguring edge detection or sw debounce being disabled */
834 if ((line->irq && !READ_ONCE(line->sw_debounced)) ||
835 (!debounce_period_us && READ_ONCE(line->sw_debounced)))
836 edge_detector_stop(line);
838 return edge_detector_setup(line, lc, line_idx, eflags);
841 static u64 gpio_v2_line_config_flags(struct gpio_v2_line_config *lc,
842 unsigned int line_idx)
845 u64 mask = BIT_ULL(line_idx);
847 for (i = 0; i < lc->num_attrs; i++) {
848 if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_FLAGS) &&
849 (lc->attrs[i].mask & mask))
850 return lc->attrs[i].attr.flags;
855 static int gpio_v2_line_config_output_value(struct gpio_v2_line_config *lc,
856 unsigned int line_idx)
859 u64 mask = BIT_ULL(line_idx);
861 for (i = 0; i < lc->num_attrs; i++) {
862 if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_OUTPUT_VALUES) &&
863 (lc->attrs[i].mask & mask))
864 return !!(lc->attrs[i].attr.values & mask);
869 static int gpio_v2_line_flags_validate(u64 flags)
871 /* Return an error if an unknown flag is set */
872 if (flags & ~GPIO_V2_LINE_VALID_FLAGS)
876 * Do not allow both INPUT and OUTPUT flags to be set as they are
879 if ((flags & GPIO_V2_LINE_FLAG_INPUT) &&
880 (flags & GPIO_V2_LINE_FLAG_OUTPUT))
883 /* Edge detection requires explicit input. */
884 if ((flags & GPIO_V2_LINE_EDGE_FLAGS) &&
885 !(flags & GPIO_V2_LINE_FLAG_INPUT))
889 * Do not allow OPEN_SOURCE and OPEN_DRAIN flags in a single
890 * request. If the hardware actually supports enabling both at the
891 * same time the electrical result would be disastrous.
893 if ((flags & GPIO_V2_LINE_FLAG_OPEN_DRAIN) &&
894 (flags & GPIO_V2_LINE_FLAG_OPEN_SOURCE))
897 /* Drive requires explicit output direction. */
898 if ((flags & GPIO_V2_LINE_DRIVE_FLAGS) &&
899 !(flags & GPIO_V2_LINE_FLAG_OUTPUT))
902 /* Bias requires explicit direction. */
903 if ((flags & GPIO_V2_LINE_BIAS_FLAGS) &&
904 !(flags & GPIO_V2_LINE_DIRECTION_FLAGS))
907 /* Only one bias flag can be set. */
908 if (((flags & GPIO_V2_LINE_FLAG_BIAS_DISABLED) &&
909 (flags & (GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN |
910 GPIO_V2_LINE_FLAG_BIAS_PULL_UP))) ||
911 ((flags & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN) &&
912 (flags & GPIO_V2_LINE_FLAG_BIAS_PULL_UP)))
918 static int gpio_v2_line_config_validate(struct gpio_v2_line_config *lc,
919 unsigned int num_lines)
925 if (lc->num_attrs > GPIO_V2_LINE_NUM_ATTRS_MAX)
928 if (memchr_inv(lc->padding, 0, sizeof(lc->padding)))
931 for (i = 0; i < num_lines; i++) {
932 flags = gpio_v2_line_config_flags(lc, i);
933 ret = gpio_v2_line_flags_validate(flags);
937 /* debounce requires explicit input */
938 if (gpio_v2_line_config_debounced(lc, i) &&
939 !(flags & GPIO_V2_LINE_FLAG_INPUT))
945 static void gpio_v2_line_config_flags_to_desc_flags(u64 flags,
946 unsigned long *flagsp)
948 assign_bit(FLAG_ACTIVE_LOW, flagsp,
949 flags & GPIO_V2_LINE_FLAG_ACTIVE_LOW);
951 if (flags & GPIO_V2_LINE_FLAG_OUTPUT)
952 set_bit(FLAG_IS_OUT, flagsp);
953 else if (flags & GPIO_V2_LINE_FLAG_INPUT)
954 clear_bit(FLAG_IS_OUT, flagsp);
956 assign_bit(FLAG_EDGE_RISING, flagsp,
957 flags & GPIO_V2_LINE_FLAG_EDGE_RISING);
958 assign_bit(FLAG_EDGE_FALLING, flagsp,
959 flags & GPIO_V2_LINE_FLAG_EDGE_FALLING);
961 assign_bit(FLAG_OPEN_DRAIN, flagsp,
962 flags & GPIO_V2_LINE_FLAG_OPEN_DRAIN);
963 assign_bit(FLAG_OPEN_SOURCE, flagsp,
964 flags & GPIO_V2_LINE_FLAG_OPEN_SOURCE);
966 assign_bit(FLAG_PULL_UP, flagsp,
967 flags & GPIO_V2_LINE_FLAG_BIAS_PULL_UP);
968 assign_bit(FLAG_PULL_DOWN, flagsp,
969 flags & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN);
970 assign_bit(FLAG_BIAS_DISABLE, flagsp,
971 flags & GPIO_V2_LINE_FLAG_BIAS_DISABLED);
974 static long linereq_get_values(struct linereq *lr, void __user *ip)
976 struct gpio_v2_line_values lv;
977 DECLARE_BITMAP(vals, GPIO_V2_LINES_MAX);
978 struct gpio_desc **descs;
979 unsigned int i, didx, num_get;
983 /* NOTE: It's ok to read values of output lines. */
984 if (copy_from_user(&lv, ip, sizeof(lv)))
987 for (num_get = 0, i = 0; i < lr->num_lines; i++) {
988 if (lv.mask & BIT_ULL(i)) {
990 descs = &lr->lines[i].desc;
998 descs = kmalloc_array(num_get, sizeof(*descs), GFP_KERNEL);
1001 for (didx = 0, i = 0; i < lr->num_lines; i++) {
1002 if (lv.mask & BIT_ULL(i)) {
1003 descs[didx] = lr->lines[i].desc;
1008 ret = gpiod_get_array_value_complex(false, true, num_get,
1017 for (didx = 0, i = 0; i < lr->num_lines; i++) {
1018 if (lv.mask & BIT_ULL(i)) {
1019 if (lr->lines[i].sw_debounced)
1020 val = debounced_value(&lr->lines[i]);
1022 val = test_bit(didx, vals);
1024 lv.bits |= BIT_ULL(i);
1029 if (copy_to_user(ip, &lv, sizeof(lv)))
1035 static long linereq_set_values_unlocked(struct linereq *lr,
1036 struct gpio_v2_line_values *lv)
1038 DECLARE_BITMAP(vals, GPIO_V2_LINES_MAX);
1039 struct gpio_desc **descs;
1040 unsigned int i, didx, num_set;
1043 bitmap_zero(vals, GPIO_V2_LINES_MAX);
1044 for (num_set = 0, i = 0; i < lr->num_lines; i++) {
1045 if (lv->mask & BIT_ULL(i)) {
1046 if (!test_bit(FLAG_IS_OUT, &lr->lines[i].desc->flags))
1048 if (lv->bits & BIT_ULL(i))
1049 __set_bit(num_set, vals);
1051 descs = &lr->lines[i].desc;
1058 /* build compacted desc array and values */
1059 descs = kmalloc_array(num_set, sizeof(*descs), GFP_KERNEL);
1062 for (didx = 0, i = 0; i < lr->num_lines; i++) {
1063 if (lv->mask & BIT_ULL(i)) {
1064 descs[didx] = lr->lines[i].desc;
1069 ret = gpiod_set_array_value_complex(false, true, num_set,
1077 static long linereq_set_values(struct linereq *lr, void __user *ip)
1079 struct gpio_v2_line_values lv;
1082 if (copy_from_user(&lv, ip, sizeof(lv)))
1085 mutex_lock(&lr->config_mutex);
1087 ret = linereq_set_values_unlocked(lr, &lv);
1089 mutex_unlock(&lr->config_mutex);
1094 static long linereq_set_config_unlocked(struct linereq *lr,
1095 struct gpio_v2_line_config *lc)
1097 struct gpio_desc *desc;
1100 bool polarity_change;
1103 for (i = 0; i < lr->num_lines; i++) {
1104 desc = lr->lines[i].desc;
1105 flags = gpio_v2_line_config_flags(lc, i);
1107 (!!test_bit(FLAG_ACTIVE_LOW, &desc->flags) !=
1108 ((flags & GPIO_V2_LINE_FLAG_ACTIVE_LOW) != 0));
1110 gpio_v2_line_config_flags_to_desc_flags(flags, &desc->flags);
1112 * Lines have to be requested explicitly for input
1113 * or output, else the line will be treated "as is".
1115 if (flags & GPIO_V2_LINE_FLAG_OUTPUT) {
1116 int val = gpio_v2_line_config_output_value(lc, i);
1118 edge_detector_stop(&lr->lines[i]);
1119 ret = gpiod_direction_output(desc, val);
1122 } else if (flags & GPIO_V2_LINE_FLAG_INPUT) {
1123 ret = gpiod_direction_input(desc);
1127 ret = edge_detector_update(&lr->lines[i], lc, i,
1128 flags & GPIO_V2_LINE_EDGE_FLAGS,
1134 blocking_notifier_call_chain(&desc->gdev->notifier,
1135 GPIO_V2_LINE_CHANGED_CONFIG,
1141 static long linereq_set_config(struct linereq *lr, void __user *ip)
1143 struct gpio_v2_line_config lc;
1146 if (copy_from_user(&lc, ip, sizeof(lc)))
1149 ret = gpio_v2_line_config_validate(&lc, lr->num_lines);
1153 mutex_lock(&lr->config_mutex);
1155 ret = linereq_set_config_unlocked(lr, &lc);
1157 mutex_unlock(&lr->config_mutex);
1162 static long linereq_ioctl(struct file *file, unsigned int cmd,
1165 struct linereq *lr = file->private_data;
1166 void __user *ip = (void __user *)arg;
1168 if (cmd == GPIO_V2_LINE_GET_VALUES_IOCTL)
1169 return linereq_get_values(lr, ip);
1170 else if (cmd == GPIO_V2_LINE_SET_VALUES_IOCTL)
1171 return linereq_set_values(lr, ip);
1172 else if (cmd == GPIO_V2_LINE_SET_CONFIG_IOCTL)
1173 return linereq_set_config(lr, ip);
1178 #ifdef CONFIG_COMPAT
1179 static long linereq_ioctl_compat(struct file *file, unsigned int cmd,
1182 return linereq_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
1186 static __poll_t linereq_poll(struct file *file,
1187 struct poll_table_struct *wait)
1189 struct linereq *lr = file->private_data;
1190 __poll_t events = 0;
1192 poll_wait(file, &lr->wait, wait);
1194 if (!kfifo_is_empty_spinlocked_noirqsave(&lr->events,
1196 events = EPOLLIN | EPOLLRDNORM;
1201 static ssize_t linereq_read(struct file *file,
1206 struct linereq *lr = file->private_data;
1207 struct gpio_v2_line_event le;
1208 ssize_t bytes_read = 0;
1211 if (count < sizeof(le))
1215 spin_lock(&lr->wait.lock);
1216 if (kfifo_is_empty(&lr->events)) {
1218 spin_unlock(&lr->wait.lock);
1222 if (file->f_flags & O_NONBLOCK) {
1223 spin_unlock(&lr->wait.lock);
1227 ret = wait_event_interruptible_locked(lr->wait,
1228 !kfifo_is_empty(&lr->events));
1230 spin_unlock(&lr->wait.lock);
1235 ret = kfifo_out(&lr->events, &le, 1);
1236 spin_unlock(&lr->wait.lock);
1239 * This should never happen - we were holding the
1240 * lock from the moment we learned the fifo is no
1241 * longer empty until now.
1247 if (copy_to_user(buf + bytes_read, &le, sizeof(le)))
1249 bytes_read += sizeof(le);
1250 } while (count >= bytes_read + sizeof(le));
1255 static void linereq_free(struct linereq *lr)
1259 for (i = 0; i < lr->num_lines; i++) {
1260 edge_detector_stop(&lr->lines[i]);
1261 if (lr->lines[i].desc)
1262 gpiod_free(lr->lines[i].desc);
1264 kfifo_free(&lr->events);
1266 put_device(&lr->gdev->dev);
1270 static int linereq_release(struct inode *inode, struct file *file)
1272 struct linereq *lr = file->private_data;
1278 static const struct file_operations line_fileops = {
1279 .release = linereq_release,
1280 .read = linereq_read,
1281 .poll = linereq_poll,
1282 .owner = THIS_MODULE,
1283 .llseek = noop_llseek,
1284 .unlocked_ioctl = linereq_ioctl,
1285 #ifdef CONFIG_COMPAT
1286 .compat_ioctl = linereq_ioctl_compat,
1290 static int linereq_create(struct gpio_device *gdev, void __user *ip)
1292 struct gpio_v2_line_request ulr;
1293 struct gpio_v2_line_config *lc;
1300 if (copy_from_user(&ulr, ip, sizeof(ulr)))
1303 if ((ulr.num_lines == 0) || (ulr.num_lines > GPIO_V2_LINES_MAX))
1306 if (memchr_inv(ulr.padding, 0, sizeof(ulr.padding)))
1310 ret = gpio_v2_line_config_validate(lc, ulr.num_lines);
1314 lr = kzalloc(struct_size(lr, lines, ulr.num_lines), GFP_KERNEL);
1319 get_device(&gdev->dev);
1321 for (i = 0; i < ulr.num_lines; i++) {
1322 lr->lines[i].req = lr;
1323 WRITE_ONCE(lr->lines[i].sw_debounced, 0);
1324 INIT_DELAYED_WORK(&lr->lines[i].work, debounce_work_func);
1327 if (ulr.consumer[0] != '\0') {
1328 /* label is only initialized if consumer is set */
1329 lr->label = kstrndup(ulr.consumer, sizeof(ulr.consumer) - 1,
1333 goto out_free_linereq;
1337 mutex_init(&lr->config_mutex);
1338 init_waitqueue_head(&lr->wait);
1339 lr->event_buffer_size = ulr.event_buffer_size;
1340 if (lr->event_buffer_size == 0)
1341 lr->event_buffer_size = ulr.num_lines * 16;
1342 else if (lr->event_buffer_size > GPIO_V2_LINES_MAX * 16)
1343 lr->event_buffer_size = GPIO_V2_LINES_MAX * 16;
1345 atomic_set(&lr->seqno, 0);
1346 lr->num_lines = ulr.num_lines;
1348 /* Request each GPIO */
1349 for (i = 0; i < ulr.num_lines; i++) {
1350 u32 offset = ulr.offsets[i];
1351 struct gpio_desc *desc = gpiochip_get_desc(gdev->chip, offset);
1354 ret = PTR_ERR(desc);
1355 goto out_free_linereq;
1358 ret = gpiod_request(desc, lr->label);
1360 goto out_free_linereq;
1362 lr->lines[i].desc = desc;
1363 flags = gpio_v2_line_config_flags(lc, i);
1364 gpio_v2_line_config_flags_to_desc_flags(flags, &desc->flags);
1366 ret = gpiod_set_transitory(desc, false);
1368 goto out_free_linereq;
1371 * Lines have to be requested explicitly for input
1372 * or output, else the line will be treated "as is".
1374 if (flags & GPIO_V2_LINE_FLAG_OUTPUT) {
1375 int val = gpio_v2_line_config_output_value(lc, i);
1377 ret = gpiod_direction_output(desc, val);
1379 goto out_free_linereq;
1380 } else if (flags & GPIO_V2_LINE_FLAG_INPUT) {
1381 ret = gpiod_direction_input(desc);
1383 goto out_free_linereq;
1385 ret = edge_detector_setup(&lr->lines[i], lc, i,
1386 flags & GPIO_V2_LINE_EDGE_FLAGS);
1388 goto out_free_linereq;
1391 blocking_notifier_call_chain(&desc->gdev->notifier,
1392 GPIO_V2_LINE_CHANGED_REQUESTED, desc);
1394 dev_dbg(&gdev->dev, "registered chardev handle for line %d\n",
1398 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
1401 goto out_free_linereq;
1404 file = anon_inode_getfile("gpio-line", &line_fileops, lr,
1405 O_RDONLY | O_CLOEXEC);
1407 ret = PTR_ERR(file);
1408 goto out_put_unused_fd;
1412 if (copy_to_user(ip, &ulr, sizeof(ulr))) {
1414 * fput() will trigger the release() callback, so do not go onto
1415 * the regular error cleanup path here.
1422 fd_install(fd, file);
1424 dev_dbg(&gdev->dev, "registered chardev handle for %d lines\n",
1436 #ifdef CONFIG_GPIO_CDEV_V1
1439 * GPIO line event management
1443 * struct lineevent_state - contains the state of a userspace event
1444 * @gdev: the GPIO device the event pertains to
1445 * @label: consumer label used to tag descriptors
1446 * @desc: the GPIO descriptor held by this event
1447 * @eflags: the event flags this line was requested with
1448 * @irq: the interrupt that trigger in response to events on this GPIO
1449 * @wait: wait queue that handles blocking reads of events
1450 * @events: KFIFO for the GPIO events
1451 * @timestamp: cache for the timestamp storing it between hardirq
1452 * and IRQ thread, used to bring the timestamp close to the actual
1455 struct lineevent_state {
1456 struct gpio_device *gdev;
1458 struct gpio_desc *desc;
1461 wait_queue_head_t wait;
1462 DECLARE_KFIFO(events, struct gpioevent_data, 16);
1466 #define GPIOEVENT_REQUEST_VALID_FLAGS \
1467 (GPIOEVENT_REQUEST_RISING_EDGE | \
1468 GPIOEVENT_REQUEST_FALLING_EDGE)
1470 static __poll_t lineevent_poll(struct file *file,
1471 struct poll_table_struct *wait)
1473 struct lineevent_state *le = file->private_data;
1474 __poll_t events = 0;
1476 poll_wait(file, &le->wait, wait);
1478 if (!kfifo_is_empty_spinlocked_noirqsave(&le->events, &le->wait.lock))
1479 events = EPOLLIN | EPOLLRDNORM;
1484 static ssize_t lineevent_get_size(void)
1486 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML)
1487 /* i386 has no padding after 'id' */
1488 if (in_ia32_syscall()) {
1489 struct compat_gpioeevent_data {
1490 compat_u64 timestamp;
1494 return sizeof(struct compat_gpioeevent_data);
1497 return sizeof(struct gpioevent_data);
1500 static ssize_t lineevent_read(struct file *file,
1505 struct lineevent_state *le = file->private_data;
1506 struct gpioevent_data ge;
1507 ssize_t bytes_read = 0;
1512 * When compatible system call is being used the struct gpioevent_data,
1513 * in case of at least ia32, has different size due to the alignment
1514 * differences. Because we have first member 64 bits followed by one of
1515 * 32 bits there is no gap between them. The only difference is the
1516 * padding at the end of the data structure. Hence, we calculate the
1517 * actual sizeof() and pass this as an argument to copy_to_user() to
1518 * drop unneeded bytes from the output.
1520 ge_size = lineevent_get_size();
1521 if (count < ge_size)
1525 spin_lock(&le->wait.lock);
1526 if (kfifo_is_empty(&le->events)) {
1528 spin_unlock(&le->wait.lock);
1532 if (file->f_flags & O_NONBLOCK) {
1533 spin_unlock(&le->wait.lock);
1537 ret = wait_event_interruptible_locked(le->wait,
1538 !kfifo_is_empty(&le->events));
1540 spin_unlock(&le->wait.lock);
1545 ret = kfifo_out(&le->events, &ge, 1);
1546 spin_unlock(&le->wait.lock);
1549 * This should never happen - we were holding the lock
1550 * from the moment we learned the fifo is no longer
1557 if (copy_to_user(buf + bytes_read, &ge, ge_size))
1559 bytes_read += ge_size;
1560 } while (count >= bytes_read + ge_size);
1565 static void lineevent_free(struct lineevent_state *le)
1568 free_irq(le->irq, le);
1570 gpiod_free(le->desc);
1572 put_device(&le->gdev->dev);
1576 static int lineevent_release(struct inode *inode, struct file *file)
1578 lineevent_free(file->private_data);
1582 static long lineevent_ioctl(struct file *file, unsigned int cmd,
1585 struct lineevent_state *le = file->private_data;
1586 void __user *ip = (void __user *)arg;
1587 struct gpiohandle_data ghd;
1590 * We can get the value for an event line but not set it,
1591 * because it is input by definition.
1593 if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
1596 memset(&ghd, 0, sizeof(ghd));
1598 val = gpiod_get_value_cansleep(le->desc);
1601 ghd.values[0] = val;
1603 if (copy_to_user(ip, &ghd, sizeof(ghd)))
1611 #ifdef CONFIG_COMPAT
1612 static long lineevent_ioctl_compat(struct file *file, unsigned int cmd,
1615 return lineevent_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
1619 static const struct file_operations lineevent_fileops = {
1620 .release = lineevent_release,
1621 .read = lineevent_read,
1622 .poll = lineevent_poll,
1623 .owner = THIS_MODULE,
1624 .llseek = noop_llseek,
1625 .unlocked_ioctl = lineevent_ioctl,
1626 #ifdef CONFIG_COMPAT
1627 .compat_ioctl = lineevent_ioctl_compat,
1631 static irqreturn_t lineevent_irq_thread(int irq, void *p)
1633 struct lineevent_state *le = p;
1634 struct gpioevent_data ge;
1637 /* Do not leak kernel stack to userspace */
1638 memset(&ge, 0, sizeof(ge));
1641 * We may be running from a nested threaded interrupt in which case
1642 * we didn't get the timestamp from lineevent_irq_handler().
1645 ge.timestamp = ktime_get_ns();
1647 ge.timestamp = le->timestamp;
1649 if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE
1650 && le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
1651 int level = gpiod_get_value_cansleep(le->desc);
1654 /* Emit low-to-high event */
1655 ge.id = GPIOEVENT_EVENT_RISING_EDGE;
1657 /* Emit high-to-low event */
1658 ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
1659 } else if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE) {
1660 /* Emit low-to-high event */
1661 ge.id = GPIOEVENT_EVENT_RISING_EDGE;
1662 } else if (le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
1663 /* Emit high-to-low event */
1664 ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
1669 ret = kfifo_in_spinlocked_noirqsave(&le->events, &ge,
1672 wake_up_poll(&le->wait, EPOLLIN);
1674 pr_debug_ratelimited("event FIFO is full - event dropped\n");
1679 static irqreturn_t lineevent_irq_handler(int irq, void *p)
1681 struct lineevent_state *le = p;
1684 * Just store the timestamp in hardirq context so we get it as
1685 * close in time as possible to the actual event.
1687 le->timestamp = ktime_get_ns();
1689 return IRQ_WAKE_THREAD;
1692 static int lineevent_create(struct gpio_device *gdev, void __user *ip)
1694 struct gpioevent_request eventreq;
1695 struct lineevent_state *le;
1696 struct gpio_desc *desc;
1703 int irq, irqflags = 0;
1705 if (copy_from_user(&eventreq, ip, sizeof(eventreq)))
1708 offset = eventreq.lineoffset;
1709 lflags = eventreq.handleflags;
1710 eflags = eventreq.eventflags;
1712 desc = gpiochip_get_desc(gdev->chip, offset);
1714 return PTR_ERR(desc);
1716 /* Return an error if a unknown flag is set */
1717 if ((lflags & ~GPIOHANDLE_REQUEST_VALID_FLAGS) ||
1718 (eflags & ~GPIOEVENT_REQUEST_VALID_FLAGS))
1721 /* This is just wrong: we don't look for events on output lines */
1722 if ((lflags & GPIOHANDLE_REQUEST_OUTPUT) ||
1723 (lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN) ||
1724 (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE))
1727 /* Only one bias flag can be set. */
1728 if (((lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE) &&
1729 (lflags & (GPIOHANDLE_REQUEST_BIAS_PULL_DOWN |
1730 GPIOHANDLE_REQUEST_BIAS_PULL_UP))) ||
1731 ((lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN) &&
1732 (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)))
1735 le = kzalloc(sizeof(*le), GFP_KERNEL);
1739 get_device(&gdev->dev);
1741 if (eventreq.consumer_label[0] != '\0') {
1742 /* label is only initialized if consumer_label is set */
1743 le->label = kstrndup(eventreq.consumer_label,
1744 sizeof(eventreq.consumer_label) - 1,
1752 ret = gpiod_request(desc, le->label);
1756 le->eflags = eflags;
1758 linehandle_flags_to_desc_flags(lflags, &desc->flags);
1760 ret = gpiod_direction_input(desc);
1764 blocking_notifier_call_chain(&desc->gdev->notifier,
1765 GPIO_V2_LINE_CHANGED_REQUESTED, desc);
1767 irq = gpiod_to_irq(desc);
1773 if (eflags & GPIOEVENT_REQUEST_RISING_EDGE)
1774 irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
1775 IRQF_TRIGGER_FALLING : IRQF_TRIGGER_RISING;
1776 if (eflags & GPIOEVENT_REQUEST_FALLING_EDGE)
1777 irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
1778 IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING;
1779 irqflags |= IRQF_ONESHOT;
1781 INIT_KFIFO(le->events);
1782 init_waitqueue_head(&le->wait);
1784 /* Request a thread to read the events */
1785 ret = request_threaded_irq(irq,
1786 lineevent_irq_handler,
1787 lineevent_irq_thread,
1796 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
1802 file = anon_inode_getfile("gpio-event",
1805 O_RDONLY | O_CLOEXEC);
1807 ret = PTR_ERR(file);
1808 goto out_put_unused_fd;
1812 if (copy_to_user(ip, &eventreq, sizeof(eventreq))) {
1814 * fput() will trigger the release() callback, so do not go onto
1815 * the regular error cleanup path here.
1822 fd_install(fd, file);
1833 static void gpio_v2_line_info_to_v1(struct gpio_v2_line_info *info_v2,
1834 struct gpioline_info *info_v1)
1836 u64 flagsv2 = info_v2->flags;
1838 memcpy(info_v1->name, info_v2->name, sizeof(info_v1->name));
1839 memcpy(info_v1->consumer, info_v2->consumer, sizeof(info_v1->consumer));
1840 info_v1->line_offset = info_v2->offset;
1843 if (flagsv2 & GPIO_V2_LINE_FLAG_USED)
1844 info_v1->flags |= GPIOLINE_FLAG_KERNEL;
1846 if (flagsv2 & GPIO_V2_LINE_FLAG_OUTPUT)
1847 info_v1->flags |= GPIOLINE_FLAG_IS_OUT;
1849 if (flagsv2 & GPIO_V2_LINE_FLAG_ACTIVE_LOW)
1850 info_v1->flags |= GPIOLINE_FLAG_ACTIVE_LOW;
1852 if (flagsv2 & GPIO_V2_LINE_FLAG_OPEN_DRAIN)
1853 info_v1->flags |= GPIOLINE_FLAG_OPEN_DRAIN;
1854 if (flagsv2 & GPIO_V2_LINE_FLAG_OPEN_SOURCE)
1855 info_v1->flags |= GPIOLINE_FLAG_OPEN_SOURCE;
1857 if (flagsv2 & GPIO_V2_LINE_FLAG_BIAS_PULL_UP)
1858 info_v1->flags |= GPIOLINE_FLAG_BIAS_PULL_UP;
1859 if (flagsv2 & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN)
1860 info_v1->flags |= GPIOLINE_FLAG_BIAS_PULL_DOWN;
1861 if (flagsv2 & GPIO_V2_LINE_FLAG_BIAS_DISABLED)
1862 info_v1->flags |= GPIOLINE_FLAG_BIAS_DISABLE;
1865 static void gpio_v2_line_info_changed_to_v1(
1866 struct gpio_v2_line_info_changed *lic_v2,
1867 struct gpioline_info_changed *lic_v1)
1869 memset(lic_v1, 0, sizeof(*lic_v1));
1870 gpio_v2_line_info_to_v1(&lic_v2->info, &lic_v1->info);
1871 lic_v1->timestamp = lic_v2->timestamp_ns;
1872 lic_v1->event_type = lic_v2->event_type;
1875 #endif /* CONFIG_GPIO_CDEV_V1 */
1877 static void gpio_desc_to_lineinfo(struct gpio_desc *desc,
1878 struct gpio_v2_line_info *info)
1880 struct gpio_chip *gc = desc->gdev->chip;
1881 bool ok_for_pinctrl;
1882 unsigned long flags;
1883 u32 debounce_period_us;
1884 unsigned int num_attrs = 0;
1886 memset(info, 0, sizeof(*info));
1887 info->offset = gpio_chip_hwgpio(desc);
1890 * This function takes a mutex so we must check this before taking
1893 * FIXME: find a non-racy way to retrieve this information. Maybe a
1894 * lock common to both frameworks?
1897 pinctrl_gpio_can_use_line(gc->base + info->offset);
1899 spin_lock_irqsave(&gpio_lock, flags);
1902 strscpy(info->name, desc->name, sizeof(info->name));
1905 strscpy(info->consumer, desc->label, sizeof(info->consumer));
1908 * Userspace only need to know that the kernel is using this GPIO so
1912 if (test_bit(FLAG_REQUESTED, &desc->flags) ||
1913 test_bit(FLAG_IS_HOGGED, &desc->flags) ||
1914 test_bit(FLAG_USED_AS_IRQ, &desc->flags) ||
1915 test_bit(FLAG_EXPORT, &desc->flags) ||
1916 test_bit(FLAG_SYSFS, &desc->flags) ||
1918 info->flags |= GPIO_V2_LINE_FLAG_USED;
1920 if (test_bit(FLAG_IS_OUT, &desc->flags))
1921 info->flags |= GPIO_V2_LINE_FLAG_OUTPUT;
1923 info->flags |= GPIO_V2_LINE_FLAG_INPUT;
1925 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
1926 info->flags |= GPIO_V2_LINE_FLAG_ACTIVE_LOW;
1928 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
1929 info->flags |= GPIO_V2_LINE_FLAG_OPEN_DRAIN;
1930 if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
1931 info->flags |= GPIO_V2_LINE_FLAG_OPEN_SOURCE;
1933 if (test_bit(FLAG_BIAS_DISABLE, &desc->flags))
1934 info->flags |= GPIO_V2_LINE_FLAG_BIAS_DISABLED;
1935 if (test_bit(FLAG_PULL_DOWN, &desc->flags))
1936 info->flags |= GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN;
1937 if (test_bit(FLAG_PULL_UP, &desc->flags))
1938 info->flags |= GPIO_V2_LINE_FLAG_BIAS_PULL_UP;
1940 if (test_bit(FLAG_EDGE_RISING, &desc->flags))
1941 info->flags |= GPIO_V2_LINE_FLAG_EDGE_RISING;
1942 if (test_bit(FLAG_EDGE_FALLING, &desc->flags))
1943 info->flags |= GPIO_V2_LINE_FLAG_EDGE_FALLING;
1945 debounce_period_us = READ_ONCE(desc->debounce_period_us);
1946 if (debounce_period_us) {
1947 info->attrs[num_attrs].id = GPIO_V2_LINE_ATTR_ID_DEBOUNCE;
1948 info->attrs[num_attrs].debounce_period_us = debounce_period_us;
1951 info->num_attrs = num_attrs;
1953 spin_unlock_irqrestore(&gpio_lock, flags);
1956 struct gpio_chardev_data {
1957 struct gpio_device *gdev;
1958 wait_queue_head_t wait;
1959 DECLARE_KFIFO(events, struct gpio_v2_line_info_changed, 32);
1960 struct notifier_block lineinfo_changed_nb;
1961 unsigned long *watched_lines;
1962 #ifdef CONFIG_GPIO_CDEV_V1
1963 atomic_t watch_abi_version;
1967 static int chipinfo_get(struct gpio_chardev_data *cdev, void __user *ip)
1969 struct gpio_device *gdev = cdev->gdev;
1970 struct gpiochip_info chipinfo;
1972 memset(&chipinfo, 0, sizeof(chipinfo));
1974 strscpy(chipinfo.name, dev_name(&gdev->dev), sizeof(chipinfo.name));
1975 strscpy(chipinfo.label, gdev->label, sizeof(chipinfo.label));
1976 chipinfo.lines = gdev->ngpio;
1977 if (copy_to_user(ip, &chipinfo, sizeof(chipinfo)))
1982 #ifdef CONFIG_GPIO_CDEV_V1
1984 * returns 0 if the versions match, else the previously selected ABI version
1986 static int lineinfo_ensure_abi_version(struct gpio_chardev_data *cdata,
1987 unsigned int version)
1989 int abiv = atomic_cmpxchg(&cdata->watch_abi_version, 0, version);
1991 if (abiv == version)
1997 static int lineinfo_get_v1(struct gpio_chardev_data *cdev, void __user *ip,
2000 struct gpio_desc *desc;
2001 struct gpioline_info lineinfo;
2002 struct gpio_v2_line_info lineinfo_v2;
2004 if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
2007 /* this doubles as a range check on line_offset */
2008 desc = gpiochip_get_desc(cdev->gdev->chip, lineinfo.line_offset);
2010 return PTR_ERR(desc);
2013 if (lineinfo_ensure_abi_version(cdev, 1))
2016 if (test_and_set_bit(lineinfo.line_offset, cdev->watched_lines))
2020 gpio_desc_to_lineinfo(desc, &lineinfo_v2);
2021 gpio_v2_line_info_to_v1(&lineinfo_v2, &lineinfo);
2023 if (copy_to_user(ip, &lineinfo, sizeof(lineinfo))) {
2025 clear_bit(lineinfo.line_offset, cdev->watched_lines);
2033 static int lineinfo_get(struct gpio_chardev_data *cdev, void __user *ip,
2036 struct gpio_desc *desc;
2037 struct gpio_v2_line_info lineinfo;
2039 if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
2042 if (memchr_inv(lineinfo.padding, 0, sizeof(lineinfo.padding)))
2045 desc = gpiochip_get_desc(cdev->gdev->chip, lineinfo.offset);
2047 return PTR_ERR(desc);
2050 #ifdef CONFIG_GPIO_CDEV_V1
2051 if (lineinfo_ensure_abi_version(cdev, 2))
2054 if (test_and_set_bit(lineinfo.offset, cdev->watched_lines))
2057 gpio_desc_to_lineinfo(desc, &lineinfo);
2059 if (copy_to_user(ip, &lineinfo, sizeof(lineinfo))) {
2061 clear_bit(lineinfo.offset, cdev->watched_lines);
2068 static int lineinfo_unwatch(struct gpio_chardev_data *cdev, void __user *ip)
2072 if (copy_from_user(&offset, ip, sizeof(offset)))
2075 if (offset >= cdev->gdev->ngpio)
2078 if (!test_and_clear_bit(offset, cdev->watched_lines))
2085 * gpio_ioctl() - ioctl handler for the GPIO chardev
2087 static long gpio_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
2089 struct gpio_chardev_data *cdev = file->private_data;
2090 struct gpio_device *gdev = cdev->gdev;
2091 void __user *ip = (void __user *)arg;
2093 /* We fail any subsequent ioctl():s when the chip is gone */
2097 /* Fill in the struct and pass to userspace */
2098 if (cmd == GPIO_GET_CHIPINFO_IOCTL) {
2099 return chipinfo_get(cdev, ip);
2100 #ifdef CONFIG_GPIO_CDEV_V1
2101 } else if (cmd == GPIO_GET_LINEHANDLE_IOCTL) {
2102 return linehandle_create(gdev, ip);
2103 } else if (cmd == GPIO_GET_LINEEVENT_IOCTL) {
2104 return lineevent_create(gdev, ip);
2105 } else if (cmd == GPIO_GET_LINEINFO_IOCTL ||
2106 cmd == GPIO_GET_LINEINFO_WATCH_IOCTL) {
2107 return lineinfo_get_v1(cdev, ip,
2108 cmd == GPIO_GET_LINEINFO_WATCH_IOCTL);
2109 #endif /* CONFIG_GPIO_CDEV_V1 */
2110 } else if (cmd == GPIO_V2_GET_LINEINFO_IOCTL ||
2111 cmd == GPIO_V2_GET_LINEINFO_WATCH_IOCTL) {
2112 return lineinfo_get(cdev, ip,
2113 cmd == GPIO_V2_GET_LINEINFO_WATCH_IOCTL);
2114 } else if (cmd == GPIO_V2_GET_LINE_IOCTL) {
2115 return linereq_create(gdev, ip);
2116 } else if (cmd == GPIO_GET_LINEINFO_UNWATCH_IOCTL) {
2117 return lineinfo_unwatch(cdev, ip);
2122 #ifdef CONFIG_COMPAT
2123 static long gpio_ioctl_compat(struct file *file, unsigned int cmd,
2126 return gpio_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
2130 static struct gpio_chardev_data *
2131 to_gpio_chardev_data(struct notifier_block *nb)
2133 return container_of(nb, struct gpio_chardev_data, lineinfo_changed_nb);
2136 static int lineinfo_changed_notify(struct notifier_block *nb,
2137 unsigned long action, void *data)
2139 struct gpio_chardev_data *cdev = to_gpio_chardev_data(nb);
2140 struct gpio_v2_line_info_changed chg;
2141 struct gpio_desc *desc = data;
2144 if (!test_bit(gpio_chip_hwgpio(desc), cdev->watched_lines))
2147 memset(&chg, 0, sizeof(chg));
2148 chg.event_type = action;
2149 chg.timestamp_ns = ktime_get_ns();
2150 gpio_desc_to_lineinfo(desc, &chg.info);
2152 ret = kfifo_in_spinlocked(&cdev->events, &chg, 1, &cdev->wait.lock);
2154 wake_up_poll(&cdev->wait, EPOLLIN);
2156 pr_debug_ratelimited("lineinfo event FIFO is full - event dropped\n");
2161 static __poll_t lineinfo_watch_poll(struct file *file,
2162 struct poll_table_struct *pollt)
2164 struct gpio_chardev_data *cdev = file->private_data;
2165 __poll_t events = 0;
2167 poll_wait(file, &cdev->wait, pollt);
2169 if (!kfifo_is_empty_spinlocked_noirqsave(&cdev->events,
2171 events = EPOLLIN | EPOLLRDNORM;
2176 static ssize_t lineinfo_watch_read(struct file *file, char __user *buf,
2177 size_t count, loff_t *off)
2179 struct gpio_chardev_data *cdev = file->private_data;
2180 struct gpio_v2_line_info_changed event;
2181 ssize_t bytes_read = 0;
2185 #ifndef CONFIG_GPIO_CDEV_V1
2186 event_size = sizeof(struct gpio_v2_line_info_changed);
2187 if (count < event_size)
2192 spin_lock(&cdev->wait.lock);
2193 if (kfifo_is_empty(&cdev->events)) {
2195 spin_unlock(&cdev->wait.lock);
2199 if (file->f_flags & O_NONBLOCK) {
2200 spin_unlock(&cdev->wait.lock);
2204 ret = wait_event_interruptible_locked(cdev->wait,
2205 !kfifo_is_empty(&cdev->events));
2207 spin_unlock(&cdev->wait.lock);
2211 #ifdef CONFIG_GPIO_CDEV_V1
2212 /* must be after kfifo check so watch_abi_version is set */
2213 if (atomic_read(&cdev->watch_abi_version) == 2)
2214 event_size = sizeof(struct gpio_v2_line_info_changed);
2216 event_size = sizeof(struct gpioline_info_changed);
2217 if (count < event_size) {
2218 spin_unlock(&cdev->wait.lock);
2222 ret = kfifo_out(&cdev->events, &event, 1);
2223 spin_unlock(&cdev->wait.lock);
2227 /* We should never get here. See lineevent_read(). */
2230 #ifdef CONFIG_GPIO_CDEV_V1
2231 if (event_size == sizeof(struct gpio_v2_line_info_changed)) {
2232 if (copy_to_user(buf + bytes_read, &event, event_size))
2235 struct gpioline_info_changed event_v1;
2237 gpio_v2_line_info_changed_to_v1(&event, &event_v1);
2238 if (copy_to_user(buf + bytes_read, &event_v1,
2243 if (copy_to_user(buf + bytes_read, &event, event_size))
2246 bytes_read += event_size;
2247 } while (count >= bytes_read + sizeof(event));
2253 * gpio_chrdev_open() - open the chardev for ioctl operations
2254 * @inode: inode for this chardev
2255 * @file: file struct for storing private data
2256 * Returns 0 on success
2258 static int gpio_chrdev_open(struct inode *inode, struct file *file)
2260 struct gpio_device *gdev = container_of(inode->i_cdev,
2261 struct gpio_device, chrdev);
2262 struct gpio_chardev_data *cdev;
2265 /* Fail on open if the backing gpiochip is gone */
2269 cdev = kzalloc(sizeof(*cdev), GFP_KERNEL);
2273 cdev->watched_lines = bitmap_zalloc(gdev->chip->ngpio, GFP_KERNEL);
2274 if (!cdev->watched_lines)
2277 init_waitqueue_head(&cdev->wait);
2278 INIT_KFIFO(cdev->events);
2281 cdev->lineinfo_changed_nb.notifier_call = lineinfo_changed_notify;
2282 ret = blocking_notifier_chain_register(&gdev->notifier,
2283 &cdev->lineinfo_changed_nb);
2285 goto out_free_bitmap;
2287 get_device(&gdev->dev);
2288 file->private_data = cdev;
2290 ret = nonseekable_open(inode, file);
2292 goto out_unregister_notifier;
2296 out_unregister_notifier:
2297 blocking_notifier_chain_unregister(&gdev->notifier,
2298 &cdev->lineinfo_changed_nb);
2300 bitmap_free(cdev->watched_lines);
2307 * gpio_chrdev_release() - close chardev after ioctl operations
2308 * @inode: inode for this chardev
2309 * @file: file struct for storing private data
2310 * Returns 0 on success
2312 static int gpio_chrdev_release(struct inode *inode, struct file *file)
2314 struct gpio_chardev_data *cdev = file->private_data;
2315 struct gpio_device *gdev = cdev->gdev;
2317 bitmap_free(cdev->watched_lines);
2318 blocking_notifier_chain_unregister(&gdev->notifier,
2319 &cdev->lineinfo_changed_nb);
2320 put_device(&gdev->dev);
2326 static const struct file_operations gpio_fileops = {
2327 .release = gpio_chrdev_release,
2328 .open = gpio_chrdev_open,
2329 .poll = lineinfo_watch_poll,
2330 .read = lineinfo_watch_read,
2331 .owner = THIS_MODULE,
2332 .llseek = no_llseek,
2333 .unlocked_ioctl = gpio_ioctl,
2334 #ifdef CONFIG_COMPAT
2335 .compat_ioctl = gpio_ioctl_compat,
2339 int gpiolib_cdev_register(struct gpio_device *gdev, dev_t devt)
2343 cdev_init(&gdev->chrdev, &gpio_fileops);
2344 gdev->chrdev.owner = THIS_MODULE;
2345 gdev->dev.devt = MKDEV(MAJOR(devt), gdev->id);
2347 ret = cdev_device_add(&gdev->chrdev, &gdev->dev);
2351 chip_dbg(gdev->chip, "added GPIO chardev (%d:%d)\n",
2352 MAJOR(devt), gdev->id);
2357 void gpiolib_cdev_unregister(struct gpio_device *gdev)
2359 cdev_device_del(&gdev->chrdev, &gdev->dev);