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/hte.h>
16 #include <linux/interrupt.h>
17 #include <linux/irqreturn.h>
18 #include <linux/kernel.h>
19 #include <linux/kfifo.h>
20 #include <linux/module.h>
21 #include <linux/mutex.h>
22 #include <linux/pinctrl/consumer.h>
23 #include <linux/poll.h>
24 #include <linux/seq_file.h>
25 #include <linux/spinlock.h>
26 #include <linux/timekeeping.h>
27 #include <linux/uaccess.h>
28 #include <linux/workqueue.h>
30 #include <uapi/linux/gpio.h>
33 #include "gpiolib-cdev.h"
36 * Array sizes must ensure 64-bit alignment and not create holes in the
39 static_assert(IS_ALIGNED(GPIO_V2_LINES_MAX, 2));
40 static_assert(IS_ALIGNED(GPIO_MAX_NAME_SIZE, 8));
43 * Check that uAPI structs are 64-bit aligned for 32/64-bit compatibility
45 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_attribute), 8));
46 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_config_attribute), 8));
47 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_config), 8));
48 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_request), 8));
49 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_info), 8));
50 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_info_changed), 8));
51 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_event), 8));
52 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_values), 8));
54 /* Character device interface to GPIO.
56 * The GPIO character device, /dev/gpiochipN, provides userspace an
57 * interface to gpiolib GPIOs via ioctl()s.
60 typedef __poll_t (*poll_fn)(struct file *, struct poll_table_struct *);
61 typedef long (*ioctl_fn)(struct file *, unsigned int, unsigned long);
62 typedef ssize_t (*read_fn)(struct file *, char __user *,
63 size_t count, loff_t *);
65 static __poll_t call_poll_locked(struct file *file,
66 struct poll_table_struct *wait,
67 struct gpio_device *gdev, poll_fn func)
71 down_read(&gdev->sem);
72 ret = func(file, wait);
78 static long call_ioctl_locked(struct file *file, unsigned int cmd,
79 unsigned long arg, struct gpio_device *gdev,
84 down_read(&gdev->sem);
85 ret = func(file, cmd, arg);
91 static ssize_t call_read_locked(struct file *file, char __user *buf,
92 size_t count, loff_t *f_ps,
93 struct gpio_device *gdev, read_fn func)
97 down_read(&gdev->sem);
98 ret = func(file, buf, count, f_ps);
105 * GPIO line handle management
108 #ifdef CONFIG_GPIO_CDEV_V1
110 * struct linehandle_state - contains the state of a userspace handle
111 * @gdev: the GPIO device the handle pertains to
112 * @label: consumer label used to tag descriptors
113 * @descs: the GPIO descriptors held by this handle
114 * @num_descs: the number of descriptors held in the descs array
116 struct linehandle_state {
117 struct gpio_device *gdev;
119 struct gpio_desc *descs[GPIOHANDLES_MAX];
123 #define GPIOHANDLE_REQUEST_VALID_FLAGS \
124 (GPIOHANDLE_REQUEST_INPUT | \
125 GPIOHANDLE_REQUEST_OUTPUT | \
126 GPIOHANDLE_REQUEST_ACTIVE_LOW | \
127 GPIOHANDLE_REQUEST_BIAS_PULL_UP | \
128 GPIOHANDLE_REQUEST_BIAS_PULL_DOWN | \
129 GPIOHANDLE_REQUEST_BIAS_DISABLE | \
130 GPIOHANDLE_REQUEST_OPEN_DRAIN | \
131 GPIOHANDLE_REQUEST_OPEN_SOURCE)
133 static int linehandle_validate_flags(u32 flags)
135 /* Return an error if an unknown flag is set */
136 if (flags & ~GPIOHANDLE_REQUEST_VALID_FLAGS)
140 * Do not allow both INPUT & OUTPUT flags to be set as they are
143 if ((flags & GPIOHANDLE_REQUEST_INPUT) &&
144 (flags & GPIOHANDLE_REQUEST_OUTPUT))
148 * Do not allow OPEN_SOURCE & OPEN_DRAIN flags in a single request. If
149 * the hardware actually supports enabling both at the same time the
150 * electrical result would be disastrous.
152 if ((flags & GPIOHANDLE_REQUEST_OPEN_DRAIN) &&
153 (flags & GPIOHANDLE_REQUEST_OPEN_SOURCE))
156 /* OPEN_DRAIN and OPEN_SOURCE flags only make sense for output mode. */
157 if (!(flags & GPIOHANDLE_REQUEST_OUTPUT) &&
158 ((flags & GPIOHANDLE_REQUEST_OPEN_DRAIN) ||
159 (flags & GPIOHANDLE_REQUEST_OPEN_SOURCE)))
162 /* Bias flags only allowed for input or output mode. */
163 if (!((flags & GPIOHANDLE_REQUEST_INPUT) ||
164 (flags & GPIOHANDLE_REQUEST_OUTPUT)) &&
165 ((flags & GPIOHANDLE_REQUEST_BIAS_DISABLE) ||
166 (flags & GPIOHANDLE_REQUEST_BIAS_PULL_UP) ||
167 (flags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN)))
170 /* Only one bias flag can be set. */
171 if (((flags & GPIOHANDLE_REQUEST_BIAS_DISABLE) &&
172 (flags & (GPIOHANDLE_REQUEST_BIAS_PULL_DOWN |
173 GPIOHANDLE_REQUEST_BIAS_PULL_UP))) ||
174 ((flags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN) &&
175 (flags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)))
181 static void linehandle_flags_to_desc_flags(u32 lflags, unsigned long *flagsp)
183 assign_bit(FLAG_ACTIVE_LOW, flagsp,
184 lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW);
185 assign_bit(FLAG_OPEN_DRAIN, flagsp,
186 lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN);
187 assign_bit(FLAG_OPEN_SOURCE, flagsp,
188 lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE);
189 assign_bit(FLAG_PULL_UP, flagsp,
190 lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP);
191 assign_bit(FLAG_PULL_DOWN, flagsp,
192 lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN);
193 assign_bit(FLAG_BIAS_DISABLE, flagsp,
194 lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE);
197 static long linehandle_set_config(struct linehandle_state *lh,
200 struct gpiohandle_config gcnf;
201 struct gpio_desc *desc;
205 if (copy_from_user(&gcnf, ip, sizeof(gcnf)))
209 ret = linehandle_validate_flags(lflags);
213 for (i = 0; i < lh->num_descs; i++) {
215 linehandle_flags_to_desc_flags(gcnf.flags, &desc->flags);
218 * Lines have to be requested explicitly for input
219 * or output, else the line will be treated "as is".
221 if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
222 int val = !!gcnf.default_values[i];
224 ret = gpiod_direction_output(desc, val);
227 } else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
228 ret = gpiod_direction_input(desc);
233 gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_CONFIG);
238 static long linehandle_ioctl_unlocked(struct file *file, unsigned int cmd,
241 struct linehandle_state *lh = file->private_data;
242 void __user *ip = (void __user *)arg;
243 struct gpiohandle_data ghd;
244 DECLARE_BITMAP(vals, GPIOHANDLES_MAX);
252 case GPIOHANDLE_GET_LINE_VALUES_IOCTL:
253 /* NOTE: It's okay to read values of output lines */
254 ret = gpiod_get_array_value_complex(false, true,
255 lh->num_descs, lh->descs,
260 memset(&ghd, 0, sizeof(ghd));
261 for (i = 0; i < lh->num_descs; i++)
262 ghd.values[i] = test_bit(i, vals);
264 if (copy_to_user(ip, &ghd, sizeof(ghd)))
268 case GPIOHANDLE_SET_LINE_VALUES_IOCTL:
270 * All line descriptors were created at once with the same
271 * flags so just check if the first one is really output.
273 if (!test_bit(FLAG_IS_OUT, &lh->descs[0]->flags))
276 if (copy_from_user(&ghd, ip, sizeof(ghd)))
279 /* Clamp all values to [0,1] */
280 for (i = 0; i < lh->num_descs; i++)
281 __assign_bit(i, vals, ghd.values[i]);
283 /* Reuse the array setting function */
284 return gpiod_set_array_value_complex(false,
290 case GPIOHANDLE_SET_CONFIG_IOCTL:
291 return linehandle_set_config(lh, ip);
297 static long linehandle_ioctl(struct file *file, unsigned int cmd,
300 struct linehandle_state *lh = file->private_data;
302 return call_ioctl_locked(file, cmd, arg, lh->gdev,
303 linehandle_ioctl_unlocked);
307 static long linehandle_ioctl_compat(struct file *file, unsigned int cmd,
310 return linehandle_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
314 static void linehandle_free(struct linehandle_state *lh)
318 for (i = 0; i < lh->num_descs; i++)
320 gpiod_free(lh->descs[i]);
322 gpio_device_put(lh->gdev);
326 static int linehandle_release(struct inode *inode, struct file *file)
328 linehandle_free(file->private_data);
332 static const struct file_operations linehandle_fileops = {
333 .release = linehandle_release,
334 .owner = THIS_MODULE,
335 .llseek = noop_llseek,
336 .unlocked_ioctl = linehandle_ioctl,
338 .compat_ioctl = linehandle_ioctl_compat,
342 static int linehandle_create(struct gpio_device *gdev, void __user *ip)
344 struct gpiohandle_request handlereq;
345 struct linehandle_state *lh;
350 if (copy_from_user(&handlereq, ip, sizeof(handlereq)))
352 if ((handlereq.lines == 0) || (handlereq.lines > GPIOHANDLES_MAX))
355 lflags = handlereq.flags;
357 ret = linehandle_validate_flags(lflags);
361 lh = kzalloc(sizeof(*lh), GFP_KERNEL);
364 lh->gdev = gpio_device_get(gdev);
366 if (handlereq.consumer_label[0] != '\0') {
367 /* label is only initialized if consumer_label is set */
368 lh->label = kstrndup(handlereq.consumer_label,
369 sizeof(handlereq.consumer_label) - 1,
377 lh->num_descs = handlereq.lines;
379 /* Request each GPIO */
380 for (i = 0; i < handlereq.lines; i++) {
381 u32 offset = handlereq.lineoffsets[i];
382 struct gpio_desc *desc = gpiochip_get_desc(gdev->chip, offset);
389 ret = gpiod_request_user(desc, lh->label);
393 linehandle_flags_to_desc_flags(handlereq.flags, &desc->flags);
395 ret = gpiod_set_transitory(desc, false);
400 * Lines have to be requested explicitly for input
401 * or output, else the line will be treated "as is".
403 if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
404 int val = !!handlereq.default_values[i];
406 ret = gpiod_direction_output(desc, val);
409 } else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
410 ret = gpiod_direction_input(desc);
415 gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_REQUESTED);
417 dev_dbg(&gdev->dev, "registered chardev handle for line %d\n",
421 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
427 file = anon_inode_getfile("gpio-linehandle",
430 O_RDONLY | O_CLOEXEC);
433 goto out_put_unused_fd;
437 if (copy_to_user(ip, &handlereq, sizeof(handlereq))) {
439 * fput() will trigger the release() callback, so do not go onto
440 * the regular error cleanup path here.
447 fd_install(fd, file);
449 dev_dbg(&gdev->dev, "registered chardev handle for %d lines\n",
460 #endif /* CONFIG_GPIO_CDEV_V1 */
463 * struct line - contains the state of a requested line
464 * @desc: the GPIO descriptor for this line.
465 * @req: the corresponding line request
466 * @irq: the interrupt triggered in response to events on this GPIO
467 * @edflags: the edge flags, GPIO_V2_LINE_FLAG_EDGE_RISING and/or
468 * GPIO_V2_LINE_FLAG_EDGE_FALLING, indicating the edge detection applied
469 * @timestamp_ns: cache for the timestamp storing it between hardirq and
470 * IRQ thread, used to bring the timestamp close to the actual event
471 * @req_seqno: the seqno for the current edge event in the sequence of
472 * events for the corresponding line request. This is drawn from the @req.
473 * @line_seqno: the seqno for the current edge event in the sequence of
474 * events for this line.
475 * @work: the worker that implements software debouncing
476 * @sw_debounced: flag indicating if the software debouncer is active
477 * @level: the current debounced physical level of the line
478 * @hdesc: the Hardware Timestamp Engine (HTE) descriptor
479 * @raw_level: the line level at the time of event
480 * @total_discard_seq: the running counter of the discarded events
481 * @last_seqno: the last sequence number before debounce period expires
484 struct gpio_desc *desc;
486 * -- edge detector specific fields --
491 * The flags for the active edge detector configuration.
493 * edflags is set by linereq_create(), linereq_free(), and
494 * linereq_set_config_unlocked(), which are themselves mutually
495 * exclusive, and is accessed by edge_irq_thread(),
496 * process_hw_ts_thread() and debounce_work_func(),
497 * which can all live with a slightly stale value.
501 * timestamp_ns and req_seqno are accessed only by
502 * edge_irq_handler() and edge_irq_thread(), which are themselves
503 * mutually exclusive, so no additional protection is necessary.
508 * line_seqno is accessed by either edge_irq_thread() or
509 * debounce_work_func(), which are themselves mutually exclusive,
510 * so no additional protection is necessary.
514 * -- debouncer specific fields --
516 struct delayed_work work;
518 * sw_debounce is accessed by linereq_set_config(), which is the
519 * only setter, and linereq_get_values(), which can live with a
520 * slightly stale value.
522 unsigned int sw_debounced;
524 * level is accessed by debounce_work_func(), which is the only
525 * setter, and linereq_get_values() which can live with a slightly
530 struct hte_ts_desc hdesc;
532 * HTE provider sets line level at the time of event. The valid
533 * value is 0 or 1 and negative value for an error.
537 * when sw_debounce is set on HTE enabled line, this is running
538 * counter of the discarded events.
540 u32 total_discard_seq;
542 * when sw_debounce is set on HTE enabled line, this variable records
543 * last sequence number before debounce period expires.
546 #endif /* CONFIG_HTE */
550 * struct linereq - contains the state of a userspace line request
551 * @gdev: the GPIO device the line request pertains to
552 * @label: consumer label used to tag GPIO descriptors
553 * @num_lines: the number of lines in the lines array
554 * @wait: wait queue that handles blocking reads of events
555 * @device_unregistered_nb: notifier block for receiving gdev unregister events
556 * @event_buffer_size: the number of elements allocated in @events
557 * @events: KFIFO for the GPIO events
558 * @seqno: the sequence number for edge events generated on all lines in
559 * this line request. Note that this is not used when @num_lines is 1, as
560 * the line_seqno is then the same and is cheaper to calculate.
561 * @config_mutex: mutex for serializing ioctl() calls to ensure consistency
562 * of configuration, particularly multi-step accesses to desc flags.
563 * @lines: the lines held by this line request, with @num_lines elements.
566 struct gpio_device *gdev;
569 wait_queue_head_t wait;
570 struct notifier_block device_unregistered_nb;
571 u32 event_buffer_size;
572 DECLARE_KFIFO_PTR(events, struct gpio_v2_line_event);
574 struct mutex config_mutex;
578 #define GPIO_V2_LINE_BIAS_FLAGS \
579 (GPIO_V2_LINE_FLAG_BIAS_PULL_UP | \
580 GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN | \
581 GPIO_V2_LINE_FLAG_BIAS_DISABLED)
583 #define GPIO_V2_LINE_DIRECTION_FLAGS \
584 (GPIO_V2_LINE_FLAG_INPUT | \
585 GPIO_V2_LINE_FLAG_OUTPUT)
587 #define GPIO_V2_LINE_DRIVE_FLAGS \
588 (GPIO_V2_LINE_FLAG_OPEN_DRAIN | \
589 GPIO_V2_LINE_FLAG_OPEN_SOURCE)
591 #define GPIO_V2_LINE_EDGE_FLAGS \
592 (GPIO_V2_LINE_FLAG_EDGE_RISING | \
593 GPIO_V2_LINE_FLAG_EDGE_FALLING)
595 #define GPIO_V2_LINE_FLAG_EDGE_BOTH GPIO_V2_LINE_EDGE_FLAGS
597 #define GPIO_V2_LINE_VALID_FLAGS \
598 (GPIO_V2_LINE_FLAG_ACTIVE_LOW | \
599 GPIO_V2_LINE_DIRECTION_FLAGS | \
600 GPIO_V2_LINE_DRIVE_FLAGS | \
601 GPIO_V2_LINE_EDGE_FLAGS | \
602 GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME | \
603 GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE | \
604 GPIO_V2_LINE_BIAS_FLAGS)
606 /* subset of flags relevant for edge detector configuration */
607 #define GPIO_V2_LINE_EDGE_DETECTOR_FLAGS \
608 (GPIO_V2_LINE_FLAG_ACTIVE_LOW | \
609 GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE | \
610 GPIO_V2_LINE_EDGE_FLAGS)
612 static int linereq_unregistered_notify(struct notifier_block *nb,
613 unsigned long action, void *data)
615 struct linereq *lr = container_of(nb, struct linereq,
616 device_unregistered_nb);
618 wake_up_poll(&lr->wait, EPOLLIN | EPOLLERR);
623 static void linereq_put_event(struct linereq *lr,
624 struct gpio_v2_line_event *le)
626 bool overflow = false;
628 spin_lock(&lr->wait.lock);
629 if (kfifo_is_full(&lr->events)) {
631 kfifo_skip(&lr->events);
633 kfifo_in(&lr->events, le, 1);
634 spin_unlock(&lr->wait.lock);
636 wake_up_poll(&lr->wait, EPOLLIN);
638 pr_debug_ratelimited("event FIFO is full - event dropped\n");
641 static u64 line_event_timestamp(struct line *line)
643 if (test_bit(FLAG_EVENT_CLOCK_REALTIME, &line->desc->flags))
644 return ktime_get_real_ns();
645 else if (IS_ENABLED(CONFIG_HTE) &&
646 test_bit(FLAG_EVENT_CLOCK_HTE, &line->desc->flags))
647 return line->timestamp_ns;
649 return ktime_get_ns();
652 static u32 line_event_id(int level)
654 return level ? GPIO_V2_LINE_EVENT_RISING_EDGE :
655 GPIO_V2_LINE_EVENT_FALLING_EDGE;
660 static enum hte_return process_hw_ts_thread(void *p)
664 struct gpio_v2_line_event le;
669 return HTE_CB_HANDLED;
674 memset(&le, 0, sizeof(le));
676 le.timestamp_ns = line->timestamp_ns;
677 edflags = READ_ONCE(line->edflags);
679 switch (edflags & GPIO_V2_LINE_EDGE_FLAGS) {
680 case GPIO_V2_LINE_FLAG_EDGE_BOTH:
681 level = (line->raw_level >= 0) ?
683 gpiod_get_raw_value_cansleep(line->desc);
685 if (edflags & GPIO_V2_LINE_FLAG_ACTIVE_LOW)
688 le.id = line_event_id(level);
690 case GPIO_V2_LINE_FLAG_EDGE_RISING:
691 le.id = GPIO_V2_LINE_EVENT_RISING_EDGE;
693 case GPIO_V2_LINE_FLAG_EDGE_FALLING:
694 le.id = GPIO_V2_LINE_EVENT_FALLING_EDGE;
697 return HTE_CB_HANDLED;
699 le.line_seqno = line->line_seqno;
700 le.seqno = (lr->num_lines == 1) ? le.line_seqno : line->req_seqno;
701 le.offset = gpio_chip_hwgpio(line->desc);
703 linereq_put_event(lr, &le);
705 return HTE_CB_HANDLED;
708 static enum hte_return process_hw_ts(struct hte_ts_data *ts, void *p)
715 return HTE_CB_HANDLED;
718 line->timestamp_ns = ts->tsc;
719 line->raw_level = ts->raw_level;
722 if (READ_ONCE(line->sw_debounced)) {
723 line->total_discard_seq++;
724 line->last_seqno = ts->seq;
725 mod_delayed_work(system_wq, &line->work,
726 usecs_to_jiffies(READ_ONCE(line->desc->debounce_period_us)));
728 if (unlikely(ts->seq < line->line_seqno))
729 return HTE_CB_HANDLED;
731 diff_seqno = ts->seq - line->line_seqno;
732 line->line_seqno = ts->seq;
733 if (lr->num_lines != 1)
734 line->req_seqno = atomic_add_return(diff_seqno,
737 return HTE_RUN_SECOND_CB;
740 return HTE_CB_HANDLED;
743 static int hte_edge_setup(struct line *line, u64 eflags)
746 unsigned long flags = 0;
747 struct hte_ts_desc *hdesc = &line->hdesc;
749 if (eflags & GPIO_V2_LINE_FLAG_EDGE_RISING)
750 flags |= test_bit(FLAG_ACTIVE_LOW, &line->desc->flags) ?
751 HTE_FALLING_EDGE_TS :
753 if (eflags & GPIO_V2_LINE_FLAG_EDGE_FALLING)
754 flags |= test_bit(FLAG_ACTIVE_LOW, &line->desc->flags) ?
758 line->total_discard_seq = 0;
760 hte_init_line_attr(hdesc, desc_to_gpio(line->desc), flags, NULL,
763 ret = hte_ts_get(NULL, hdesc, 0);
767 return hte_request_ts_ns(hdesc, process_hw_ts, process_hw_ts_thread,
773 static int hte_edge_setup(struct line *line, u64 eflags)
777 #endif /* CONFIG_HTE */
779 static irqreturn_t edge_irq_thread(int irq, void *p)
781 struct line *line = p;
782 struct linereq *lr = line->req;
783 struct gpio_v2_line_event le;
785 /* Do not leak kernel stack to userspace */
786 memset(&le, 0, sizeof(le));
788 if (line->timestamp_ns) {
789 le.timestamp_ns = line->timestamp_ns;
792 * We may be running from a nested threaded interrupt in
793 * which case we didn't get the timestamp from
794 * edge_irq_handler().
796 le.timestamp_ns = line_event_timestamp(line);
797 if (lr->num_lines != 1)
798 line->req_seqno = atomic_inc_return(&lr->seqno);
800 line->timestamp_ns = 0;
802 switch (READ_ONCE(line->edflags) & GPIO_V2_LINE_EDGE_FLAGS) {
803 case GPIO_V2_LINE_FLAG_EDGE_BOTH:
804 le.id = line_event_id(gpiod_get_value_cansleep(line->desc));
806 case GPIO_V2_LINE_FLAG_EDGE_RISING:
807 le.id = GPIO_V2_LINE_EVENT_RISING_EDGE;
809 case GPIO_V2_LINE_FLAG_EDGE_FALLING:
810 le.id = GPIO_V2_LINE_EVENT_FALLING_EDGE;
816 le.line_seqno = line->line_seqno;
817 le.seqno = (lr->num_lines == 1) ? le.line_seqno : line->req_seqno;
818 le.offset = gpio_chip_hwgpio(line->desc);
820 linereq_put_event(lr, &le);
825 static irqreturn_t edge_irq_handler(int irq, void *p)
827 struct line *line = p;
828 struct linereq *lr = line->req;
831 * Just store the timestamp in hardirq context so we get it as
832 * close in time as possible to the actual event.
834 line->timestamp_ns = line_event_timestamp(line);
836 if (lr->num_lines != 1)
837 line->req_seqno = atomic_inc_return(&lr->seqno);
839 return IRQ_WAKE_THREAD;
843 * returns the current debounced logical value.
845 static bool debounced_value(struct line *line)
850 * minor race - debouncer may be stopped here, so edge_detector_stop()
851 * must leave the value unchanged so the following will read the level
852 * from when the debouncer was last running.
854 value = READ_ONCE(line->level);
856 if (test_bit(FLAG_ACTIVE_LOW, &line->desc->flags))
862 static irqreturn_t debounce_irq_handler(int irq, void *p)
864 struct line *line = p;
866 mod_delayed_work(system_wq, &line->work,
867 usecs_to_jiffies(READ_ONCE(line->desc->debounce_period_us)));
872 static void debounce_work_func(struct work_struct *work)
874 struct gpio_v2_line_event le;
875 struct line *line = container_of(work, struct line, work.work);
877 u64 eflags, edflags = READ_ONCE(line->edflags);
882 if (edflags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE)
883 level = line->raw_level;
886 level = gpiod_get_raw_value_cansleep(line->desc);
888 pr_debug_ratelimited("debouncer failed to read line value\n");
892 if (READ_ONCE(line->level) == level)
895 WRITE_ONCE(line->level, level);
897 /* -- edge detection -- */
898 eflags = edflags & GPIO_V2_LINE_EDGE_FLAGS;
902 /* switch from physical level to logical - if they differ */
903 if (edflags & GPIO_V2_LINE_FLAG_ACTIVE_LOW)
906 /* ignore edges that are not being monitored */
907 if (((eflags == GPIO_V2_LINE_FLAG_EDGE_RISING) && !level) ||
908 ((eflags == GPIO_V2_LINE_FLAG_EDGE_FALLING) && level))
911 /* Do not leak kernel stack to userspace */
912 memset(&le, 0, sizeof(le));
915 le.timestamp_ns = line_event_timestamp(line);
916 le.offset = gpio_chip_hwgpio(line->desc);
918 if (edflags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE) {
919 /* discard events except the last one */
920 line->total_discard_seq -= 1;
921 diff_seqno = line->last_seqno - line->total_discard_seq -
923 line->line_seqno = line->last_seqno - line->total_discard_seq;
924 le.line_seqno = line->line_seqno;
925 le.seqno = (lr->num_lines == 1) ?
926 le.line_seqno : atomic_add_return(diff_seqno, &lr->seqno);
928 #endif /* CONFIG_HTE */
931 le.line_seqno = line->line_seqno;
932 le.seqno = (lr->num_lines == 1) ?
933 le.line_seqno : atomic_inc_return(&lr->seqno);
936 le.id = line_event_id(level);
938 linereq_put_event(lr, &le);
941 static int debounce_setup(struct line *line, unsigned int debounce_period_us)
943 unsigned long irqflags;
947 ret = gpiod_set_debounce(line->desc, debounce_period_us);
949 WRITE_ONCE(line->desc->debounce_period_us, debounce_period_us);
952 if (ret != -ENOTSUPP)
955 if (debounce_period_us) {
956 /* setup software debounce */
957 level = gpiod_get_raw_value_cansleep(line->desc);
961 if (!(IS_ENABLED(CONFIG_HTE) &&
962 test_bit(FLAG_EVENT_CLOCK_HTE, &line->desc->flags))) {
963 irq = gpiod_to_irq(line->desc);
967 irqflags = IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING;
968 ret = request_irq(irq, debounce_irq_handler, irqflags,
969 line->req->label, line);
974 ret = hte_edge_setup(line, GPIO_V2_LINE_FLAG_EDGE_BOTH);
979 WRITE_ONCE(line->level, level);
980 WRITE_ONCE(line->sw_debounced, 1);
985 static bool gpio_v2_line_config_debounced(struct gpio_v2_line_config *lc,
986 unsigned int line_idx)
989 u64 mask = BIT_ULL(line_idx);
991 for (i = 0; i < lc->num_attrs; i++) {
992 if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_DEBOUNCE) &&
993 (lc->attrs[i].mask & mask))
999 static u32 gpio_v2_line_config_debounce_period(struct gpio_v2_line_config *lc,
1000 unsigned int line_idx)
1003 u64 mask = BIT_ULL(line_idx);
1005 for (i = 0; i < lc->num_attrs; i++) {
1006 if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_DEBOUNCE) &&
1007 (lc->attrs[i].mask & mask))
1008 return lc->attrs[i].attr.debounce_period_us;
1013 static void edge_detector_stop(struct line *line)
1016 free_irq(line->irq, line);
1021 if (READ_ONCE(line->edflags) & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE)
1022 hte_ts_put(&line->hdesc);
1025 cancel_delayed_work_sync(&line->work);
1026 WRITE_ONCE(line->sw_debounced, 0);
1027 WRITE_ONCE(line->edflags, 0);
1029 WRITE_ONCE(line->desc->debounce_period_us, 0);
1030 /* do not change line->level - see comment in debounced_value() */
1033 static int edge_detector_setup(struct line *line,
1034 struct gpio_v2_line_config *lc,
1035 unsigned int line_idx, u64 edflags)
1037 u32 debounce_period_us;
1038 unsigned long irqflags = 0;
1042 eflags = edflags & GPIO_V2_LINE_EDGE_FLAGS;
1043 if (eflags && !kfifo_initialized(&line->req->events)) {
1044 ret = kfifo_alloc(&line->req->events,
1045 line->req->event_buffer_size, GFP_KERNEL);
1049 if (gpio_v2_line_config_debounced(lc, line_idx)) {
1050 debounce_period_us = gpio_v2_line_config_debounce_period(lc, line_idx);
1051 ret = debounce_setup(line, debounce_period_us);
1054 WRITE_ONCE(line->desc->debounce_period_us, debounce_period_us);
1057 /* detection disabled or sw debouncer will provide edge detection */
1058 if (!eflags || READ_ONCE(line->sw_debounced))
1061 if (IS_ENABLED(CONFIG_HTE) &&
1062 (edflags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE))
1063 return hte_edge_setup(line, edflags);
1065 irq = gpiod_to_irq(line->desc);
1069 if (eflags & GPIO_V2_LINE_FLAG_EDGE_RISING)
1070 irqflags |= test_bit(FLAG_ACTIVE_LOW, &line->desc->flags) ?
1071 IRQF_TRIGGER_FALLING : IRQF_TRIGGER_RISING;
1072 if (eflags & GPIO_V2_LINE_FLAG_EDGE_FALLING)
1073 irqflags |= test_bit(FLAG_ACTIVE_LOW, &line->desc->flags) ?
1074 IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING;
1075 irqflags |= IRQF_ONESHOT;
1077 /* Request a thread to read the events */
1078 ret = request_threaded_irq(irq, edge_irq_handler, edge_irq_thread,
1079 irqflags, line->req->label, line);
1087 static int edge_detector_update(struct line *line,
1088 struct gpio_v2_line_config *lc,
1089 unsigned int line_idx, u64 edflags)
1091 u64 active_edflags = READ_ONCE(line->edflags);
1092 unsigned int debounce_period_us =
1093 gpio_v2_line_config_debounce_period(lc, line_idx);
1095 if ((active_edflags == edflags) &&
1096 (READ_ONCE(line->desc->debounce_period_us) == debounce_period_us))
1099 /* sw debounced and still will be...*/
1100 if (debounce_period_us && READ_ONCE(line->sw_debounced)) {
1101 WRITE_ONCE(line->desc->debounce_period_us, debounce_period_us);
1105 /* reconfiguring edge detection or sw debounce being disabled */
1106 if ((line->irq && !READ_ONCE(line->sw_debounced)) ||
1107 (active_edflags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE) ||
1108 (!debounce_period_us && READ_ONCE(line->sw_debounced)))
1109 edge_detector_stop(line);
1111 return edge_detector_setup(line, lc, line_idx, edflags);
1114 static u64 gpio_v2_line_config_flags(struct gpio_v2_line_config *lc,
1115 unsigned int line_idx)
1118 u64 mask = BIT_ULL(line_idx);
1120 for (i = 0; i < lc->num_attrs; i++) {
1121 if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_FLAGS) &&
1122 (lc->attrs[i].mask & mask))
1123 return lc->attrs[i].attr.flags;
1128 static int gpio_v2_line_config_output_value(struct gpio_v2_line_config *lc,
1129 unsigned int line_idx)
1132 u64 mask = BIT_ULL(line_idx);
1134 for (i = 0; i < lc->num_attrs; i++) {
1135 if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_OUTPUT_VALUES) &&
1136 (lc->attrs[i].mask & mask))
1137 return !!(lc->attrs[i].attr.values & mask);
1142 static int gpio_v2_line_flags_validate(u64 flags)
1144 /* Return an error if an unknown flag is set */
1145 if (flags & ~GPIO_V2_LINE_VALID_FLAGS)
1148 if (!IS_ENABLED(CONFIG_HTE) &&
1149 (flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE))
1153 * Do not allow both INPUT and OUTPUT flags to be set as they are
1156 if ((flags & GPIO_V2_LINE_FLAG_INPUT) &&
1157 (flags & GPIO_V2_LINE_FLAG_OUTPUT))
1160 /* Only allow one event clock source */
1161 if (IS_ENABLED(CONFIG_HTE) &&
1162 (flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME) &&
1163 (flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE))
1166 /* Edge detection requires explicit input. */
1167 if ((flags & GPIO_V2_LINE_EDGE_FLAGS) &&
1168 !(flags & GPIO_V2_LINE_FLAG_INPUT))
1172 * Do not allow OPEN_SOURCE and OPEN_DRAIN flags in a single
1173 * request. If the hardware actually supports enabling both at the
1174 * same time the electrical result would be disastrous.
1176 if ((flags & GPIO_V2_LINE_FLAG_OPEN_DRAIN) &&
1177 (flags & GPIO_V2_LINE_FLAG_OPEN_SOURCE))
1180 /* Drive requires explicit output direction. */
1181 if ((flags & GPIO_V2_LINE_DRIVE_FLAGS) &&
1182 !(flags & GPIO_V2_LINE_FLAG_OUTPUT))
1185 /* Bias requires explicit direction. */
1186 if ((flags & GPIO_V2_LINE_BIAS_FLAGS) &&
1187 !(flags & GPIO_V2_LINE_DIRECTION_FLAGS))
1190 /* Only one bias flag can be set. */
1191 if (((flags & GPIO_V2_LINE_FLAG_BIAS_DISABLED) &&
1192 (flags & (GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN |
1193 GPIO_V2_LINE_FLAG_BIAS_PULL_UP))) ||
1194 ((flags & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN) &&
1195 (flags & GPIO_V2_LINE_FLAG_BIAS_PULL_UP)))
1201 static int gpio_v2_line_config_validate(struct gpio_v2_line_config *lc,
1202 unsigned int num_lines)
1208 if (lc->num_attrs > GPIO_V2_LINE_NUM_ATTRS_MAX)
1211 if (memchr_inv(lc->padding, 0, sizeof(lc->padding)))
1214 for (i = 0; i < num_lines; i++) {
1215 flags = gpio_v2_line_config_flags(lc, i);
1216 ret = gpio_v2_line_flags_validate(flags);
1220 /* debounce requires explicit input */
1221 if (gpio_v2_line_config_debounced(lc, i) &&
1222 !(flags & GPIO_V2_LINE_FLAG_INPUT))
1228 static void gpio_v2_line_config_flags_to_desc_flags(u64 flags,
1229 unsigned long *flagsp)
1231 assign_bit(FLAG_ACTIVE_LOW, flagsp,
1232 flags & GPIO_V2_LINE_FLAG_ACTIVE_LOW);
1234 if (flags & GPIO_V2_LINE_FLAG_OUTPUT)
1235 set_bit(FLAG_IS_OUT, flagsp);
1236 else if (flags & GPIO_V2_LINE_FLAG_INPUT)
1237 clear_bit(FLAG_IS_OUT, flagsp);
1239 assign_bit(FLAG_EDGE_RISING, flagsp,
1240 flags & GPIO_V2_LINE_FLAG_EDGE_RISING);
1241 assign_bit(FLAG_EDGE_FALLING, flagsp,
1242 flags & GPIO_V2_LINE_FLAG_EDGE_FALLING);
1244 assign_bit(FLAG_OPEN_DRAIN, flagsp,
1245 flags & GPIO_V2_LINE_FLAG_OPEN_DRAIN);
1246 assign_bit(FLAG_OPEN_SOURCE, flagsp,
1247 flags & GPIO_V2_LINE_FLAG_OPEN_SOURCE);
1249 assign_bit(FLAG_PULL_UP, flagsp,
1250 flags & GPIO_V2_LINE_FLAG_BIAS_PULL_UP);
1251 assign_bit(FLAG_PULL_DOWN, flagsp,
1252 flags & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN);
1253 assign_bit(FLAG_BIAS_DISABLE, flagsp,
1254 flags & GPIO_V2_LINE_FLAG_BIAS_DISABLED);
1256 assign_bit(FLAG_EVENT_CLOCK_REALTIME, flagsp,
1257 flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME);
1258 assign_bit(FLAG_EVENT_CLOCK_HTE, flagsp,
1259 flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE);
1262 static long linereq_get_values(struct linereq *lr, void __user *ip)
1264 struct gpio_v2_line_values lv;
1265 DECLARE_BITMAP(vals, GPIO_V2_LINES_MAX);
1266 struct gpio_desc **descs;
1267 unsigned int i, didx, num_get;
1271 /* NOTE: It's ok to read values of output lines. */
1272 if (copy_from_user(&lv, ip, sizeof(lv)))
1275 for (num_get = 0, i = 0; i < lr->num_lines; i++) {
1276 if (lv.mask & BIT_ULL(i)) {
1278 descs = &lr->lines[i].desc;
1286 descs = kmalloc_array(num_get, sizeof(*descs), GFP_KERNEL);
1289 for (didx = 0, i = 0; i < lr->num_lines; i++) {
1290 if (lv.mask & BIT_ULL(i)) {
1291 descs[didx] = lr->lines[i].desc;
1296 ret = gpiod_get_array_value_complex(false, true, num_get,
1305 for (didx = 0, i = 0; i < lr->num_lines; i++) {
1306 if (lv.mask & BIT_ULL(i)) {
1307 if (lr->lines[i].sw_debounced)
1308 val = debounced_value(&lr->lines[i]);
1310 val = test_bit(didx, vals);
1312 lv.bits |= BIT_ULL(i);
1317 if (copy_to_user(ip, &lv, sizeof(lv)))
1323 static long linereq_set_values_unlocked(struct linereq *lr,
1324 struct gpio_v2_line_values *lv)
1326 DECLARE_BITMAP(vals, GPIO_V2_LINES_MAX);
1327 struct gpio_desc **descs;
1328 unsigned int i, didx, num_set;
1331 bitmap_zero(vals, GPIO_V2_LINES_MAX);
1332 for (num_set = 0, i = 0; i < lr->num_lines; i++) {
1333 if (lv->mask & BIT_ULL(i)) {
1334 if (!test_bit(FLAG_IS_OUT, &lr->lines[i].desc->flags))
1336 if (lv->bits & BIT_ULL(i))
1337 __set_bit(num_set, vals);
1339 descs = &lr->lines[i].desc;
1346 /* build compacted desc array and values */
1347 descs = kmalloc_array(num_set, sizeof(*descs), GFP_KERNEL);
1350 for (didx = 0, i = 0; i < lr->num_lines; i++) {
1351 if (lv->mask & BIT_ULL(i)) {
1352 descs[didx] = lr->lines[i].desc;
1357 ret = gpiod_set_array_value_complex(false, true, num_set,
1365 static long linereq_set_values(struct linereq *lr, void __user *ip)
1367 struct gpio_v2_line_values lv;
1370 if (copy_from_user(&lv, ip, sizeof(lv)))
1373 mutex_lock(&lr->config_mutex);
1375 ret = linereq_set_values_unlocked(lr, &lv);
1377 mutex_unlock(&lr->config_mutex);
1382 static long linereq_set_config_unlocked(struct linereq *lr,
1383 struct gpio_v2_line_config *lc)
1385 struct gpio_desc *desc;
1391 for (i = 0; i < lr->num_lines; i++) {
1392 line = &lr->lines[i];
1393 desc = lr->lines[i].desc;
1394 flags = gpio_v2_line_config_flags(lc, i);
1395 gpio_v2_line_config_flags_to_desc_flags(flags, &desc->flags);
1396 edflags = flags & GPIO_V2_LINE_EDGE_DETECTOR_FLAGS;
1398 * Lines have to be requested explicitly for input
1399 * or output, else the line will be treated "as is".
1401 if (flags & GPIO_V2_LINE_FLAG_OUTPUT) {
1402 int val = gpio_v2_line_config_output_value(lc, i);
1404 edge_detector_stop(line);
1405 ret = gpiod_direction_output(desc, val);
1408 } else if (flags & GPIO_V2_LINE_FLAG_INPUT) {
1409 ret = gpiod_direction_input(desc);
1413 ret = edge_detector_update(line, lc, i, edflags);
1418 WRITE_ONCE(line->edflags, edflags);
1420 gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_CONFIG);
1425 static long linereq_set_config(struct linereq *lr, void __user *ip)
1427 struct gpio_v2_line_config lc;
1430 if (copy_from_user(&lc, ip, sizeof(lc)))
1433 ret = gpio_v2_line_config_validate(&lc, lr->num_lines);
1437 mutex_lock(&lr->config_mutex);
1439 ret = linereq_set_config_unlocked(lr, &lc);
1441 mutex_unlock(&lr->config_mutex);
1446 static long linereq_ioctl_unlocked(struct file *file, unsigned int cmd,
1449 struct linereq *lr = file->private_data;
1450 void __user *ip = (void __user *)arg;
1452 if (!lr->gdev->chip)
1456 case GPIO_V2_LINE_GET_VALUES_IOCTL:
1457 return linereq_get_values(lr, ip);
1458 case GPIO_V2_LINE_SET_VALUES_IOCTL:
1459 return linereq_set_values(lr, ip);
1460 case GPIO_V2_LINE_SET_CONFIG_IOCTL:
1461 return linereq_set_config(lr, ip);
1467 static long linereq_ioctl(struct file *file, unsigned int cmd,
1470 struct linereq *lr = file->private_data;
1472 return call_ioctl_locked(file, cmd, arg, lr->gdev,
1473 linereq_ioctl_unlocked);
1476 #ifdef CONFIG_COMPAT
1477 static long linereq_ioctl_compat(struct file *file, unsigned int cmd,
1480 return linereq_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
1484 static __poll_t linereq_poll_unlocked(struct file *file,
1485 struct poll_table_struct *wait)
1487 struct linereq *lr = file->private_data;
1488 __poll_t events = 0;
1490 if (!lr->gdev->chip)
1491 return EPOLLHUP | EPOLLERR;
1493 poll_wait(file, &lr->wait, wait);
1495 if (!kfifo_is_empty_spinlocked_noirqsave(&lr->events,
1497 events = EPOLLIN | EPOLLRDNORM;
1502 static __poll_t linereq_poll(struct file *file,
1503 struct poll_table_struct *wait)
1505 struct linereq *lr = file->private_data;
1507 return call_poll_locked(file, wait, lr->gdev, linereq_poll_unlocked);
1510 static ssize_t linereq_read_unlocked(struct file *file, char __user *buf,
1511 size_t count, loff_t *f_ps)
1513 struct linereq *lr = file->private_data;
1514 struct gpio_v2_line_event le;
1515 ssize_t bytes_read = 0;
1518 if (!lr->gdev->chip)
1521 if (count < sizeof(le))
1525 spin_lock(&lr->wait.lock);
1526 if (kfifo_is_empty(&lr->events)) {
1528 spin_unlock(&lr->wait.lock);
1532 if (file->f_flags & O_NONBLOCK) {
1533 spin_unlock(&lr->wait.lock);
1537 ret = wait_event_interruptible_locked(lr->wait,
1538 !kfifo_is_empty(&lr->events));
1540 spin_unlock(&lr->wait.lock);
1545 ret = kfifo_out(&lr->events, &le, 1);
1546 spin_unlock(&lr->wait.lock);
1549 * This should never happen - we were holding the
1550 * lock from the moment we learned the fifo is no
1551 * longer empty until now.
1557 if (copy_to_user(buf + bytes_read, &le, sizeof(le)))
1559 bytes_read += sizeof(le);
1560 } while (count >= bytes_read + sizeof(le));
1565 static ssize_t linereq_read(struct file *file, char __user *buf,
1566 size_t count, loff_t *f_ps)
1568 struct linereq *lr = file->private_data;
1570 return call_read_locked(file, buf, count, f_ps, lr->gdev,
1571 linereq_read_unlocked);
1574 static void linereq_free(struct linereq *lr)
1578 if (lr->device_unregistered_nb.notifier_call)
1579 blocking_notifier_chain_unregister(&lr->gdev->device_notifier,
1580 &lr->device_unregistered_nb);
1582 for (i = 0; i < lr->num_lines; i++) {
1583 if (lr->lines[i].desc) {
1584 edge_detector_stop(&lr->lines[i]);
1585 gpiod_free(lr->lines[i].desc);
1588 kfifo_free(&lr->events);
1590 gpio_device_put(lr->gdev);
1594 static int linereq_release(struct inode *inode, struct file *file)
1596 struct linereq *lr = file->private_data;
1602 #ifdef CONFIG_PROC_FS
1603 static void linereq_show_fdinfo(struct seq_file *out, struct file *file)
1605 struct linereq *lr = file->private_data;
1606 struct device *dev = &lr->gdev->dev;
1609 seq_printf(out, "gpio-chip:\t%s\n", dev_name(dev));
1611 for (i = 0; i < lr->num_lines; i++)
1612 seq_printf(out, "gpio-line:\t%d\n",
1613 gpio_chip_hwgpio(lr->lines[i].desc));
1617 static const struct file_operations line_fileops = {
1618 .release = linereq_release,
1619 .read = linereq_read,
1620 .poll = linereq_poll,
1621 .owner = THIS_MODULE,
1622 .llseek = noop_llseek,
1623 .unlocked_ioctl = linereq_ioctl,
1624 #ifdef CONFIG_COMPAT
1625 .compat_ioctl = linereq_ioctl_compat,
1627 #ifdef CONFIG_PROC_FS
1628 .show_fdinfo = linereq_show_fdinfo,
1632 static int linereq_create(struct gpio_device *gdev, void __user *ip)
1634 struct gpio_v2_line_request ulr;
1635 struct gpio_v2_line_config *lc;
1642 if (copy_from_user(&ulr, ip, sizeof(ulr)))
1645 if ((ulr.num_lines == 0) || (ulr.num_lines > GPIO_V2_LINES_MAX))
1648 if (memchr_inv(ulr.padding, 0, sizeof(ulr.padding)))
1652 ret = gpio_v2_line_config_validate(lc, ulr.num_lines);
1656 lr = kzalloc(struct_size(lr, lines, ulr.num_lines), GFP_KERNEL);
1660 lr->gdev = gpio_device_get(gdev);
1662 for (i = 0; i < ulr.num_lines; i++) {
1663 lr->lines[i].req = lr;
1664 WRITE_ONCE(lr->lines[i].sw_debounced, 0);
1665 INIT_DELAYED_WORK(&lr->lines[i].work, debounce_work_func);
1668 if (ulr.consumer[0] != '\0') {
1669 /* label is only initialized if consumer is set */
1670 lr->label = kstrndup(ulr.consumer, sizeof(ulr.consumer) - 1,
1674 goto out_free_linereq;
1678 mutex_init(&lr->config_mutex);
1679 init_waitqueue_head(&lr->wait);
1680 lr->event_buffer_size = ulr.event_buffer_size;
1681 if (lr->event_buffer_size == 0)
1682 lr->event_buffer_size = ulr.num_lines * 16;
1683 else if (lr->event_buffer_size > GPIO_V2_LINES_MAX * 16)
1684 lr->event_buffer_size = GPIO_V2_LINES_MAX * 16;
1686 atomic_set(&lr->seqno, 0);
1687 lr->num_lines = ulr.num_lines;
1689 /* Request each GPIO */
1690 for (i = 0; i < ulr.num_lines; i++) {
1691 u32 offset = ulr.offsets[i];
1692 struct gpio_desc *desc = gpiochip_get_desc(gdev->chip, offset);
1695 ret = PTR_ERR(desc);
1696 goto out_free_linereq;
1699 ret = gpiod_request_user(desc, lr->label);
1701 goto out_free_linereq;
1703 lr->lines[i].desc = desc;
1704 flags = gpio_v2_line_config_flags(lc, i);
1705 gpio_v2_line_config_flags_to_desc_flags(flags, &desc->flags);
1707 ret = gpiod_set_transitory(desc, false);
1709 goto out_free_linereq;
1711 edflags = flags & GPIO_V2_LINE_EDGE_DETECTOR_FLAGS;
1713 * Lines have to be requested explicitly for input
1714 * or output, else the line will be treated "as is".
1716 if (flags & GPIO_V2_LINE_FLAG_OUTPUT) {
1717 int val = gpio_v2_line_config_output_value(lc, i);
1719 ret = gpiod_direction_output(desc, val);
1721 goto out_free_linereq;
1722 } else if (flags & GPIO_V2_LINE_FLAG_INPUT) {
1723 ret = gpiod_direction_input(desc);
1725 goto out_free_linereq;
1727 ret = edge_detector_setup(&lr->lines[i], lc, i,
1730 goto out_free_linereq;
1733 lr->lines[i].edflags = edflags;
1735 gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_REQUESTED);
1737 dev_dbg(&gdev->dev, "registered chardev handle for line %d\n",
1741 lr->device_unregistered_nb.notifier_call = linereq_unregistered_notify;
1742 ret = blocking_notifier_chain_register(&gdev->device_notifier,
1743 &lr->device_unregistered_nb);
1745 goto out_free_linereq;
1747 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
1750 goto out_free_linereq;
1753 file = anon_inode_getfile("gpio-line", &line_fileops, lr,
1754 O_RDONLY | O_CLOEXEC);
1756 ret = PTR_ERR(file);
1757 goto out_put_unused_fd;
1761 if (copy_to_user(ip, &ulr, sizeof(ulr))) {
1763 * fput() will trigger the release() callback, so do not go onto
1764 * the regular error cleanup path here.
1771 fd_install(fd, file);
1773 dev_dbg(&gdev->dev, "registered chardev handle for %d lines\n",
1785 #ifdef CONFIG_GPIO_CDEV_V1
1788 * GPIO line event management
1792 * struct lineevent_state - contains the state of a userspace event
1793 * @gdev: the GPIO device the event pertains to
1794 * @label: consumer label used to tag descriptors
1795 * @desc: the GPIO descriptor held by this event
1796 * @eflags: the event flags this line was requested with
1797 * @irq: the interrupt that trigger in response to events on this GPIO
1798 * @wait: wait queue that handles blocking reads of events
1799 * @device_unregistered_nb: notifier block for receiving gdev unregister events
1800 * @events: KFIFO for the GPIO events
1801 * @timestamp: cache for the timestamp storing it between hardirq
1802 * and IRQ thread, used to bring the timestamp close to the actual
1805 struct lineevent_state {
1806 struct gpio_device *gdev;
1808 struct gpio_desc *desc;
1811 wait_queue_head_t wait;
1812 struct notifier_block device_unregistered_nb;
1813 DECLARE_KFIFO(events, struct gpioevent_data, 16);
1817 #define GPIOEVENT_REQUEST_VALID_FLAGS \
1818 (GPIOEVENT_REQUEST_RISING_EDGE | \
1819 GPIOEVENT_REQUEST_FALLING_EDGE)
1821 static __poll_t lineevent_poll_unlocked(struct file *file,
1822 struct poll_table_struct *wait)
1824 struct lineevent_state *le = file->private_data;
1825 __poll_t events = 0;
1827 if (!le->gdev->chip)
1828 return EPOLLHUP | EPOLLERR;
1830 poll_wait(file, &le->wait, wait);
1832 if (!kfifo_is_empty_spinlocked_noirqsave(&le->events, &le->wait.lock))
1833 events = EPOLLIN | EPOLLRDNORM;
1838 static __poll_t lineevent_poll(struct file *file,
1839 struct poll_table_struct *wait)
1841 struct lineevent_state *le = file->private_data;
1843 return call_poll_locked(file, wait, le->gdev, lineevent_poll_unlocked);
1846 static int lineevent_unregistered_notify(struct notifier_block *nb,
1847 unsigned long action, void *data)
1849 struct lineevent_state *le = container_of(nb, struct lineevent_state,
1850 device_unregistered_nb);
1852 wake_up_poll(&le->wait, EPOLLIN | EPOLLERR);
1857 struct compat_gpioeevent_data {
1858 compat_u64 timestamp;
1862 static ssize_t lineevent_read_unlocked(struct file *file, char __user *buf,
1863 size_t count, loff_t *f_ps)
1865 struct lineevent_state *le = file->private_data;
1866 struct gpioevent_data ge;
1867 ssize_t bytes_read = 0;
1871 if (!le->gdev->chip)
1875 * When compatible system call is being used the struct gpioevent_data,
1876 * in case of at least ia32, has different size due to the alignment
1877 * differences. Because we have first member 64 bits followed by one of
1878 * 32 bits there is no gap between them. The only difference is the
1879 * padding at the end of the data structure. Hence, we calculate the
1880 * actual sizeof() and pass this as an argument to copy_to_user() to
1881 * drop unneeded bytes from the output.
1883 if (compat_need_64bit_alignment_fixup())
1884 ge_size = sizeof(struct compat_gpioeevent_data);
1886 ge_size = sizeof(struct gpioevent_data);
1887 if (count < ge_size)
1891 spin_lock(&le->wait.lock);
1892 if (kfifo_is_empty(&le->events)) {
1894 spin_unlock(&le->wait.lock);
1898 if (file->f_flags & O_NONBLOCK) {
1899 spin_unlock(&le->wait.lock);
1903 ret = wait_event_interruptible_locked(le->wait,
1904 !kfifo_is_empty(&le->events));
1906 spin_unlock(&le->wait.lock);
1911 ret = kfifo_out(&le->events, &ge, 1);
1912 spin_unlock(&le->wait.lock);
1915 * This should never happen - we were holding the lock
1916 * from the moment we learned the fifo is no longer
1923 if (copy_to_user(buf + bytes_read, &ge, ge_size))
1925 bytes_read += ge_size;
1926 } while (count >= bytes_read + ge_size);
1931 static ssize_t lineevent_read(struct file *file, char __user *buf,
1932 size_t count, loff_t *f_ps)
1934 struct lineevent_state *le = file->private_data;
1936 return call_read_locked(file, buf, count, f_ps, le->gdev,
1937 lineevent_read_unlocked);
1940 static void lineevent_free(struct lineevent_state *le)
1942 if (le->device_unregistered_nb.notifier_call)
1943 blocking_notifier_chain_unregister(&le->gdev->device_notifier,
1944 &le->device_unregistered_nb);
1946 free_irq(le->irq, le);
1948 gpiod_free(le->desc);
1950 gpio_device_put(le->gdev);
1954 static int lineevent_release(struct inode *inode, struct file *file)
1956 lineevent_free(file->private_data);
1960 static long lineevent_ioctl_unlocked(struct file *file, unsigned int cmd,
1963 struct lineevent_state *le = file->private_data;
1964 void __user *ip = (void __user *)arg;
1965 struct gpiohandle_data ghd;
1967 if (!le->gdev->chip)
1971 * We can get the value for an event line but not set it,
1972 * because it is input by definition.
1974 if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
1977 memset(&ghd, 0, sizeof(ghd));
1979 val = gpiod_get_value_cansleep(le->desc);
1982 ghd.values[0] = val;
1984 if (copy_to_user(ip, &ghd, sizeof(ghd)))
1992 static long lineevent_ioctl(struct file *file, unsigned int cmd,
1995 struct lineevent_state *le = file->private_data;
1997 return call_ioctl_locked(file, cmd, arg, le->gdev,
1998 lineevent_ioctl_unlocked);
2001 #ifdef CONFIG_COMPAT
2002 static long lineevent_ioctl_compat(struct file *file, unsigned int cmd,
2005 return lineevent_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
2009 static const struct file_operations lineevent_fileops = {
2010 .release = lineevent_release,
2011 .read = lineevent_read,
2012 .poll = lineevent_poll,
2013 .owner = THIS_MODULE,
2014 .llseek = noop_llseek,
2015 .unlocked_ioctl = lineevent_ioctl,
2016 #ifdef CONFIG_COMPAT
2017 .compat_ioctl = lineevent_ioctl_compat,
2021 static irqreturn_t lineevent_irq_thread(int irq, void *p)
2023 struct lineevent_state *le = p;
2024 struct gpioevent_data ge;
2027 /* Do not leak kernel stack to userspace */
2028 memset(&ge, 0, sizeof(ge));
2031 * We may be running from a nested threaded interrupt in which case
2032 * we didn't get the timestamp from lineevent_irq_handler().
2035 ge.timestamp = ktime_get_ns();
2037 ge.timestamp = le->timestamp;
2039 if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE
2040 && le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
2041 int level = gpiod_get_value_cansleep(le->desc);
2044 /* Emit low-to-high event */
2045 ge.id = GPIOEVENT_EVENT_RISING_EDGE;
2047 /* Emit high-to-low event */
2048 ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
2049 } else if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE) {
2050 /* Emit low-to-high event */
2051 ge.id = GPIOEVENT_EVENT_RISING_EDGE;
2052 } else if (le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
2053 /* Emit high-to-low event */
2054 ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
2059 ret = kfifo_in_spinlocked_noirqsave(&le->events, &ge,
2062 wake_up_poll(&le->wait, EPOLLIN);
2064 pr_debug_ratelimited("event FIFO is full - event dropped\n");
2069 static irqreturn_t lineevent_irq_handler(int irq, void *p)
2071 struct lineevent_state *le = p;
2074 * Just store the timestamp in hardirq context so we get it as
2075 * close in time as possible to the actual event.
2077 le->timestamp = ktime_get_ns();
2079 return IRQ_WAKE_THREAD;
2082 static int lineevent_create(struct gpio_device *gdev, void __user *ip)
2084 struct gpioevent_request eventreq;
2085 struct lineevent_state *le;
2086 struct gpio_desc *desc;
2093 int irq, irqflags = 0;
2095 if (copy_from_user(&eventreq, ip, sizeof(eventreq)))
2098 offset = eventreq.lineoffset;
2099 lflags = eventreq.handleflags;
2100 eflags = eventreq.eventflags;
2102 desc = gpiochip_get_desc(gdev->chip, offset);
2104 return PTR_ERR(desc);
2106 /* Return an error if a unknown flag is set */
2107 if ((lflags & ~GPIOHANDLE_REQUEST_VALID_FLAGS) ||
2108 (eflags & ~GPIOEVENT_REQUEST_VALID_FLAGS))
2111 /* This is just wrong: we don't look for events on output lines */
2112 if ((lflags & GPIOHANDLE_REQUEST_OUTPUT) ||
2113 (lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN) ||
2114 (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE))
2117 /* Only one bias flag can be set. */
2118 if (((lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE) &&
2119 (lflags & (GPIOHANDLE_REQUEST_BIAS_PULL_DOWN |
2120 GPIOHANDLE_REQUEST_BIAS_PULL_UP))) ||
2121 ((lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN) &&
2122 (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)))
2125 le = kzalloc(sizeof(*le), GFP_KERNEL);
2128 le->gdev = gpio_device_get(gdev);
2130 if (eventreq.consumer_label[0] != '\0') {
2131 /* label is only initialized if consumer_label is set */
2132 le->label = kstrndup(eventreq.consumer_label,
2133 sizeof(eventreq.consumer_label) - 1,
2141 ret = gpiod_request_user(desc, le->label);
2145 le->eflags = eflags;
2147 linehandle_flags_to_desc_flags(lflags, &desc->flags);
2149 ret = gpiod_direction_input(desc);
2153 gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_REQUESTED);
2155 irq = gpiod_to_irq(desc);
2161 if (eflags & GPIOEVENT_REQUEST_RISING_EDGE)
2162 irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
2163 IRQF_TRIGGER_FALLING : IRQF_TRIGGER_RISING;
2164 if (eflags & GPIOEVENT_REQUEST_FALLING_EDGE)
2165 irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
2166 IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING;
2167 irqflags |= IRQF_ONESHOT;
2169 INIT_KFIFO(le->events);
2170 init_waitqueue_head(&le->wait);
2172 le->device_unregistered_nb.notifier_call = lineevent_unregistered_notify;
2173 ret = blocking_notifier_chain_register(&gdev->device_notifier,
2174 &le->device_unregistered_nb);
2178 /* Request a thread to read the events */
2179 ret = request_threaded_irq(irq,
2180 lineevent_irq_handler,
2181 lineevent_irq_thread,
2190 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
2196 file = anon_inode_getfile("gpio-event",
2199 O_RDONLY | O_CLOEXEC);
2201 ret = PTR_ERR(file);
2202 goto out_put_unused_fd;
2206 if (copy_to_user(ip, &eventreq, sizeof(eventreq))) {
2208 * fput() will trigger the release() callback, so do not go onto
2209 * the regular error cleanup path here.
2216 fd_install(fd, file);
2227 static void gpio_v2_line_info_to_v1(struct gpio_v2_line_info *info_v2,
2228 struct gpioline_info *info_v1)
2230 u64 flagsv2 = info_v2->flags;
2232 memcpy(info_v1->name, info_v2->name, sizeof(info_v1->name));
2233 memcpy(info_v1->consumer, info_v2->consumer, sizeof(info_v1->consumer));
2234 info_v1->line_offset = info_v2->offset;
2237 if (flagsv2 & GPIO_V2_LINE_FLAG_USED)
2238 info_v1->flags |= GPIOLINE_FLAG_KERNEL;
2240 if (flagsv2 & GPIO_V2_LINE_FLAG_OUTPUT)
2241 info_v1->flags |= GPIOLINE_FLAG_IS_OUT;
2243 if (flagsv2 & GPIO_V2_LINE_FLAG_ACTIVE_LOW)
2244 info_v1->flags |= GPIOLINE_FLAG_ACTIVE_LOW;
2246 if (flagsv2 & GPIO_V2_LINE_FLAG_OPEN_DRAIN)
2247 info_v1->flags |= GPIOLINE_FLAG_OPEN_DRAIN;
2248 if (flagsv2 & GPIO_V2_LINE_FLAG_OPEN_SOURCE)
2249 info_v1->flags |= GPIOLINE_FLAG_OPEN_SOURCE;
2251 if (flagsv2 & GPIO_V2_LINE_FLAG_BIAS_PULL_UP)
2252 info_v1->flags |= GPIOLINE_FLAG_BIAS_PULL_UP;
2253 if (flagsv2 & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN)
2254 info_v1->flags |= GPIOLINE_FLAG_BIAS_PULL_DOWN;
2255 if (flagsv2 & GPIO_V2_LINE_FLAG_BIAS_DISABLED)
2256 info_v1->flags |= GPIOLINE_FLAG_BIAS_DISABLE;
2259 static void gpio_v2_line_info_changed_to_v1(
2260 struct gpio_v2_line_info_changed *lic_v2,
2261 struct gpioline_info_changed *lic_v1)
2263 memset(lic_v1, 0, sizeof(*lic_v1));
2264 gpio_v2_line_info_to_v1(&lic_v2->info, &lic_v1->info);
2265 lic_v1->timestamp = lic_v2->timestamp_ns;
2266 lic_v1->event_type = lic_v2->event_type;
2269 #endif /* CONFIG_GPIO_CDEV_V1 */
2271 static void gpio_desc_to_lineinfo(struct gpio_desc *desc,
2272 struct gpio_v2_line_info *info)
2274 struct gpio_chip *gc = desc->gdev->chip;
2275 bool ok_for_pinctrl;
2276 unsigned long flags;
2277 u32 debounce_period_us;
2278 unsigned int num_attrs = 0;
2280 memset(info, 0, sizeof(*info));
2281 info->offset = gpio_chip_hwgpio(desc);
2284 * This function takes a mutex so we must check this before taking
2287 * FIXME: find a non-racy way to retrieve this information. Maybe a
2288 * lock common to both frameworks?
2291 pinctrl_gpio_can_use_line(gc->base + info->offset);
2293 spin_lock_irqsave(&gpio_lock, flags);
2296 strscpy(info->name, desc->name, sizeof(info->name));
2299 strscpy(info->consumer, desc->label, sizeof(info->consumer));
2302 * Userspace only need to know that the kernel is using this GPIO so
2306 if (test_bit(FLAG_REQUESTED, &desc->flags) ||
2307 test_bit(FLAG_IS_HOGGED, &desc->flags) ||
2308 test_bit(FLAG_USED_AS_IRQ, &desc->flags) ||
2309 test_bit(FLAG_EXPORT, &desc->flags) ||
2310 test_bit(FLAG_SYSFS, &desc->flags) ||
2311 !gpiochip_line_is_valid(gc, info->offset) ||
2313 info->flags |= GPIO_V2_LINE_FLAG_USED;
2315 if (test_bit(FLAG_IS_OUT, &desc->flags))
2316 info->flags |= GPIO_V2_LINE_FLAG_OUTPUT;
2318 info->flags |= GPIO_V2_LINE_FLAG_INPUT;
2320 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2321 info->flags |= GPIO_V2_LINE_FLAG_ACTIVE_LOW;
2323 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
2324 info->flags |= GPIO_V2_LINE_FLAG_OPEN_DRAIN;
2325 if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
2326 info->flags |= GPIO_V2_LINE_FLAG_OPEN_SOURCE;
2328 if (test_bit(FLAG_BIAS_DISABLE, &desc->flags))
2329 info->flags |= GPIO_V2_LINE_FLAG_BIAS_DISABLED;
2330 if (test_bit(FLAG_PULL_DOWN, &desc->flags))
2331 info->flags |= GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN;
2332 if (test_bit(FLAG_PULL_UP, &desc->flags))
2333 info->flags |= GPIO_V2_LINE_FLAG_BIAS_PULL_UP;
2335 if (test_bit(FLAG_EDGE_RISING, &desc->flags))
2336 info->flags |= GPIO_V2_LINE_FLAG_EDGE_RISING;
2337 if (test_bit(FLAG_EDGE_FALLING, &desc->flags))
2338 info->flags |= GPIO_V2_LINE_FLAG_EDGE_FALLING;
2340 if (test_bit(FLAG_EVENT_CLOCK_REALTIME, &desc->flags))
2341 info->flags |= GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME;
2342 else if (test_bit(FLAG_EVENT_CLOCK_HTE, &desc->flags))
2343 info->flags |= GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE;
2345 debounce_period_us = READ_ONCE(desc->debounce_period_us);
2346 if (debounce_period_us) {
2347 info->attrs[num_attrs].id = GPIO_V2_LINE_ATTR_ID_DEBOUNCE;
2348 info->attrs[num_attrs].debounce_period_us = debounce_period_us;
2351 info->num_attrs = num_attrs;
2353 spin_unlock_irqrestore(&gpio_lock, flags);
2356 struct gpio_chardev_data {
2357 struct gpio_device *gdev;
2358 wait_queue_head_t wait;
2359 DECLARE_KFIFO(events, struct gpio_v2_line_info_changed, 32);
2360 struct notifier_block lineinfo_changed_nb;
2361 struct notifier_block device_unregistered_nb;
2362 unsigned long *watched_lines;
2363 #ifdef CONFIG_GPIO_CDEV_V1
2364 atomic_t watch_abi_version;
2368 static int chipinfo_get(struct gpio_chardev_data *cdev, void __user *ip)
2370 struct gpio_device *gdev = cdev->gdev;
2371 struct gpiochip_info chipinfo;
2373 memset(&chipinfo, 0, sizeof(chipinfo));
2375 strscpy(chipinfo.name, dev_name(&gdev->dev), sizeof(chipinfo.name));
2376 strscpy(chipinfo.label, gdev->label, sizeof(chipinfo.label));
2377 chipinfo.lines = gdev->ngpio;
2378 if (copy_to_user(ip, &chipinfo, sizeof(chipinfo)))
2383 #ifdef CONFIG_GPIO_CDEV_V1
2385 * returns 0 if the versions match, else the previously selected ABI version
2387 static int lineinfo_ensure_abi_version(struct gpio_chardev_data *cdata,
2388 unsigned int version)
2390 int abiv = atomic_cmpxchg(&cdata->watch_abi_version, 0, version);
2392 if (abiv == version)
2398 static int lineinfo_get_v1(struct gpio_chardev_data *cdev, void __user *ip,
2401 struct gpio_desc *desc;
2402 struct gpioline_info lineinfo;
2403 struct gpio_v2_line_info lineinfo_v2;
2405 if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
2408 /* this doubles as a range check on line_offset */
2409 desc = gpiochip_get_desc(cdev->gdev->chip, lineinfo.line_offset);
2411 return PTR_ERR(desc);
2414 if (lineinfo_ensure_abi_version(cdev, 1))
2417 if (test_and_set_bit(lineinfo.line_offset, cdev->watched_lines))
2421 gpio_desc_to_lineinfo(desc, &lineinfo_v2);
2422 gpio_v2_line_info_to_v1(&lineinfo_v2, &lineinfo);
2424 if (copy_to_user(ip, &lineinfo, sizeof(lineinfo))) {
2426 clear_bit(lineinfo.line_offset, cdev->watched_lines);
2434 static int lineinfo_get(struct gpio_chardev_data *cdev, void __user *ip,
2437 struct gpio_desc *desc;
2438 struct gpio_v2_line_info lineinfo;
2440 if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
2443 if (memchr_inv(lineinfo.padding, 0, sizeof(lineinfo.padding)))
2446 desc = gpiochip_get_desc(cdev->gdev->chip, lineinfo.offset);
2448 return PTR_ERR(desc);
2451 #ifdef CONFIG_GPIO_CDEV_V1
2452 if (lineinfo_ensure_abi_version(cdev, 2))
2455 if (test_and_set_bit(lineinfo.offset, cdev->watched_lines))
2458 gpio_desc_to_lineinfo(desc, &lineinfo);
2460 if (copy_to_user(ip, &lineinfo, sizeof(lineinfo))) {
2462 clear_bit(lineinfo.offset, cdev->watched_lines);
2469 static int lineinfo_unwatch(struct gpio_chardev_data *cdev, void __user *ip)
2473 if (copy_from_user(&offset, ip, sizeof(offset)))
2476 if (offset >= cdev->gdev->ngpio)
2479 if (!test_and_clear_bit(offset, cdev->watched_lines))
2486 * gpio_ioctl() - ioctl handler for the GPIO chardev
2488 static long gpio_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
2490 struct gpio_chardev_data *cdev = file->private_data;
2491 struct gpio_device *gdev = cdev->gdev;
2492 void __user *ip = (void __user *)arg;
2494 /* We fail any subsequent ioctl():s when the chip is gone */
2498 /* Fill in the struct and pass to userspace */
2500 case GPIO_GET_CHIPINFO_IOCTL:
2501 return chipinfo_get(cdev, ip);
2502 #ifdef CONFIG_GPIO_CDEV_V1
2503 case GPIO_GET_LINEHANDLE_IOCTL:
2504 return linehandle_create(gdev, ip);
2505 case GPIO_GET_LINEEVENT_IOCTL:
2506 return lineevent_create(gdev, ip);
2507 case GPIO_GET_LINEINFO_IOCTL:
2508 return lineinfo_get_v1(cdev, ip, false);
2509 case GPIO_GET_LINEINFO_WATCH_IOCTL:
2510 return lineinfo_get_v1(cdev, ip, true);
2511 #endif /* CONFIG_GPIO_CDEV_V1 */
2512 case GPIO_V2_GET_LINEINFO_IOCTL:
2513 return lineinfo_get(cdev, ip, false);
2514 case GPIO_V2_GET_LINEINFO_WATCH_IOCTL:
2515 return lineinfo_get(cdev, ip, true);
2516 case GPIO_V2_GET_LINE_IOCTL:
2517 return linereq_create(gdev, ip);
2518 case GPIO_GET_LINEINFO_UNWATCH_IOCTL:
2519 return lineinfo_unwatch(cdev, ip);
2525 #ifdef CONFIG_COMPAT
2526 static long gpio_ioctl_compat(struct file *file, unsigned int cmd,
2529 return gpio_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
2533 static int lineinfo_changed_notify(struct notifier_block *nb,
2534 unsigned long action, void *data)
2536 struct gpio_chardev_data *cdev =
2537 container_of(nb, struct gpio_chardev_data, lineinfo_changed_nb);
2538 struct gpio_v2_line_info_changed chg;
2539 struct gpio_desc *desc = data;
2542 if (!test_bit(gpio_chip_hwgpio(desc), cdev->watched_lines))
2545 memset(&chg, 0, sizeof(chg));
2546 chg.event_type = action;
2547 chg.timestamp_ns = ktime_get_ns();
2548 gpio_desc_to_lineinfo(desc, &chg.info);
2550 ret = kfifo_in_spinlocked(&cdev->events, &chg, 1, &cdev->wait.lock);
2552 wake_up_poll(&cdev->wait, EPOLLIN);
2554 pr_debug_ratelimited("lineinfo event FIFO is full - event dropped\n");
2559 static int gpio_device_unregistered_notify(struct notifier_block *nb,
2560 unsigned long action, void *data)
2562 struct gpio_chardev_data *cdev = container_of(nb,
2563 struct gpio_chardev_data,
2564 device_unregistered_nb);
2566 wake_up_poll(&cdev->wait, EPOLLIN | EPOLLERR);
2571 static __poll_t lineinfo_watch_poll_unlocked(struct file *file,
2572 struct poll_table_struct *pollt)
2574 struct gpio_chardev_data *cdev = file->private_data;
2575 __poll_t events = 0;
2577 if (!cdev->gdev->chip)
2578 return EPOLLHUP | EPOLLERR;
2580 poll_wait(file, &cdev->wait, pollt);
2582 if (!kfifo_is_empty_spinlocked_noirqsave(&cdev->events,
2584 events = EPOLLIN | EPOLLRDNORM;
2589 static __poll_t lineinfo_watch_poll(struct file *file,
2590 struct poll_table_struct *pollt)
2592 struct gpio_chardev_data *cdev = file->private_data;
2594 return call_poll_locked(file, pollt, cdev->gdev,
2595 lineinfo_watch_poll_unlocked);
2598 static ssize_t lineinfo_watch_read_unlocked(struct file *file, char __user *buf,
2599 size_t count, loff_t *off)
2601 struct gpio_chardev_data *cdev = file->private_data;
2602 struct gpio_v2_line_info_changed event;
2603 ssize_t bytes_read = 0;
2607 if (!cdev->gdev->chip)
2610 #ifndef CONFIG_GPIO_CDEV_V1
2611 event_size = sizeof(struct gpio_v2_line_info_changed);
2612 if (count < event_size)
2617 spin_lock(&cdev->wait.lock);
2618 if (kfifo_is_empty(&cdev->events)) {
2620 spin_unlock(&cdev->wait.lock);
2624 if (file->f_flags & O_NONBLOCK) {
2625 spin_unlock(&cdev->wait.lock);
2629 ret = wait_event_interruptible_locked(cdev->wait,
2630 !kfifo_is_empty(&cdev->events));
2632 spin_unlock(&cdev->wait.lock);
2636 #ifdef CONFIG_GPIO_CDEV_V1
2637 /* must be after kfifo check so watch_abi_version is set */
2638 if (atomic_read(&cdev->watch_abi_version) == 2)
2639 event_size = sizeof(struct gpio_v2_line_info_changed);
2641 event_size = sizeof(struct gpioline_info_changed);
2642 if (count < event_size) {
2643 spin_unlock(&cdev->wait.lock);
2647 ret = kfifo_out(&cdev->events, &event, 1);
2648 spin_unlock(&cdev->wait.lock);
2652 /* We should never get here. See lineevent_read(). */
2655 #ifdef CONFIG_GPIO_CDEV_V1
2656 if (event_size == sizeof(struct gpio_v2_line_info_changed)) {
2657 if (copy_to_user(buf + bytes_read, &event, event_size))
2660 struct gpioline_info_changed event_v1;
2662 gpio_v2_line_info_changed_to_v1(&event, &event_v1);
2663 if (copy_to_user(buf + bytes_read, &event_v1,
2668 if (copy_to_user(buf + bytes_read, &event, event_size))
2671 bytes_read += event_size;
2672 } while (count >= bytes_read + sizeof(event));
2677 static ssize_t lineinfo_watch_read(struct file *file, char __user *buf,
2678 size_t count, loff_t *off)
2680 struct gpio_chardev_data *cdev = file->private_data;
2682 return call_read_locked(file, buf, count, off, cdev->gdev,
2683 lineinfo_watch_read_unlocked);
2687 * gpio_chrdev_open() - open the chardev for ioctl operations
2688 * @inode: inode for this chardev
2689 * @file: file struct for storing private data
2690 * Returns 0 on success
2692 static int gpio_chrdev_open(struct inode *inode, struct file *file)
2694 struct gpio_device *gdev = container_of(inode->i_cdev,
2695 struct gpio_device, chrdev);
2696 struct gpio_chardev_data *cdev;
2699 down_read(&gdev->sem);
2701 /* Fail on open if the backing gpiochip is gone */
2707 cdev = kzalloc(sizeof(*cdev), GFP_KERNEL);
2711 cdev->watched_lines = bitmap_zalloc(gdev->chip->ngpio, GFP_KERNEL);
2712 if (!cdev->watched_lines)
2715 init_waitqueue_head(&cdev->wait);
2716 INIT_KFIFO(cdev->events);
2717 cdev->gdev = gpio_device_get(gdev);
2719 cdev->lineinfo_changed_nb.notifier_call = lineinfo_changed_notify;
2720 ret = blocking_notifier_chain_register(&gdev->line_state_notifier,
2721 &cdev->lineinfo_changed_nb);
2723 goto out_free_bitmap;
2725 cdev->device_unregistered_nb.notifier_call =
2726 gpio_device_unregistered_notify;
2727 ret = blocking_notifier_chain_register(&gdev->device_notifier,
2728 &cdev->device_unregistered_nb);
2730 goto out_unregister_line_notifier;
2732 file->private_data = cdev;
2734 ret = nonseekable_open(inode, file);
2736 goto out_unregister_device_notifier;
2738 up_read(&gdev->sem);
2742 out_unregister_device_notifier:
2743 blocking_notifier_chain_unregister(&gdev->device_notifier,
2744 &cdev->device_unregistered_nb);
2745 out_unregister_line_notifier:
2746 blocking_notifier_chain_unregister(&gdev->line_state_notifier,
2747 &cdev->lineinfo_changed_nb);
2749 gpio_device_put(gdev);
2750 bitmap_free(cdev->watched_lines);
2754 up_read(&gdev->sem);
2759 * gpio_chrdev_release() - close chardev after ioctl operations
2760 * @inode: inode for this chardev
2761 * @file: file struct for storing private data
2762 * Returns 0 on success
2764 static int gpio_chrdev_release(struct inode *inode, struct file *file)
2766 struct gpio_chardev_data *cdev = file->private_data;
2767 struct gpio_device *gdev = cdev->gdev;
2769 bitmap_free(cdev->watched_lines);
2770 blocking_notifier_chain_unregister(&gdev->device_notifier,
2771 &cdev->device_unregistered_nb);
2772 blocking_notifier_chain_unregister(&gdev->line_state_notifier,
2773 &cdev->lineinfo_changed_nb);
2774 gpio_device_put(gdev);
2780 static const struct file_operations gpio_fileops = {
2781 .release = gpio_chrdev_release,
2782 .open = gpio_chrdev_open,
2783 .poll = lineinfo_watch_poll,
2784 .read = lineinfo_watch_read,
2785 .owner = THIS_MODULE,
2786 .llseek = no_llseek,
2787 .unlocked_ioctl = gpio_ioctl,
2788 #ifdef CONFIG_COMPAT
2789 .compat_ioctl = gpio_ioctl_compat,
2793 int gpiolib_cdev_register(struct gpio_device *gdev, dev_t devt)
2797 cdev_init(&gdev->chrdev, &gpio_fileops);
2798 gdev->chrdev.owner = THIS_MODULE;
2799 gdev->dev.devt = MKDEV(MAJOR(devt), gdev->id);
2801 ret = cdev_device_add(&gdev->chrdev, &gdev->dev);
2805 chip_dbg(gdev->chip, "added GPIO chardev (%d:%d)\n",
2806 MAJOR(devt), gdev->id);
2811 void gpiolib_cdev_unregister(struct gpio_device *gdev)
2813 cdev_device_del(&gdev->chrdev, &gdev->dev);
2814 blocking_notifier_call_chain(&gdev->device_notifier, 0, NULL);