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 blocking_notifier_call_chain(&desc->gdev->notifier,
234 GPIO_V2_LINE_CHANGED_CONFIG,
240 static long linehandle_ioctl_unlocked(struct file *file, unsigned int cmd,
243 struct linehandle_state *lh = file->private_data;
244 void __user *ip = (void __user *)arg;
245 struct gpiohandle_data ghd;
246 DECLARE_BITMAP(vals, GPIOHANDLES_MAX);
254 case GPIOHANDLE_GET_LINE_VALUES_IOCTL:
255 /* NOTE: It's okay to read values of output lines */
256 ret = gpiod_get_array_value_complex(false, true,
257 lh->num_descs, lh->descs,
262 memset(&ghd, 0, sizeof(ghd));
263 for (i = 0; i < lh->num_descs; i++)
264 ghd.values[i] = test_bit(i, vals);
266 if (copy_to_user(ip, &ghd, sizeof(ghd)))
270 case GPIOHANDLE_SET_LINE_VALUES_IOCTL:
272 * All line descriptors were created at once with the same
273 * flags so just check if the first one is really output.
275 if (!test_bit(FLAG_IS_OUT, &lh->descs[0]->flags))
278 if (copy_from_user(&ghd, ip, sizeof(ghd)))
281 /* Clamp all values to [0,1] */
282 for (i = 0; i < lh->num_descs; i++)
283 __assign_bit(i, vals, ghd.values[i]);
285 /* Reuse the array setting function */
286 return gpiod_set_array_value_complex(false,
292 case GPIOHANDLE_SET_CONFIG_IOCTL:
293 return linehandle_set_config(lh, ip);
299 static long linehandle_ioctl(struct file *file, unsigned int cmd,
302 struct linehandle_state *lh = file->private_data;
304 return call_ioctl_locked(file, cmd, arg, lh->gdev,
305 linehandle_ioctl_unlocked);
309 static long linehandle_ioctl_compat(struct file *file, unsigned int cmd,
312 return linehandle_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
316 static void linehandle_free(struct linehandle_state *lh)
320 for (i = 0; i < lh->num_descs; i++)
322 gpiod_free(lh->descs[i]);
324 gpio_device_put(lh->gdev);
328 static int linehandle_release(struct inode *inode, struct file *file)
330 linehandle_free(file->private_data);
334 static const struct file_operations linehandle_fileops = {
335 .release = linehandle_release,
336 .owner = THIS_MODULE,
337 .llseek = noop_llseek,
338 .unlocked_ioctl = linehandle_ioctl,
340 .compat_ioctl = linehandle_ioctl_compat,
344 static int linehandle_create(struct gpio_device *gdev, void __user *ip)
346 struct gpiohandle_request handlereq;
347 struct linehandle_state *lh;
352 if (copy_from_user(&handlereq, ip, sizeof(handlereq)))
354 if ((handlereq.lines == 0) || (handlereq.lines > GPIOHANDLES_MAX))
357 lflags = handlereq.flags;
359 ret = linehandle_validate_flags(lflags);
363 lh = kzalloc(sizeof(*lh), GFP_KERNEL);
366 lh->gdev = gpio_device_get(gdev);
368 if (handlereq.consumer_label[0] != '\0') {
369 /* label is only initialized if consumer_label is set */
370 lh->label = kstrndup(handlereq.consumer_label,
371 sizeof(handlereq.consumer_label) - 1,
379 lh->num_descs = handlereq.lines;
381 /* Request each GPIO */
382 for (i = 0; i < handlereq.lines; i++) {
383 u32 offset = handlereq.lineoffsets[i];
384 struct gpio_desc *desc = gpiochip_get_desc(gdev->chip, offset);
391 ret = gpiod_request_user(desc, lh->label);
395 linehandle_flags_to_desc_flags(handlereq.flags, &desc->flags);
397 ret = gpiod_set_transitory(desc, false);
402 * Lines have to be requested explicitly for input
403 * or output, else the line will be treated "as is".
405 if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
406 int val = !!handlereq.default_values[i];
408 ret = gpiod_direction_output(desc, val);
411 } else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
412 ret = gpiod_direction_input(desc);
417 blocking_notifier_call_chain(&desc->gdev->notifier,
418 GPIO_V2_LINE_CHANGED_REQUESTED, desc);
420 dev_dbg(&gdev->dev, "registered chardev handle for line %d\n",
424 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
430 file = anon_inode_getfile("gpio-linehandle",
433 O_RDONLY | O_CLOEXEC);
436 goto out_put_unused_fd;
440 if (copy_to_user(ip, &handlereq, sizeof(handlereq))) {
442 * fput() will trigger the release() callback, so do not go onto
443 * the regular error cleanup path here.
450 fd_install(fd, file);
452 dev_dbg(&gdev->dev, "registered chardev handle for %d lines\n",
463 #endif /* CONFIG_GPIO_CDEV_V1 */
466 * struct line - contains the state of a requested line
467 * @desc: the GPIO descriptor for this line.
468 * @req: the corresponding line request
469 * @irq: the interrupt triggered in response to events on this GPIO
470 * @edflags: the edge flags, GPIO_V2_LINE_FLAG_EDGE_RISING and/or
471 * GPIO_V2_LINE_FLAG_EDGE_FALLING, indicating the edge detection applied
472 * @timestamp_ns: cache for the timestamp storing it between hardirq and
473 * IRQ thread, used to bring the timestamp close to the actual event
474 * @req_seqno: the seqno for the current edge event in the sequence of
475 * events for the corresponding line request. This is drawn from the @req.
476 * @line_seqno: the seqno for the current edge event in the sequence of
477 * events for this line.
478 * @work: the worker that implements software debouncing
479 * @sw_debounced: flag indicating if the software debouncer is active
480 * @level: the current debounced physical level of the line
481 * @hdesc: the Hardware Timestamp Engine (HTE) descriptor
482 * @raw_level: the line level at the time of event
483 * @total_discard_seq: the running counter of the discarded events
484 * @last_seqno: the last sequence number before debounce period expires
487 struct gpio_desc *desc;
489 * -- edge detector specific fields --
494 * The flags for the active edge detector configuration.
496 * edflags is set by linereq_create(), linereq_free(), and
497 * linereq_set_config_unlocked(), which are themselves mutually
498 * exclusive, and is accessed by edge_irq_thread(),
499 * process_hw_ts_thread() and debounce_work_func(),
500 * which can all live with a slightly stale value.
504 * timestamp_ns and req_seqno are accessed only by
505 * edge_irq_handler() and edge_irq_thread(), which are themselves
506 * mutually exclusive, so no additional protection is necessary.
511 * line_seqno is accessed by either edge_irq_thread() or
512 * debounce_work_func(), which are themselves mutually exclusive,
513 * so no additional protection is necessary.
517 * -- debouncer specific fields --
519 struct delayed_work work;
521 * sw_debounce is accessed by linereq_set_config(), which is the
522 * only setter, and linereq_get_values(), which can live with a
523 * slightly stale value.
525 unsigned int sw_debounced;
527 * level is accessed by debounce_work_func(), which is the only
528 * setter, and linereq_get_values() which can live with a slightly
533 struct hte_ts_desc hdesc;
535 * HTE provider sets line level at the time of event. The valid
536 * value is 0 or 1 and negative value for an error.
540 * when sw_debounce is set on HTE enabled line, this is running
541 * counter of the discarded events.
543 u32 total_discard_seq;
545 * when sw_debounce is set on HTE enabled line, this variable records
546 * last sequence number before debounce period expires.
549 #endif /* CONFIG_HTE */
553 * struct linereq - contains the state of a userspace line request
554 * @gdev: the GPIO device the line request pertains to
555 * @label: consumer label used to tag GPIO descriptors
556 * @num_lines: the number of lines in the lines array
557 * @wait: wait queue that handles blocking reads of events
558 * @event_buffer_size: the number of elements allocated in @events
559 * @events: KFIFO for the GPIO events
560 * @seqno: the sequence number for edge events generated on all lines in
561 * this line request. Note that this is not used when @num_lines is 1, as
562 * the line_seqno is then the same and is cheaper to calculate.
563 * @config_mutex: mutex for serializing ioctl() calls to ensure consistency
564 * of configuration, particularly multi-step accesses to desc flags.
565 * @lines: the lines held by this line request, with @num_lines elements.
568 struct gpio_device *gdev;
571 wait_queue_head_t wait;
572 u32 event_buffer_size;
573 DECLARE_KFIFO_PTR(events, struct gpio_v2_line_event);
575 struct mutex config_mutex;
579 #define GPIO_V2_LINE_BIAS_FLAGS \
580 (GPIO_V2_LINE_FLAG_BIAS_PULL_UP | \
581 GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN | \
582 GPIO_V2_LINE_FLAG_BIAS_DISABLED)
584 #define GPIO_V2_LINE_DIRECTION_FLAGS \
585 (GPIO_V2_LINE_FLAG_INPUT | \
586 GPIO_V2_LINE_FLAG_OUTPUT)
588 #define GPIO_V2_LINE_DRIVE_FLAGS \
589 (GPIO_V2_LINE_FLAG_OPEN_DRAIN | \
590 GPIO_V2_LINE_FLAG_OPEN_SOURCE)
592 #define GPIO_V2_LINE_EDGE_FLAGS \
593 (GPIO_V2_LINE_FLAG_EDGE_RISING | \
594 GPIO_V2_LINE_FLAG_EDGE_FALLING)
596 #define GPIO_V2_LINE_FLAG_EDGE_BOTH GPIO_V2_LINE_EDGE_FLAGS
598 #define GPIO_V2_LINE_VALID_FLAGS \
599 (GPIO_V2_LINE_FLAG_ACTIVE_LOW | \
600 GPIO_V2_LINE_DIRECTION_FLAGS | \
601 GPIO_V2_LINE_DRIVE_FLAGS | \
602 GPIO_V2_LINE_EDGE_FLAGS | \
603 GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME | \
604 GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE | \
605 GPIO_V2_LINE_BIAS_FLAGS)
607 /* subset of flags relevant for edge detector configuration */
608 #define GPIO_V2_LINE_EDGE_DETECTOR_FLAGS \
609 (GPIO_V2_LINE_FLAG_ACTIVE_LOW | \
610 GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE | \
611 GPIO_V2_LINE_EDGE_FLAGS)
613 static void linereq_put_event(struct linereq *lr,
614 struct gpio_v2_line_event *le)
616 bool overflow = false;
618 spin_lock(&lr->wait.lock);
619 if (kfifo_is_full(&lr->events)) {
621 kfifo_skip(&lr->events);
623 kfifo_in(&lr->events, le, 1);
624 spin_unlock(&lr->wait.lock);
626 wake_up_poll(&lr->wait, EPOLLIN);
628 pr_debug_ratelimited("event FIFO is full - event dropped\n");
631 static u64 line_event_timestamp(struct line *line)
633 if (test_bit(FLAG_EVENT_CLOCK_REALTIME, &line->desc->flags))
634 return ktime_get_real_ns();
635 else if (IS_ENABLED(CONFIG_HTE) &&
636 test_bit(FLAG_EVENT_CLOCK_HTE, &line->desc->flags))
637 return line->timestamp_ns;
639 return ktime_get_ns();
642 static u32 line_event_id(int level)
644 return level ? GPIO_V2_LINE_EVENT_RISING_EDGE :
645 GPIO_V2_LINE_EVENT_FALLING_EDGE;
650 static enum hte_return process_hw_ts_thread(void *p)
654 struct gpio_v2_line_event le;
659 return HTE_CB_HANDLED;
664 memset(&le, 0, sizeof(le));
666 le.timestamp_ns = line->timestamp_ns;
667 edflags = READ_ONCE(line->edflags);
669 switch (edflags & GPIO_V2_LINE_EDGE_FLAGS) {
670 case GPIO_V2_LINE_FLAG_EDGE_BOTH:
671 level = (line->raw_level >= 0) ?
673 gpiod_get_raw_value_cansleep(line->desc);
675 if (edflags & GPIO_V2_LINE_FLAG_ACTIVE_LOW)
678 le.id = line_event_id(level);
680 case GPIO_V2_LINE_FLAG_EDGE_RISING:
681 le.id = GPIO_V2_LINE_EVENT_RISING_EDGE;
683 case GPIO_V2_LINE_FLAG_EDGE_FALLING:
684 le.id = GPIO_V2_LINE_EVENT_FALLING_EDGE;
687 return HTE_CB_HANDLED;
689 le.line_seqno = line->line_seqno;
690 le.seqno = (lr->num_lines == 1) ? le.line_seqno : line->req_seqno;
691 le.offset = gpio_chip_hwgpio(line->desc);
693 linereq_put_event(lr, &le);
695 return HTE_CB_HANDLED;
698 static enum hte_return process_hw_ts(struct hte_ts_data *ts, void *p)
705 return HTE_CB_HANDLED;
708 line->timestamp_ns = ts->tsc;
709 line->raw_level = ts->raw_level;
712 if (READ_ONCE(line->sw_debounced)) {
713 line->total_discard_seq++;
714 line->last_seqno = ts->seq;
715 mod_delayed_work(system_wq, &line->work,
716 usecs_to_jiffies(READ_ONCE(line->desc->debounce_period_us)));
718 if (unlikely(ts->seq < line->line_seqno))
719 return HTE_CB_HANDLED;
721 diff_seqno = ts->seq - line->line_seqno;
722 line->line_seqno = ts->seq;
723 if (lr->num_lines != 1)
724 line->req_seqno = atomic_add_return(diff_seqno,
727 return HTE_RUN_SECOND_CB;
730 return HTE_CB_HANDLED;
733 static int hte_edge_setup(struct line *line, u64 eflags)
736 unsigned long flags = 0;
737 struct hte_ts_desc *hdesc = &line->hdesc;
739 if (eflags & GPIO_V2_LINE_FLAG_EDGE_RISING)
740 flags |= test_bit(FLAG_ACTIVE_LOW, &line->desc->flags) ?
741 HTE_FALLING_EDGE_TS :
743 if (eflags & GPIO_V2_LINE_FLAG_EDGE_FALLING)
744 flags |= test_bit(FLAG_ACTIVE_LOW, &line->desc->flags) ?
748 line->total_discard_seq = 0;
750 hte_init_line_attr(hdesc, desc_to_gpio(line->desc), flags, NULL,
753 ret = hte_ts_get(NULL, hdesc, 0);
757 return hte_request_ts_ns(hdesc, process_hw_ts, process_hw_ts_thread,
763 static int hte_edge_setup(struct line *line, u64 eflags)
767 #endif /* CONFIG_HTE */
769 static irqreturn_t edge_irq_thread(int irq, void *p)
771 struct line *line = p;
772 struct linereq *lr = line->req;
773 struct gpio_v2_line_event le;
775 /* Do not leak kernel stack to userspace */
776 memset(&le, 0, sizeof(le));
778 if (line->timestamp_ns) {
779 le.timestamp_ns = line->timestamp_ns;
782 * We may be running from a nested threaded interrupt in
783 * which case we didn't get the timestamp from
784 * edge_irq_handler().
786 le.timestamp_ns = line_event_timestamp(line);
787 if (lr->num_lines != 1)
788 line->req_seqno = atomic_inc_return(&lr->seqno);
790 line->timestamp_ns = 0;
792 switch (READ_ONCE(line->edflags) & GPIO_V2_LINE_EDGE_FLAGS) {
793 case GPIO_V2_LINE_FLAG_EDGE_BOTH:
794 le.id = line_event_id(gpiod_get_value_cansleep(line->desc));
796 case GPIO_V2_LINE_FLAG_EDGE_RISING:
797 le.id = GPIO_V2_LINE_EVENT_RISING_EDGE;
799 case GPIO_V2_LINE_FLAG_EDGE_FALLING:
800 le.id = GPIO_V2_LINE_EVENT_FALLING_EDGE;
806 le.line_seqno = line->line_seqno;
807 le.seqno = (lr->num_lines == 1) ? le.line_seqno : line->req_seqno;
808 le.offset = gpio_chip_hwgpio(line->desc);
810 linereq_put_event(lr, &le);
815 static irqreturn_t edge_irq_handler(int irq, void *p)
817 struct line *line = p;
818 struct linereq *lr = line->req;
821 * Just store the timestamp in hardirq context so we get it as
822 * close in time as possible to the actual event.
824 line->timestamp_ns = line_event_timestamp(line);
826 if (lr->num_lines != 1)
827 line->req_seqno = atomic_inc_return(&lr->seqno);
829 return IRQ_WAKE_THREAD;
833 * returns the current debounced logical value.
835 static bool debounced_value(struct line *line)
840 * minor race - debouncer may be stopped here, so edge_detector_stop()
841 * must leave the value unchanged so the following will read the level
842 * from when the debouncer was last running.
844 value = READ_ONCE(line->level);
846 if (test_bit(FLAG_ACTIVE_LOW, &line->desc->flags))
852 static irqreturn_t debounce_irq_handler(int irq, void *p)
854 struct line *line = p;
856 mod_delayed_work(system_wq, &line->work,
857 usecs_to_jiffies(READ_ONCE(line->desc->debounce_period_us)));
862 static void debounce_work_func(struct work_struct *work)
864 struct gpio_v2_line_event le;
865 struct line *line = container_of(work, struct line, work.work);
867 u64 eflags, edflags = READ_ONCE(line->edflags);
872 if (edflags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE)
873 level = line->raw_level;
876 level = gpiod_get_raw_value_cansleep(line->desc);
878 pr_debug_ratelimited("debouncer failed to read line value\n");
882 if (READ_ONCE(line->level) == level)
885 WRITE_ONCE(line->level, level);
887 /* -- edge detection -- */
888 eflags = edflags & GPIO_V2_LINE_EDGE_FLAGS;
892 /* switch from physical level to logical - if they differ */
893 if (edflags & GPIO_V2_LINE_FLAG_ACTIVE_LOW)
896 /* ignore edges that are not being monitored */
897 if (((eflags == GPIO_V2_LINE_FLAG_EDGE_RISING) && !level) ||
898 ((eflags == GPIO_V2_LINE_FLAG_EDGE_FALLING) && level))
901 /* Do not leak kernel stack to userspace */
902 memset(&le, 0, sizeof(le));
905 le.timestamp_ns = line_event_timestamp(line);
906 le.offset = gpio_chip_hwgpio(line->desc);
908 if (edflags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE) {
909 /* discard events except the last one */
910 line->total_discard_seq -= 1;
911 diff_seqno = line->last_seqno - line->total_discard_seq -
913 line->line_seqno = line->last_seqno - line->total_discard_seq;
914 le.line_seqno = line->line_seqno;
915 le.seqno = (lr->num_lines == 1) ?
916 le.line_seqno : atomic_add_return(diff_seqno, &lr->seqno);
918 #endif /* CONFIG_HTE */
921 le.line_seqno = line->line_seqno;
922 le.seqno = (lr->num_lines == 1) ?
923 le.line_seqno : atomic_inc_return(&lr->seqno);
926 le.id = line_event_id(level);
928 linereq_put_event(lr, &le);
931 static int debounce_setup(struct line *line, unsigned int debounce_period_us)
933 unsigned long irqflags;
937 ret = gpiod_set_debounce(line->desc, debounce_period_us);
939 WRITE_ONCE(line->desc->debounce_period_us, debounce_period_us);
942 if (ret != -ENOTSUPP)
945 if (debounce_period_us) {
946 /* setup software debounce */
947 level = gpiod_get_raw_value_cansleep(line->desc);
951 if (!(IS_ENABLED(CONFIG_HTE) &&
952 test_bit(FLAG_EVENT_CLOCK_HTE, &line->desc->flags))) {
953 irq = gpiod_to_irq(line->desc);
957 irqflags = IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING;
958 ret = request_irq(irq, debounce_irq_handler, irqflags,
959 line->req->label, line);
964 ret = hte_edge_setup(line, GPIO_V2_LINE_FLAG_EDGE_BOTH);
969 WRITE_ONCE(line->level, level);
970 WRITE_ONCE(line->sw_debounced, 1);
975 static bool gpio_v2_line_config_debounced(struct gpio_v2_line_config *lc,
976 unsigned int line_idx)
979 u64 mask = BIT_ULL(line_idx);
981 for (i = 0; i < lc->num_attrs; i++) {
982 if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_DEBOUNCE) &&
983 (lc->attrs[i].mask & mask))
989 static u32 gpio_v2_line_config_debounce_period(struct gpio_v2_line_config *lc,
990 unsigned int line_idx)
993 u64 mask = BIT_ULL(line_idx);
995 for (i = 0; i < lc->num_attrs; i++) {
996 if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_DEBOUNCE) &&
997 (lc->attrs[i].mask & mask))
998 return lc->attrs[i].attr.debounce_period_us;
1003 static void edge_detector_stop(struct line *line)
1006 free_irq(line->irq, line);
1011 if (READ_ONCE(line->edflags) & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE)
1012 hte_ts_put(&line->hdesc);
1015 cancel_delayed_work_sync(&line->work);
1016 WRITE_ONCE(line->sw_debounced, 0);
1017 WRITE_ONCE(line->edflags, 0);
1019 WRITE_ONCE(line->desc->debounce_period_us, 0);
1020 /* do not change line->level - see comment in debounced_value() */
1023 static int edge_detector_setup(struct line *line,
1024 struct gpio_v2_line_config *lc,
1025 unsigned int line_idx, u64 edflags)
1027 u32 debounce_period_us;
1028 unsigned long irqflags = 0;
1032 eflags = edflags & GPIO_V2_LINE_EDGE_FLAGS;
1033 if (eflags && !kfifo_initialized(&line->req->events)) {
1034 ret = kfifo_alloc(&line->req->events,
1035 line->req->event_buffer_size, GFP_KERNEL);
1039 if (gpio_v2_line_config_debounced(lc, line_idx)) {
1040 debounce_period_us = gpio_v2_line_config_debounce_period(lc, line_idx);
1041 ret = debounce_setup(line, debounce_period_us);
1044 WRITE_ONCE(line->desc->debounce_period_us, debounce_period_us);
1047 /* detection disabled or sw debouncer will provide edge detection */
1048 if (!eflags || READ_ONCE(line->sw_debounced))
1051 if (IS_ENABLED(CONFIG_HTE) &&
1052 (edflags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE))
1053 return hte_edge_setup(line, edflags);
1055 irq = gpiod_to_irq(line->desc);
1059 if (eflags & GPIO_V2_LINE_FLAG_EDGE_RISING)
1060 irqflags |= test_bit(FLAG_ACTIVE_LOW, &line->desc->flags) ?
1061 IRQF_TRIGGER_FALLING : IRQF_TRIGGER_RISING;
1062 if (eflags & GPIO_V2_LINE_FLAG_EDGE_FALLING)
1063 irqflags |= test_bit(FLAG_ACTIVE_LOW, &line->desc->flags) ?
1064 IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING;
1065 irqflags |= IRQF_ONESHOT;
1067 /* Request a thread to read the events */
1068 ret = request_threaded_irq(irq, edge_irq_handler, edge_irq_thread,
1069 irqflags, line->req->label, line);
1077 static int edge_detector_update(struct line *line,
1078 struct gpio_v2_line_config *lc,
1079 unsigned int line_idx, u64 edflags)
1081 u64 active_edflags = READ_ONCE(line->edflags);
1082 unsigned int debounce_period_us =
1083 gpio_v2_line_config_debounce_period(lc, line_idx);
1085 if ((active_edflags == edflags) &&
1086 (READ_ONCE(line->desc->debounce_period_us) == debounce_period_us))
1089 /* sw debounced and still will be...*/
1090 if (debounce_period_us && READ_ONCE(line->sw_debounced)) {
1091 WRITE_ONCE(line->desc->debounce_period_us, debounce_period_us);
1095 /* reconfiguring edge detection or sw debounce being disabled */
1096 if ((line->irq && !READ_ONCE(line->sw_debounced)) ||
1097 (active_edflags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE) ||
1098 (!debounce_period_us && READ_ONCE(line->sw_debounced)))
1099 edge_detector_stop(line);
1101 return edge_detector_setup(line, lc, line_idx, edflags);
1104 static u64 gpio_v2_line_config_flags(struct gpio_v2_line_config *lc,
1105 unsigned int line_idx)
1108 u64 mask = BIT_ULL(line_idx);
1110 for (i = 0; i < lc->num_attrs; i++) {
1111 if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_FLAGS) &&
1112 (lc->attrs[i].mask & mask))
1113 return lc->attrs[i].attr.flags;
1118 static int gpio_v2_line_config_output_value(struct gpio_v2_line_config *lc,
1119 unsigned int line_idx)
1122 u64 mask = BIT_ULL(line_idx);
1124 for (i = 0; i < lc->num_attrs; i++) {
1125 if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_OUTPUT_VALUES) &&
1126 (lc->attrs[i].mask & mask))
1127 return !!(lc->attrs[i].attr.values & mask);
1132 static int gpio_v2_line_flags_validate(u64 flags)
1134 /* Return an error if an unknown flag is set */
1135 if (flags & ~GPIO_V2_LINE_VALID_FLAGS)
1138 if (!IS_ENABLED(CONFIG_HTE) &&
1139 (flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE))
1143 * Do not allow both INPUT and OUTPUT flags to be set as they are
1146 if ((flags & GPIO_V2_LINE_FLAG_INPUT) &&
1147 (flags & GPIO_V2_LINE_FLAG_OUTPUT))
1150 /* Only allow one event clock source */
1151 if (IS_ENABLED(CONFIG_HTE) &&
1152 (flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME) &&
1153 (flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE))
1156 /* Edge detection requires explicit input. */
1157 if ((flags & GPIO_V2_LINE_EDGE_FLAGS) &&
1158 !(flags & GPIO_V2_LINE_FLAG_INPUT))
1162 * Do not allow OPEN_SOURCE and OPEN_DRAIN flags in a single
1163 * request. If the hardware actually supports enabling both at the
1164 * same time the electrical result would be disastrous.
1166 if ((flags & GPIO_V2_LINE_FLAG_OPEN_DRAIN) &&
1167 (flags & GPIO_V2_LINE_FLAG_OPEN_SOURCE))
1170 /* Drive requires explicit output direction. */
1171 if ((flags & GPIO_V2_LINE_DRIVE_FLAGS) &&
1172 !(flags & GPIO_V2_LINE_FLAG_OUTPUT))
1175 /* Bias requires explicit direction. */
1176 if ((flags & GPIO_V2_LINE_BIAS_FLAGS) &&
1177 !(flags & GPIO_V2_LINE_DIRECTION_FLAGS))
1180 /* Only one bias flag can be set. */
1181 if (((flags & GPIO_V2_LINE_FLAG_BIAS_DISABLED) &&
1182 (flags & (GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN |
1183 GPIO_V2_LINE_FLAG_BIAS_PULL_UP))) ||
1184 ((flags & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN) &&
1185 (flags & GPIO_V2_LINE_FLAG_BIAS_PULL_UP)))
1191 static int gpio_v2_line_config_validate(struct gpio_v2_line_config *lc,
1192 unsigned int num_lines)
1198 if (lc->num_attrs > GPIO_V2_LINE_NUM_ATTRS_MAX)
1201 if (memchr_inv(lc->padding, 0, sizeof(lc->padding)))
1204 for (i = 0; i < num_lines; i++) {
1205 flags = gpio_v2_line_config_flags(lc, i);
1206 ret = gpio_v2_line_flags_validate(flags);
1210 /* debounce requires explicit input */
1211 if (gpio_v2_line_config_debounced(lc, i) &&
1212 !(flags & GPIO_V2_LINE_FLAG_INPUT))
1218 static void gpio_v2_line_config_flags_to_desc_flags(u64 flags,
1219 unsigned long *flagsp)
1221 assign_bit(FLAG_ACTIVE_LOW, flagsp,
1222 flags & GPIO_V2_LINE_FLAG_ACTIVE_LOW);
1224 if (flags & GPIO_V2_LINE_FLAG_OUTPUT)
1225 set_bit(FLAG_IS_OUT, flagsp);
1226 else if (flags & GPIO_V2_LINE_FLAG_INPUT)
1227 clear_bit(FLAG_IS_OUT, flagsp);
1229 assign_bit(FLAG_EDGE_RISING, flagsp,
1230 flags & GPIO_V2_LINE_FLAG_EDGE_RISING);
1231 assign_bit(FLAG_EDGE_FALLING, flagsp,
1232 flags & GPIO_V2_LINE_FLAG_EDGE_FALLING);
1234 assign_bit(FLAG_OPEN_DRAIN, flagsp,
1235 flags & GPIO_V2_LINE_FLAG_OPEN_DRAIN);
1236 assign_bit(FLAG_OPEN_SOURCE, flagsp,
1237 flags & GPIO_V2_LINE_FLAG_OPEN_SOURCE);
1239 assign_bit(FLAG_PULL_UP, flagsp,
1240 flags & GPIO_V2_LINE_FLAG_BIAS_PULL_UP);
1241 assign_bit(FLAG_PULL_DOWN, flagsp,
1242 flags & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN);
1243 assign_bit(FLAG_BIAS_DISABLE, flagsp,
1244 flags & GPIO_V2_LINE_FLAG_BIAS_DISABLED);
1246 assign_bit(FLAG_EVENT_CLOCK_REALTIME, flagsp,
1247 flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME);
1248 assign_bit(FLAG_EVENT_CLOCK_HTE, flagsp,
1249 flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE);
1252 static long linereq_get_values(struct linereq *lr, void __user *ip)
1254 struct gpio_v2_line_values lv;
1255 DECLARE_BITMAP(vals, GPIO_V2_LINES_MAX);
1256 struct gpio_desc **descs;
1257 unsigned int i, didx, num_get;
1261 /* NOTE: It's ok to read values of output lines. */
1262 if (copy_from_user(&lv, ip, sizeof(lv)))
1265 for (num_get = 0, i = 0; i < lr->num_lines; i++) {
1266 if (lv.mask & BIT_ULL(i)) {
1268 descs = &lr->lines[i].desc;
1276 descs = kmalloc_array(num_get, sizeof(*descs), GFP_KERNEL);
1279 for (didx = 0, i = 0; i < lr->num_lines; i++) {
1280 if (lv.mask & BIT_ULL(i)) {
1281 descs[didx] = lr->lines[i].desc;
1286 ret = gpiod_get_array_value_complex(false, true, num_get,
1295 for (didx = 0, i = 0; i < lr->num_lines; i++) {
1296 if (lv.mask & BIT_ULL(i)) {
1297 if (lr->lines[i].sw_debounced)
1298 val = debounced_value(&lr->lines[i]);
1300 val = test_bit(didx, vals);
1302 lv.bits |= BIT_ULL(i);
1307 if (copy_to_user(ip, &lv, sizeof(lv)))
1313 static long linereq_set_values_unlocked(struct linereq *lr,
1314 struct gpio_v2_line_values *lv)
1316 DECLARE_BITMAP(vals, GPIO_V2_LINES_MAX);
1317 struct gpio_desc **descs;
1318 unsigned int i, didx, num_set;
1321 bitmap_zero(vals, GPIO_V2_LINES_MAX);
1322 for (num_set = 0, i = 0; i < lr->num_lines; i++) {
1323 if (lv->mask & BIT_ULL(i)) {
1324 if (!test_bit(FLAG_IS_OUT, &lr->lines[i].desc->flags))
1326 if (lv->bits & BIT_ULL(i))
1327 __set_bit(num_set, vals);
1329 descs = &lr->lines[i].desc;
1336 /* build compacted desc array and values */
1337 descs = kmalloc_array(num_set, sizeof(*descs), GFP_KERNEL);
1340 for (didx = 0, i = 0; i < lr->num_lines; i++) {
1341 if (lv->mask & BIT_ULL(i)) {
1342 descs[didx] = lr->lines[i].desc;
1347 ret = gpiod_set_array_value_complex(false, true, num_set,
1355 static long linereq_set_values(struct linereq *lr, void __user *ip)
1357 struct gpio_v2_line_values lv;
1360 if (copy_from_user(&lv, ip, sizeof(lv)))
1363 mutex_lock(&lr->config_mutex);
1365 ret = linereq_set_values_unlocked(lr, &lv);
1367 mutex_unlock(&lr->config_mutex);
1372 static long linereq_set_config_unlocked(struct linereq *lr,
1373 struct gpio_v2_line_config *lc)
1375 struct gpio_desc *desc;
1381 for (i = 0; i < lr->num_lines; i++) {
1382 line = &lr->lines[i];
1383 desc = lr->lines[i].desc;
1384 flags = gpio_v2_line_config_flags(lc, i);
1385 gpio_v2_line_config_flags_to_desc_flags(flags, &desc->flags);
1386 edflags = flags & GPIO_V2_LINE_EDGE_DETECTOR_FLAGS;
1388 * Lines have to be requested explicitly for input
1389 * or output, else the line will be treated "as is".
1391 if (flags & GPIO_V2_LINE_FLAG_OUTPUT) {
1392 int val = gpio_v2_line_config_output_value(lc, i);
1394 edge_detector_stop(line);
1395 ret = gpiod_direction_output(desc, val);
1398 } else if (flags & GPIO_V2_LINE_FLAG_INPUT) {
1399 ret = gpiod_direction_input(desc);
1403 ret = edge_detector_update(line, lc, i, edflags);
1408 WRITE_ONCE(line->edflags, edflags);
1410 blocking_notifier_call_chain(&desc->gdev->notifier,
1411 GPIO_V2_LINE_CHANGED_CONFIG,
1417 static long linereq_set_config(struct linereq *lr, void __user *ip)
1419 struct gpio_v2_line_config lc;
1422 if (copy_from_user(&lc, ip, sizeof(lc)))
1425 ret = gpio_v2_line_config_validate(&lc, lr->num_lines);
1429 mutex_lock(&lr->config_mutex);
1431 ret = linereq_set_config_unlocked(lr, &lc);
1433 mutex_unlock(&lr->config_mutex);
1438 static long linereq_ioctl_unlocked(struct file *file, unsigned int cmd,
1441 struct linereq *lr = file->private_data;
1442 void __user *ip = (void __user *)arg;
1444 if (!lr->gdev->chip)
1448 case GPIO_V2_LINE_GET_VALUES_IOCTL:
1449 return linereq_get_values(lr, ip);
1450 case GPIO_V2_LINE_SET_VALUES_IOCTL:
1451 return linereq_set_values(lr, ip);
1452 case GPIO_V2_LINE_SET_CONFIG_IOCTL:
1453 return linereq_set_config(lr, ip);
1459 static long linereq_ioctl(struct file *file, unsigned int cmd,
1462 struct linereq *lr = file->private_data;
1464 return call_ioctl_locked(file, cmd, arg, lr->gdev,
1465 linereq_ioctl_unlocked);
1468 #ifdef CONFIG_COMPAT
1469 static long linereq_ioctl_compat(struct file *file, unsigned int cmd,
1472 return linereq_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
1476 static __poll_t linereq_poll_unlocked(struct file *file,
1477 struct poll_table_struct *wait)
1479 struct linereq *lr = file->private_data;
1480 __poll_t events = 0;
1482 if (!lr->gdev->chip)
1483 return EPOLLHUP | EPOLLERR;
1485 poll_wait(file, &lr->wait, wait);
1487 if (!kfifo_is_empty_spinlocked_noirqsave(&lr->events,
1489 events = EPOLLIN | EPOLLRDNORM;
1494 static __poll_t linereq_poll(struct file *file,
1495 struct poll_table_struct *wait)
1497 struct linereq *lr = file->private_data;
1499 return call_poll_locked(file, wait, lr->gdev, linereq_poll_unlocked);
1502 static ssize_t linereq_read_unlocked(struct file *file, char __user *buf,
1503 size_t count, loff_t *f_ps)
1505 struct linereq *lr = file->private_data;
1506 struct gpio_v2_line_event le;
1507 ssize_t bytes_read = 0;
1510 if (!lr->gdev->chip)
1513 if (count < sizeof(le))
1517 spin_lock(&lr->wait.lock);
1518 if (kfifo_is_empty(&lr->events)) {
1520 spin_unlock(&lr->wait.lock);
1524 if (file->f_flags & O_NONBLOCK) {
1525 spin_unlock(&lr->wait.lock);
1529 ret = wait_event_interruptible_locked(lr->wait,
1530 !kfifo_is_empty(&lr->events));
1532 spin_unlock(&lr->wait.lock);
1537 ret = kfifo_out(&lr->events, &le, 1);
1538 spin_unlock(&lr->wait.lock);
1541 * This should never happen - we were holding the
1542 * lock from the moment we learned the fifo is no
1543 * longer empty until now.
1549 if (copy_to_user(buf + bytes_read, &le, sizeof(le)))
1551 bytes_read += sizeof(le);
1552 } while (count >= bytes_read + sizeof(le));
1557 static ssize_t linereq_read(struct file *file, char __user *buf,
1558 size_t count, loff_t *f_ps)
1560 struct linereq *lr = file->private_data;
1562 return call_read_locked(file, buf, count, f_ps, lr->gdev,
1563 linereq_read_unlocked);
1566 static void linereq_free(struct linereq *lr)
1570 for (i = 0; i < lr->num_lines; i++) {
1571 if (lr->lines[i].desc) {
1572 edge_detector_stop(&lr->lines[i]);
1573 gpiod_free(lr->lines[i].desc);
1576 kfifo_free(&lr->events);
1578 gpio_device_put(lr->gdev);
1582 static int linereq_release(struct inode *inode, struct file *file)
1584 struct linereq *lr = file->private_data;
1590 #ifdef CONFIG_PROC_FS
1591 static void linereq_show_fdinfo(struct seq_file *out, struct file *file)
1593 struct linereq *lr = file->private_data;
1594 struct device *dev = &lr->gdev->dev;
1597 seq_printf(out, "gpio-chip:\t%s\n", dev_name(dev));
1599 for (i = 0; i < lr->num_lines; i++)
1600 seq_printf(out, "gpio-line:\t%d\n",
1601 gpio_chip_hwgpio(lr->lines[i].desc));
1605 static const struct file_operations line_fileops = {
1606 .release = linereq_release,
1607 .read = linereq_read,
1608 .poll = linereq_poll,
1609 .owner = THIS_MODULE,
1610 .llseek = noop_llseek,
1611 .unlocked_ioctl = linereq_ioctl,
1612 #ifdef CONFIG_COMPAT
1613 .compat_ioctl = linereq_ioctl_compat,
1615 #ifdef CONFIG_PROC_FS
1616 .show_fdinfo = linereq_show_fdinfo,
1620 static int linereq_create(struct gpio_device *gdev, void __user *ip)
1622 struct gpio_v2_line_request ulr;
1623 struct gpio_v2_line_config *lc;
1630 if (copy_from_user(&ulr, ip, sizeof(ulr)))
1633 if ((ulr.num_lines == 0) || (ulr.num_lines > GPIO_V2_LINES_MAX))
1636 if (memchr_inv(ulr.padding, 0, sizeof(ulr.padding)))
1640 ret = gpio_v2_line_config_validate(lc, ulr.num_lines);
1644 lr = kzalloc(struct_size(lr, lines, ulr.num_lines), GFP_KERNEL);
1648 lr->gdev = gpio_device_get(gdev);
1650 for (i = 0; i < ulr.num_lines; i++) {
1651 lr->lines[i].req = lr;
1652 WRITE_ONCE(lr->lines[i].sw_debounced, 0);
1653 INIT_DELAYED_WORK(&lr->lines[i].work, debounce_work_func);
1656 if (ulr.consumer[0] != '\0') {
1657 /* label is only initialized if consumer is set */
1658 lr->label = kstrndup(ulr.consumer, sizeof(ulr.consumer) - 1,
1662 goto out_free_linereq;
1666 mutex_init(&lr->config_mutex);
1667 init_waitqueue_head(&lr->wait);
1668 lr->event_buffer_size = ulr.event_buffer_size;
1669 if (lr->event_buffer_size == 0)
1670 lr->event_buffer_size = ulr.num_lines * 16;
1671 else if (lr->event_buffer_size > GPIO_V2_LINES_MAX * 16)
1672 lr->event_buffer_size = GPIO_V2_LINES_MAX * 16;
1674 atomic_set(&lr->seqno, 0);
1675 lr->num_lines = ulr.num_lines;
1677 /* Request each GPIO */
1678 for (i = 0; i < ulr.num_lines; i++) {
1679 u32 offset = ulr.offsets[i];
1680 struct gpio_desc *desc = gpiochip_get_desc(gdev->chip, offset);
1683 ret = PTR_ERR(desc);
1684 goto out_free_linereq;
1687 ret = gpiod_request_user(desc, lr->label);
1689 goto out_free_linereq;
1691 lr->lines[i].desc = desc;
1692 flags = gpio_v2_line_config_flags(lc, i);
1693 gpio_v2_line_config_flags_to_desc_flags(flags, &desc->flags);
1695 ret = gpiod_set_transitory(desc, false);
1697 goto out_free_linereq;
1699 edflags = flags & GPIO_V2_LINE_EDGE_DETECTOR_FLAGS;
1701 * Lines have to be requested explicitly for input
1702 * or output, else the line will be treated "as is".
1704 if (flags & GPIO_V2_LINE_FLAG_OUTPUT) {
1705 int val = gpio_v2_line_config_output_value(lc, i);
1707 ret = gpiod_direction_output(desc, val);
1709 goto out_free_linereq;
1710 } else if (flags & GPIO_V2_LINE_FLAG_INPUT) {
1711 ret = gpiod_direction_input(desc);
1713 goto out_free_linereq;
1715 ret = edge_detector_setup(&lr->lines[i], lc, i,
1718 goto out_free_linereq;
1721 lr->lines[i].edflags = edflags;
1723 blocking_notifier_call_chain(&desc->gdev->notifier,
1724 GPIO_V2_LINE_CHANGED_REQUESTED, desc);
1726 dev_dbg(&gdev->dev, "registered chardev handle for line %d\n",
1730 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
1733 goto out_free_linereq;
1736 file = anon_inode_getfile("gpio-line", &line_fileops, lr,
1737 O_RDONLY | O_CLOEXEC);
1739 ret = PTR_ERR(file);
1740 goto out_put_unused_fd;
1744 if (copy_to_user(ip, &ulr, sizeof(ulr))) {
1746 * fput() will trigger the release() callback, so do not go onto
1747 * the regular error cleanup path here.
1754 fd_install(fd, file);
1756 dev_dbg(&gdev->dev, "registered chardev handle for %d lines\n",
1768 #ifdef CONFIG_GPIO_CDEV_V1
1771 * GPIO line event management
1775 * struct lineevent_state - contains the state of a userspace event
1776 * @gdev: the GPIO device the event pertains to
1777 * @label: consumer label used to tag descriptors
1778 * @desc: the GPIO descriptor held by this event
1779 * @eflags: the event flags this line was requested with
1780 * @irq: the interrupt that trigger in response to events on this GPIO
1781 * @wait: wait queue that handles blocking reads of events
1782 * @events: KFIFO for the GPIO events
1783 * @timestamp: cache for the timestamp storing it between hardirq
1784 * and IRQ thread, used to bring the timestamp close to the actual
1787 struct lineevent_state {
1788 struct gpio_device *gdev;
1790 struct gpio_desc *desc;
1793 wait_queue_head_t wait;
1794 DECLARE_KFIFO(events, struct gpioevent_data, 16);
1798 #define GPIOEVENT_REQUEST_VALID_FLAGS \
1799 (GPIOEVENT_REQUEST_RISING_EDGE | \
1800 GPIOEVENT_REQUEST_FALLING_EDGE)
1802 static __poll_t lineevent_poll_unlocked(struct file *file,
1803 struct poll_table_struct *wait)
1805 struct lineevent_state *le = file->private_data;
1806 __poll_t events = 0;
1808 if (!le->gdev->chip)
1809 return EPOLLHUP | EPOLLERR;
1811 poll_wait(file, &le->wait, wait);
1813 if (!kfifo_is_empty_spinlocked_noirqsave(&le->events, &le->wait.lock))
1814 events = EPOLLIN | EPOLLRDNORM;
1819 static __poll_t lineevent_poll(struct file *file,
1820 struct poll_table_struct *wait)
1822 struct lineevent_state *le = file->private_data;
1824 return call_poll_locked(file, wait, le->gdev, lineevent_poll_unlocked);
1827 struct compat_gpioeevent_data {
1828 compat_u64 timestamp;
1832 static ssize_t lineevent_read_unlocked(struct file *file, char __user *buf,
1833 size_t count, loff_t *f_ps)
1835 struct lineevent_state *le = file->private_data;
1836 struct gpioevent_data ge;
1837 ssize_t bytes_read = 0;
1841 if (!le->gdev->chip)
1845 * When compatible system call is being used the struct gpioevent_data,
1846 * in case of at least ia32, has different size due to the alignment
1847 * differences. Because we have first member 64 bits followed by one of
1848 * 32 bits there is no gap between them. The only difference is the
1849 * padding at the end of the data structure. Hence, we calculate the
1850 * actual sizeof() and pass this as an argument to copy_to_user() to
1851 * drop unneeded bytes from the output.
1853 if (compat_need_64bit_alignment_fixup())
1854 ge_size = sizeof(struct compat_gpioeevent_data);
1856 ge_size = sizeof(struct gpioevent_data);
1857 if (count < ge_size)
1861 spin_lock(&le->wait.lock);
1862 if (kfifo_is_empty(&le->events)) {
1864 spin_unlock(&le->wait.lock);
1868 if (file->f_flags & O_NONBLOCK) {
1869 spin_unlock(&le->wait.lock);
1873 ret = wait_event_interruptible_locked(le->wait,
1874 !kfifo_is_empty(&le->events));
1876 spin_unlock(&le->wait.lock);
1881 ret = kfifo_out(&le->events, &ge, 1);
1882 spin_unlock(&le->wait.lock);
1885 * This should never happen - we were holding the lock
1886 * from the moment we learned the fifo is no longer
1893 if (copy_to_user(buf + bytes_read, &ge, ge_size))
1895 bytes_read += ge_size;
1896 } while (count >= bytes_read + ge_size);
1901 static ssize_t lineevent_read(struct file *file, char __user *buf,
1902 size_t count, loff_t *f_ps)
1904 struct lineevent_state *le = file->private_data;
1906 return call_read_locked(file, buf, count, f_ps, le->gdev,
1907 lineevent_read_unlocked);
1910 static void lineevent_free(struct lineevent_state *le)
1913 free_irq(le->irq, le);
1915 gpiod_free(le->desc);
1917 gpio_device_put(le->gdev);
1921 static int lineevent_release(struct inode *inode, struct file *file)
1923 lineevent_free(file->private_data);
1927 static long lineevent_ioctl_unlocked(struct file *file, unsigned int cmd,
1930 struct lineevent_state *le = file->private_data;
1931 void __user *ip = (void __user *)arg;
1932 struct gpiohandle_data ghd;
1934 if (!le->gdev->chip)
1938 * We can get the value for an event line but not set it,
1939 * because it is input by definition.
1941 if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
1944 memset(&ghd, 0, sizeof(ghd));
1946 val = gpiod_get_value_cansleep(le->desc);
1949 ghd.values[0] = val;
1951 if (copy_to_user(ip, &ghd, sizeof(ghd)))
1959 static long lineevent_ioctl(struct file *file, unsigned int cmd,
1962 struct lineevent_state *le = file->private_data;
1964 return call_ioctl_locked(file, cmd, arg, le->gdev,
1965 lineevent_ioctl_unlocked);
1968 #ifdef CONFIG_COMPAT
1969 static long lineevent_ioctl_compat(struct file *file, unsigned int cmd,
1972 return lineevent_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
1976 static const struct file_operations lineevent_fileops = {
1977 .release = lineevent_release,
1978 .read = lineevent_read,
1979 .poll = lineevent_poll,
1980 .owner = THIS_MODULE,
1981 .llseek = noop_llseek,
1982 .unlocked_ioctl = lineevent_ioctl,
1983 #ifdef CONFIG_COMPAT
1984 .compat_ioctl = lineevent_ioctl_compat,
1988 static irqreturn_t lineevent_irq_thread(int irq, void *p)
1990 struct lineevent_state *le = p;
1991 struct gpioevent_data ge;
1994 /* Do not leak kernel stack to userspace */
1995 memset(&ge, 0, sizeof(ge));
1998 * We may be running from a nested threaded interrupt in which case
1999 * we didn't get the timestamp from lineevent_irq_handler().
2002 ge.timestamp = ktime_get_ns();
2004 ge.timestamp = le->timestamp;
2006 if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE
2007 && le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
2008 int level = gpiod_get_value_cansleep(le->desc);
2011 /* Emit low-to-high event */
2012 ge.id = GPIOEVENT_EVENT_RISING_EDGE;
2014 /* Emit high-to-low event */
2015 ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
2016 } else if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE) {
2017 /* Emit low-to-high event */
2018 ge.id = GPIOEVENT_EVENT_RISING_EDGE;
2019 } else if (le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
2020 /* Emit high-to-low event */
2021 ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
2026 ret = kfifo_in_spinlocked_noirqsave(&le->events, &ge,
2029 wake_up_poll(&le->wait, EPOLLIN);
2031 pr_debug_ratelimited("event FIFO is full - event dropped\n");
2036 static irqreturn_t lineevent_irq_handler(int irq, void *p)
2038 struct lineevent_state *le = p;
2041 * Just store the timestamp in hardirq context so we get it as
2042 * close in time as possible to the actual event.
2044 le->timestamp = ktime_get_ns();
2046 return IRQ_WAKE_THREAD;
2049 static int lineevent_create(struct gpio_device *gdev, void __user *ip)
2051 struct gpioevent_request eventreq;
2052 struct lineevent_state *le;
2053 struct gpio_desc *desc;
2060 int irq, irqflags = 0;
2062 if (copy_from_user(&eventreq, ip, sizeof(eventreq)))
2065 offset = eventreq.lineoffset;
2066 lflags = eventreq.handleflags;
2067 eflags = eventreq.eventflags;
2069 desc = gpiochip_get_desc(gdev->chip, offset);
2071 return PTR_ERR(desc);
2073 /* Return an error if a unknown flag is set */
2074 if ((lflags & ~GPIOHANDLE_REQUEST_VALID_FLAGS) ||
2075 (eflags & ~GPIOEVENT_REQUEST_VALID_FLAGS))
2078 /* This is just wrong: we don't look for events on output lines */
2079 if ((lflags & GPIOHANDLE_REQUEST_OUTPUT) ||
2080 (lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN) ||
2081 (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE))
2084 /* Only one bias flag can be set. */
2085 if (((lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE) &&
2086 (lflags & (GPIOHANDLE_REQUEST_BIAS_PULL_DOWN |
2087 GPIOHANDLE_REQUEST_BIAS_PULL_UP))) ||
2088 ((lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN) &&
2089 (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)))
2092 le = kzalloc(sizeof(*le), GFP_KERNEL);
2095 le->gdev = gpio_device_get(gdev);
2097 if (eventreq.consumer_label[0] != '\0') {
2098 /* label is only initialized if consumer_label is set */
2099 le->label = kstrndup(eventreq.consumer_label,
2100 sizeof(eventreq.consumer_label) - 1,
2108 ret = gpiod_request_user(desc, le->label);
2112 le->eflags = eflags;
2114 linehandle_flags_to_desc_flags(lflags, &desc->flags);
2116 ret = gpiod_direction_input(desc);
2120 blocking_notifier_call_chain(&desc->gdev->notifier,
2121 GPIO_V2_LINE_CHANGED_REQUESTED, desc);
2123 irq = gpiod_to_irq(desc);
2129 if (eflags & GPIOEVENT_REQUEST_RISING_EDGE)
2130 irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
2131 IRQF_TRIGGER_FALLING : IRQF_TRIGGER_RISING;
2132 if (eflags & GPIOEVENT_REQUEST_FALLING_EDGE)
2133 irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
2134 IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING;
2135 irqflags |= IRQF_ONESHOT;
2137 INIT_KFIFO(le->events);
2138 init_waitqueue_head(&le->wait);
2140 /* Request a thread to read the events */
2141 ret = request_threaded_irq(irq,
2142 lineevent_irq_handler,
2143 lineevent_irq_thread,
2152 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
2158 file = anon_inode_getfile("gpio-event",
2161 O_RDONLY | O_CLOEXEC);
2163 ret = PTR_ERR(file);
2164 goto out_put_unused_fd;
2168 if (copy_to_user(ip, &eventreq, sizeof(eventreq))) {
2170 * fput() will trigger the release() callback, so do not go onto
2171 * the regular error cleanup path here.
2178 fd_install(fd, file);
2189 static void gpio_v2_line_info_to_v1(struct gpio_v2_line_info *info_v2,
2190 struct gpioline_info *info_v1)
2192 u64 flagsv2 = info_v2->flags;
2194 memcpy(info_v1->name, info_v2->name, sizeof(info_v1->name));
2195 memcpy(info_v1->consumer, info_v2->consumer, sizeof(info_v1->consumer));
2196 info_v1->line_offset = info_v2->offset;
2199 if (flagsv2 & GPIO_V2_LINE_FLAG_USED)
2200 info_v1->flags |= GPIOLINE_FLAG_KERNEL;
2202 if (flagsv2 & GPIO_V2_LINE_FLAG_OUTPUT)
2203 info_v1->flags |= GPIOLINE_FLAG_IS_OUT;
2205 if (flagsv2 & GPIO_V2_LINE_FLAG_ACTIVE_LOW)
2206 info_v1->flags |= GPIOLINE_FLAG_ACTIVE_LOW;
2208 if (flagsv2 & GPIO_V2_LINE_FLAG_OPEN_DRAIN)
2209 info_v1->flags |= GPIOLINE_FLAG_OPEN_DRAIN;
2210 if (flagsv2 & GPIO_V2_LINE_FLAG_OPEN_SOURCE)
2211 info_v1->flags |= GPIOLINE_FLAG_OPEN_SOURCE;
2213 if (flagsv2 & GPIO_V2_LINE_FLAG_BIAS_PULL_UP)
2214 info_v1->flags |= GPIOLINE_FLAG_BIAS_PULL_UP;
2215 if (flagsv2 & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN)
2216 info_v1->flags |= GPIOLINE_FLAG_BIAS_PULL_DOWN;
2217 if (flagsv2 & GPIO_V2_LINE_FLAG_BIAS_DISABLED)
2218 info_v1->flags |= GPIOLINE_FLAG_BIAS_DISABLE;
2221 static void gpio_v2_line_info_changed_to_v1(
2222 struct gpio_v2_line_info_changed *lic_v2,
2223 struct gpioline_info_changed *lic_v1)
2225 memset(lic_v1, 0, sizeof(*lic_v1));
2226 gpio_v2_line_info_to_v1(&lic_v2->info, &lic_v1->info);
2227 lic_v1->timestamp = lic_v2->timestamp_ns;
2228 lic_v1->event_type = lic_v2->event_type;
2231 #endif /* CONFIG_GPIO_CDEV_V1 */
2233 static void gpio_desc_to_lineinfo(struct gpio_desc *desc,
2234 struct gpio_v2_line_info *info)
2236 struct gpio_chip *gc = desc->gdev->chip;
2237 bool ok_for_pinctrl;
2238 unsigned long flags;
2239 u32 debounce_period_us;
2240 unsigned int num_attrs = 0;
2242 memset(info, 0, sizeof(*info));
2243 info->offset = gpio_chip_hwgpio(desc);
2246 * This function takes a mutex so we must check this before taking
2249 * FIXME: find a non-racy way to retrieve this information. Maybe a
2250 * lock common to both frameworks?
2253 pinctrl_gpio_can_use_line(gc->base + info->offset);
2255 spin_lock_irqsave(&gpio_lock, flags);
2258 strscpy(info->name, desc->name, sizeof(info->name));
2261 strscpy(info->consumer, desc->label, sizeof(info->consumer));
2264 * Userspace only need to know that the kernel is using this GPIO so
2268 if (test_bit(FLAG_REQUESTED, &desc->flags) ||
2269 test_bit(FLAG_IS_HOGGED, &desc->flags) ||
2270 test_bit(FLAG_USED_AS_IRQ, &desc->flags) ||
2271 test_bit(FLAG_EXPORT, &desc->flags) ||
2272 test_bit(FLAG_SYSFS, &desc->flags) ||
2273 !gpiochip_line_is_valid(gc, info->offset) ||
2275 info->flags |= GPIO_V2_LINE_FLAG_USED;
2277 if (test_bit(FLAG_IS_OUT, &desc->flags))
2278 info->flags |= GPIO_V2_LINE_FLAG_OUTPUT;
2280 info->flags |= GPIO_V2_LINE_FLAG_INPUT;
2282 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2283 info->flags |= GPIO_V2_LINE_FLAG_ACTIVE_LOW;
2285 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
2286 info->flags |= GPIO_V2_LINE_FLAG_OPEN_DRAIN;
2287 if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
2288 info->flags |= GPIO_V2_LINE_FLAG_OPEN_SOURCE;
2290 if (test_bit(FLAG_BIAS_DISABLE, &desc->flags))
2291 info->flags |= GPIO_V2_LINE_FLAG_BIAS_DISABLED;
2292 if (test_bit(FLAG_PULL_DOWN, &desc->flags))
2293 info->flags |= GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN;
2294 if (test_bit(FLAG_PULL_UP, &desc->flags))
2295 info->flags |= GPIO_V2_LINE_FLAG_BIAS_PULL_UP;
2297 if (test_bit(FLAG_EDGE_RISING, &desc->flags))
2298 info->flags |= GPIO_V2_LINE_FLAG_EDGE_RISING;
2299 if (test_bit(FLAG_EDGE_FALLING, &desc->flags))
2300 info->flags |= GPIO_V2_LINE_FLAG_EDGE_FALLING;
2302 if (test_bit(FLAG_EVENT_CLOCK_REALTIME, &desc->flags))
2303 info->flags |= GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME;
2304 else if (test_bit(FLAG_EVENT_CLOCK_HTE, &desc->flags))
2305 info->flags |= GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE;
2307 debounce_period_us = READ_ONCE(desc->debounce_period_us);
2308 if (debounce_period_us) {
2309 info->attrs[num_attrs].id = GPIO_V2_LINE_ATTR_ID_DEBOUNCE;
2310 info->attrs[num_attrs].debounce_period_us = debounce_period_us;
2313 info->num_attrs = num_attrs;
2315 spin_unlock_irqrestore(&gpio_lock, flags);
2318 struct gpio_chardev_data {
2319 struct gpio_device *gdev;
2320 wait_queue_head_t wait;
2321 DECLARE_KFIFO(events, struct gpio_v2_line_info_changed, 32);
2322 struct notifier_block lineinfo_changed_nb;
2323 unsigned long *watched_lines;
2324 #ifdef CONFIG_GPIO_CDEV_V1
2325 atomic_t watch_abi_version;
2329 static int chipinfo_get(struct gpio_chardev_data *cdev, void __user *ip)
2331 struct gpio_device *gdev = cdev->gdev;
2332 struct gpiochip_info chipinfo;
2334 memset(&chipinfo, 0, sizeof(chipinfo));
2336 strscpy(chipinfo.name, dev_name(&gdev->dev), sizeof(chipinfo.name));
2337 strscpy(chipinfo.label, gdev->label, sizeof(chipinfo.label));
2338 chipinfo.lines = gdev->ngpio;
2339 if (copy_to_user(ip, &chipinfo, sizeof(chipinfo)))
2344 #ifdef CONFIG_GPIO_CDEV_V1
2346 * returns 0 if the versions match, else the previously selected ABI version
2348 static int lineinfo_ensure_abi_version(struct gpio_chardev_data *cdata,
2349 unsigned int version)
2351 int abiv = atomic_cmpxchg(&cdata->watch_abi_version, 0, version);
2353 if (abiv == version)
2359 static int lineinfo_get_v1(struct gpio_chardev_data *cdev, void __user *ip,
2362 struct gpio_desc *desc;
2363 struct gpioline_info lineinfo;
2364 struct gpio_v2_line_info lineinfo_v2;
2366 if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
2369 /* this doubles as a range check on line_offset */
2370 desc = gpiochip_get_desc(cdev->gdev->chip, lineinfo.line_offset);
2372 return PTR_ERR(desc);
2375 if (lineinfo_ensure_abi_version(cdev, 1))
2378 if (test_and_set_bit(lineinfo.line_offset, cdev->watched_lines))
2382 gpio_desc_to_lineinfo(desc, &lineinfo_v2);
2383 gpio_v2_line_info_to_v1(&lineinfo_v2, &lineinfo);
2385 if (copy_to_user(ip, &lineinfo, sizeof(lineinfo))) {
2387 clear_bit(lineinfo.line_offset, cdev->watched_lines);
2395 static int lineinfo_get(struct gpio_chardev_data *cdev, void __user *ip,
2398 struct gpio_desc *desc;
2399 struct gpio_v2_line_info lineinfo;
2401 if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
2404 if (memchr_inv(lineinfo.padding, 0, sizeof(lineinfo.padding)))
2407 desc = gpiochip_get_desc(cdev->gdev->chip, lineinfo.offset);
2409 return PTR_ERR(desc);
2412 #ifdef CONFIG_GPIO_CDEV_V1
2413 if (lineinfo_ensure_abi_version(cdev, 2))
2416 if (test_and_set_bit(lineinfo.offset, cdev->watched_lines))
2419 gpio_desc_to_lineinfo(desc, &lineinfo);
2421 if (copy_to_user(ip, &lineinfo, sizeof(lineinfo))) {
2423 clear_bit(lineinfo.offset, cdev->watched_lines);
2430 static int lineinfo_unwatch(struct gpio_chardev_data *cdev, void __user *ip)
2434 if (copy_from_user(&offset, ip, sizeof(offset)))
2437 if (offset >= cdev->gdev->ngpio)
2440 if (!test_and_clear_bit(offset, cdev->watched_lines))
2447 * gpio_ioctl() - ioctl handler for the GPIO chardev
2449 static long gpio_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
2451 struct gpio_chardev_data *cdev = file->private_data;
2452 struct gpio_device *gdev = cdev->gdev;
2453 void __user *ip = (void __user *)arg;
2455 /* We fail any subsequent ioctl():s when the chip is gone */
2459 /* Fill in the struct and pass to userspace */
2461 case GPIO_GET_CHIPINFO_IOCTL:
2462 return chipinfo_get(cdev, ip);
2463 #ifdef CONFIG_GPIO_CDEV_V1
2464 case GPIO_GET_LINEHANDLE_IOCTL:
2465 return linehandle_create(gdev, ip);
2466 case GPIO_GET_LINEEVENT_IOCTL:
2467 return lineevent_create(gdev, ip);
2468 case GPIO_GET_LINEINFO_IOCTL:
2469 return lineinfo_get_v1(cdev, ip, false);
2470 case GPIO_GET_LINEINFO_WATCH_IOCTL:
2471 return lineinfo_get_v1(cdev, ip, true);
2472 #endif /* CONFIG_GPIO_CDEV_V1 */
2473 case GPIO_V2_GET_LINEINFO_IOCTL:
2474 return lineinfo_get(cdev, ip, false);
2475 case GPIO_V2_GET_LINEINFO_WATCH_IOCTL:
2476 return lineinfo_get(cdev, ip, true);
2477 case GPIO_V2_GET_LINE_IOCTL:
2478 return linereq_create(gdev, ip);
2479 case GPIO_GET_LINEINFO_UNWATCH_IOCTL:
2480 return lineinfo_unwatch(cdev, ip);
2486 #ifdef CONFIG_COMPAT
2487 static long gpio_ioctl_compat(struct file *file, unsigned int cmd,
2490 return gpio_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
2494 static struct gpio_chardev_data *
2495 to_gpio_chardev_data(struct notifier_block *nb)
2497 return container_of(nb, struct gpio_chardev_data, lineinfo_changed_nb);
2500 static int lineinfo_changed_notify(struct notifier_block *nb,
2501 unsigned long action, void *data)
2503 struct gpio_chardev_data *cdev = to_gpio_chardev_data(nb);
2504 struct gpio_v2_line_info_changed chg;
2505 struct gpio_desc *desc = data;
2508 if (!test_bit(gpio_chip_hwgpio(desc), cdev->watched_lines))
2511 memset(&chg, 0, sizeof(chg));
2512 chg.event_type = action;
2513 chg.timestamp_ns = ktime_get_ns();
2514 gpio_desc_to_lineinfo(desc, &chg.info);
2516 ret = kfifo_in_spinlocked(&cdev->events, &chg, 1, &cdev->wait.lock);
2518 wake_up_poll(&cdev->wait, EPOLLIN);
2520 pr_debug_ratelimited("lineinfo event FIFO is full - event dropped\n");
2525 static __poll_t lineinfo_watch_poll_unlocked(struct file *file,
2526 struct poll_table_struct *pollt)
2528 struct gpio_chardev_data *cdev = file->private_data;
2529 __poll_t events = 0;
2531 if (!cdev->gdev->chip)
2532 return EPOLLHUP | EPOLLERR;
2534 poll_wait(file, &cdev->wait, pollt);
2536 if (!kfifo_is_empty_spinlocked_noirqsave(&cdev->events,
2538 events = EPOLLIN | EPOLLRDNORM;
2543 static __poll_t lineinfo_watch_poll(struct file *file,
2544 struct poll_table_struct *pollt)
2546 struct gpio_chardev_data *cdev = file->private_data;
2548 return call_poll_locked(file, pollt, cdev->gdev,
2549 lineinfo_watch_poll_unlocked);
2552 static ssize_t lineinfo_watch_read_unlocked(struct file *file, char __user *buf,
2553 size_t count, loff_t *off)
2555 struct gpio_chardev_data *cdev = file->private_data;
2556 struct gpio_v2_line_info_changed event;
2557 ssize_t bytes_read = 0;
2561 if (!cdev->gdev->chip)
2564 #ifndef CONFIG_GPIO_CDEV_V1
2565 event_size = sizeof(struct gpio_v2_line_info_changed);
2566 if (count < event_size)
2571 spin_lock(&cdev->wait.lock);
2572 if (kfifo_is_empty(&cdev->events)) {
2574 spin_unlock(&cdev->wait.lock);
2578 if (file->f_flags & O_NONBLOCK) {
2579 spin_unlock(&cdev->wait.lock);
2583 ret = wait_event_interruptible_locked(cdev->wait,
2584 !kfifo_is_empty(&cdev->events));
2586 spin_unlock(&cdev->wait.lock);
2590 #ifdef CONFIG_GPIO_CDEV_V1
2591 /* must be after kfifo check so watch_abi_version is set */
2592 if (atomic_read(&cdev->watch_abi_version) == 2)
2593 event_size = sizeof(struct gpio_v2_line_info_changed);
2595 event_size = sizeof(struct gpioline_info_changed);
2596 if (count < event_size) {
2597 spin_unlock(&cdev->wait.lock);
2601 ret = kfifo_out(&cdev->events, &event, 1);
2602 spin_unlock(&cdev->wait.lock);
2606 /* We should never get here. See lineevent_read(). */
2609 #ifdef CONFIG_GPIO_CDEV_V1
2610 if (event_size == sizeof(struct gpio_v2_line_info_changed)) {
2611 if (copy_to_user(buf + bytes_read, &event, event_size))
2614 struct gpioline_info_changed event_v1;
2616 gpio_v2_line_info_changed_to_v1(&event, &event_v1);
2617 if (copy_to_user(buf + bytes_read, &event_v1,
2622 if (copy_to_user(buf + bytes_read, &event, event_size))
2625 bytes_read += event_size;
2626 } while (count >= bytes_read + sizeof(event));
2631 static ssize_t lineinfo_watch_read(struct file *file, char __user *buf,
2632 size_t count, loff_t *off)
2634 struct gpio_chardev_data *cdev = file->private_data;
2636 return call_read_locked(file, buf, count, off, cdev->gdev,
2637 lineinfo_watch_read_unlocked);
2641 * gpio_chrdev_open() - open the chardev for ioctl operations
2642 * @inode: inode for this chardev
2643 * @file: file struct for storing private data
2644 * Returns 0 on success
2646 static int gpio_chrdev_open(struct inode *inode, struct file *file)
2648 struct gpio_device *gdev = container_of(inode->i_cdev,
2649 struct gpio_device, chrdev);
2650 struct gpio_chardev_data *cdev;
2653 down_read(&gdev->sem);
2655 /* Fail on open if the backing gpiochip is gone */
2661 cdev = kzalloc(sizeof(*cdev), GFP_KERNEL);
2665 cdev->watched_lines = bitmap_zalloc(gdev->chip->ngpio, GFP_KERNEL);
2666 if (!cdev->watched_lines)
2669 init_waitqueue_head(&cdev->wait);
2670 INIT_KFIFO(cdev->events);
2671 cdev->gdev = gpio_device_get(gdev);
2673 cdev->lineinfo_changed_nb.notifier_call = lineinfo_changed_notify;
2674 ret = blocking_notifier_chain_register(&gdev->notifier,
2675 &cdev->lineinfo_changed_nb);
2677 goto out_free_bitmap;
2679 file->private_data = cdev;
2681 ret = nonseekable_open(inode, file);
2683 goto out_unregister_notifier;
2685 up_read(&gdev->sem);
2689 out_unregister_notifier:
2690 blocking_notifier_chain_unregister(&gdev->notifier,
2691 &cdev->lineinfo_changed_nb);
2693 gpio_device_put(gdev);
2694 bitmap_free(cdev->watched_lines);
2698 up_read(&gdev->sem);
2703 * gpio_chrdev_release() - close chardev after ioctl operations
2704 * @inode: inode for this chardev
2705 * @file: file struct for storing private data
2706 * Returns 0 on success
2708 static int gpio_chrdev_release(struct inode *inode, struct file *file)
2710 struct gpio_chardev_data *cdev = file->private_data;
2711 struct gpio_device *gdev = cdev->gdev;
2713 bitmap_free(cdev->watched_lines);
2714 blocking_notifier_chain_unregister(&gdev->notifier,
2715 &cdev->lineinfo_changed_nb);
2716 gpio_device_put(gdev);
2722 static const struct file_operations gpio_fileops = {
2723 .release = gpio_chrdev_release,
2724 .open = gpio_chrdev_open,
2725 .poll = lineinfo_watch_poll,
2726 .read = lineinfo_watch_read,
2727 .owner = THIS_MODULE,
2728 .llseek = no_llseek,
2729 .unlocked_ioctl = gpio_ioctl,
2730 #ifdef CONFIG_COMPAT
2731 .compat_ioctl = gpio_ioctl_compat,
2735 int gpiolib_cdev_register(struct gpio_device *gdev, dev_t devt)
2739 cdev_init(&gdev->chrdev, &gpio_fileops);
2740 gdev->chrdev.owner = THIS_MODULE;
2741 gdev->dev.devt = MKDEV(MAJOR(devt), gdev->id);
2743 ret = cdev_device_add(&gdev->chrdev, &gdev->dev);
2747 chip_dbg(gdev->chip, "added GPIO chardev (%d:%d)\n",
2748 MAJOR(devt), gdev->id);
2753 void gpiolib_cdev_unregister(struct gpio_device *gdev)
2755 cdev_device_del(&gdev->chrdev, &gdev->dev);