1 // SPDX-License-Identifier: GPL-2.0
3 #include <linux/anon_inodes.h>
4 #include <linux/atomic.h>
5 #include <linux/bitmap.h>
6 #include <linux/build_bug.h>
7 #include <linux/cdev.h>
8 #include <linux/compat.h>
9 #include <linux/compiler.h>
10 #include <linux/device.h>
11 #include <linux/err.h>
12 #include <linux/file.h>
13 #include <linux/gpio.h>
14 #include <linux/gpio/driver.h>
15 #include <linux/interrupt.h>
16 #include <linux/irqreturn.h>
17 #include <linux/kernel.h>
18 #include <linux/kfifo.h>
19 #include <linux/module.h>
20 #include <linux/mutex.h>
21 #include <linux/pinctrl/consumer.h>
22 #include <linux/poll.h>
23 #include <linux/spinlock.h>
24 #include <linux/timekeeping.h>
25 #include <linux/uaccess.h>
26 #include <linux/workqueue.h>
27 #include <linux/hte.h>
28 #include <uapi/linux/gpio.h>
31 #include "gpiolib-cdev.h"
34 * Array sizes must ensure 64-bit alignment and not create holes in the
37 static_assert(IS_ALIGNED(GPIO_V2_LINES_MAX, 2));
38 static_assert(IS_ALIGNED(GPIO_MAX_NAME_SIZE, 8));
41 * Check that uAPI structs are 64-bit aligned for 32/64-bit compatibility
43 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_attribute), 8));
44 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_config_attribute), 8));
45 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_config), 8));
46 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_request), 8));
47 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_info), 8));
48 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_info_changed), 8));
49 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_event), 8));
50 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_values), 8));
52 /* Character device interface to GPIO.
54 * The GPIO character device, /dev/gpiochipN, provides userspace an
55 * interface to gpiolib GPIOs via ioctl()s.
58 typedef __poll_t (*poll_fn)(struct file *, struct poll_table_struct *);
59 typedef long (*ioctl_fn)(struct file *, unsigned int, unsigned long);
60 typedef ssize_t (*read_fn)(struct file *, char __user *,
61 size_t count, loff_t *);
63 static __poll_t call_poll_locked(struct file *file,
64 struct poll_table_struct *wait,
65 struct gpio_device *gdev, poll_fn func)
69 down_read(&gdev->sem);
70 ret = func(file, wait);
76 static long call_ioctl_locked(struct file *file, unsigned int cmd,
77 unsigned long arg, struct gpio_device *gdev,
82 down_read(&gdev->sem);
83 ret = func(file, cmd, arg);
89 static ssize_t call_read_locked(struct file *file, char __user *buf,
90 size_t count, loff_t *f_ps,
91 struct gpio_device *gdev, read_fn func)
95 down_read(&gdev->sem);
96 ret = func(file, buf, count, f_ps);
103 * GPIO line handle management
106 #ifdef CONFIG_GPIO_CDEV_V1
108 * struct linehandle_state - contains the state of a userspace handle
109 * @gdev: the GPIO device the handle pertains to
110 * @label: consumer label used to tag descriptors
111 * @descs: the GPIO descriptors held by this handle
112 * @num_descs: the number of descriptors held in the descs array
114 struct linehandle_state {
115 struct gpio_device *gdev;
117 struct gpio_desc *descs[GPIOHANDLES_MAX];
121 #define GPIOHANDLE_REQUEST_VALID_FLAGS \
122 (GPIOHANDLE_REQUEST_INPUT | \
123 GPIOHANDLE_REQUEST_OUTPUT | \
124 GPIOHANDLE_REQUEST_ACTIVE_LOW | \
125 GPIOHANDLE_REQUEST_BIAS_PULL_UP | \
126 GPIOHANDLE_REQUEST_BIAS_PULL_DOWN | \
127 GPIOHANDLE_REQUEST_BIAS_DISABLE | \
128 GPIOHANDLE_REQUEST_OPEN_DRAIN | \
129 GPIOHANDLE_REQUEST_OPEN_SOURCE)
131 static int linehandle_validate_flags(u32 flags)
133 /* Return an error if an unknown flag is set */
134 if (flags & ~GPIOHANDLE_REQUEST_VALID_FLAGS)
138 * Do not allow both INPUT & OUTPUT flags to be set as they are
141 if ((flags & GPIOHANDLE_REQUEST_INPUT) &&
142 (flags & GPIOHANDLE_REQUEST_OUTPUT))
146 * Do not allow OPEN_SOURCE & OPEN_DRAIN flags in a single request. If
147 * the hardware actually supports enabling both at the same time the
148 * electrical result would be disastrous.
150 if ((flags & GPIOHANDLE_REQUEST_OPEN_DRAIN) &&
151 (flags & GPIOHANDLE_REQUEST_OPEN_SOURCE))
154 /* OPEN_DRAIN and OPEN_SOURCE flags only make sense for output mode. */
155 if (!(flags & GPIOHANDLE_REQUEST_OUTPUT) &&
156 ((flags & GPIOHANDLE_REQUEST_OPEN_DRAIN) ||
157 (flags & GPIOHANDLE_REQUEST_OPEN_SOURCE)))
160 /* Bias flags only allowed for input or output mode. */
161 if (!((flags & GPIOHANDLE_REQUEST_INPUT) ||
162 (flags & GPIOHANDLE_REQUEST_OUTPUT)) &&
163 ((flags & GPIOHANDLE_REQUEST_BIAS_DISABLE) ||
164 (flags & GPIOHANDLE_REQUEST_BIAS_PULL_UP) ||
165 (flags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN)))
168 /* Only one bias flag can be set. */
169 if (((flags & GPIOHANDLE_REQUEST_BIAS_DISABLE) &&
170 (flags & (GPIOHANDLE_REQUEST_BIAS_PULL_DOWN |
171 GPIOHANDLE_REQUEST_BIAS_PULL_UP))) ||
172 ((flags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN) &&
173 (flags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)))
179 static void linehandle_flags_to_desc_flags(u32 lflags, unsigned long *flagsp)
181 assign_bit(FLAG_ACTIVE_LOW, flagsp,
182 lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW);
183 assign_bit(FLAG_OPEN_DRAIN, flagsp,
184 lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN);
185 assign_bit(FLAG_OPEN_SOURCE, flagsp,
186 lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE);
187 assign_bit(FLAG_PULL_UP, flagsp,
188 lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP);
189 assign_bit(FLAG_PULL_DOWN, flagsp,
190 lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN);
191 assign_bit(FLAG_BIAS_DISABLE, flagsp,
192 lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE);
195 static long linehandle_set_config(struct linehandle_state *lh,
198 struct gpiohandle_config gcnf;
199 struct gpio_desc *desc;
203 if (copy_from_user(&gcnf, ip, sizeof(gcnf)))
207 ret = linehandle_validate_flags(lflags);
211 for (i = 0; i < lh->num_descs; i++) {
213 linehandle_flags_to_desc_flags(gcnf.flags, &desc->flags);
216 * Lines have to be requested explicitly for input
217 * or output, else the line will be treated "as is".
219 if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
220 int val = !!gcnf.default_values[i];
222 ret = gpiod_direction_output(desc, val);
225 } else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
226 ret = gpiod_direction_input(desc);
231 blocking_notifier_call_chain(&desc->gdev->notifier,
232 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 put_device(&lh->gdev->dev);
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);
365 get_device(&gdev->dev);
367 if (handlereq.consumer_label[0] != '\0') {
368 /* label is only initialized if consumer_label is set */
369 lh->label = kstrndup(handlereq.consumer_label,
370 sizeof(handlereq.consumer_label) - 1,
378 lh->num_descs = handlereq.lines;
380 /* Request each GPIO */
381 for (i = 0; i < handlereq.lines; i++) {
382 u32 offset = handlereq.lineoffsets[i];
383 struct gpio_desc *desc = gpiochip_get_desc(gdev->chip, offset);
390 ret = gpiod_request_user(desc, lh->label);
394 linehandle_flags_to_desc_flags(handlereq.flags, &desc->flags);
396 ret = gpiod_set_transitory(desc, false);
401 * Lines have to be requested explicitly for input
402 * or output, else the line will be treated "as is".
404 if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
405 int val = !!handlereq.default_values[i];
407 ret = gpiod_direction_output(desc, val);
410 } else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
411 ret = gpiod_direction_input(desc);
416 blocking_notifier_call_chain(&desc->gdev->notifier,
417 GPIO_V2_LINE_CHANGED_REQUESTED, desc);
419 dev_dbg(&gdev->dev, "registered chardev handle for line %d\n",
423 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
429 file = anon_inode_getfile("gpio-linehandle",
432 O_RDONLY | O_CLOEXEC);
435 goto out_put_unused_fd;
439 if (copy_to_user(ip, &handlereq, sizeof(handlereq))) {
441 * fput() will trigger the release() callback, so do not go onto
442 * the regular error cleanup path here.
449 fd_install(fd, file);
451 dev_dbg(&gdev->dev, "registered chardev handle for %d lines\n",
462 #endif /* CONFIG_GPIO_CDEV_V1 */
465 * struct line - contains the state of a requested line
466 * @desc: the GPIO descriptor for this line.
467 * @req: the corresponding line request
468 * @irq: the interrupt triggered in response to events on this GPIO
469 * @eflags: the edge flags, GPIO_V2_LINE_FLAG_EDGE_RISING and/or
470 * GPIO_V2_LINE_FLAG_EDGE_FALLING, indicating the edge detection applied
471 * @timestamp_ns: cache for the timestamp storing it between hardirq and
472 * IRQ thread, used to bring the timestamp close to the actual event
473 * @req_seqno: the seqno for the current edge event in the sequence of
474 * events for the corresponding line request. This is drawn from the @req.
475 * @line_seqno: the seqno for the current edge event in the sequence of
476 * events for this line.
477 * @work: the worker that implements software debouncing
478 * @sw_debounced: flag indicating if the software debouncer is active
479 * @level: the current debounced physical level of the line
480 * @hdesc: the Hardware Timestamp Engine (HTE) descriptor
481 * @raw_level: the line level at the time of event
482 * @total_discard_seq: the running counter of the discarded events
483 * @last_seqno: the last sequence number before debounce period expires
486 struct gpio_desc *desc;
488 * -- edge detector specific fields --
493 * The flags for the active edge detector configuration.
495 * edflags is set by linereq_create(), linereq_free(), and
496 * linereq_set_config_unlocked(), which are themselves mutually
497 * exclusive, and is accessed by edge_irq_thread(),
498 * process_hw_ts_thread() and debounce_work_func(),
499 * which can all live with a slightly stale value.
503 * timestamp_ns and req_seqno are accessed only by
504 * edge_irq_handler() and edge_irq_thread(), which are themselves
505 * mutually exclusive, so no additional protection is necessary.
510 * line_seqno is accessed by either edge_irq_thread() or
511 * debounce_work_func(), which are themselves mutually exclusive,
512 * so no additional protection is necessary.
516 * -- debouncer specific fields --
518 struct delayed_work work;
520 * sw_debounce is accessed by linereq_set_config(), which is the
521 * only setter, and linereq_get_values(), which can live with a
522 * slightly stale value.
524 unsigned int sw_debounced;
526 * level is accessed by debounce_work_func(), which is the only
527 * setter, and linereq_get_values() which can live with a slightly
532 struct hte_ts_desc hdesc;
534 * HTE provider sets line level at the time of event. The valid
535 * value is 0 or 1 and negative value for an error.
539 * when sw_debounce is set on HTE enabled line, this is running
540 * counter of the discarded events.
542 u32 total_discard_seq;
544 * when sw_debounce is set on HTE enabled line, this variable records
545 * last sequence number before debounce period expires.
548 #endif /* CONFIG_HTE */
552 * struct linereq - contains the state of a userspace line request
553 * @gdev: the GPIO device the line request pertains to
554 * @label: consumer label used to tag GPIO descriptors
555 * @num_lines: the number of lines in the lines array
556 * @wait: wait queue that handles blocking reads of events
557 * @event_buffer_size: the number of elements allocated in @events
558 * @events: KFIFO for the GPIO events
559 * @seqno: the sequence number for edge events generated on all lines in
560 * this line request. Note that this is not used when @num_lines is 1, as
561 * the line_seqno is then the same and is cheaper to calculate.
562 * @config_mutex: mutex for serializing ioctl() calls to ensure consistency
563 * of configuration, particularly multi-step accesses to desc flags.
564 * @lines: the lines held by this line request, with @num_lines elements.
567 struct gpio_device *gdev;
570 wait_queue_head_t wait;
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 void linereq_put_event(struct linereq *lr,
613 struct gpio_v2_line_event *le)
615 bool overflow = false;
617 spin_lock(&lr->wait.lock);
618 if (kfifo_is_full(&lr->events)) {
620 kfifo_skip(&lr->events);
622 kfifo_in(&lr->events, le, 1);
623 spin_unlock(&lr->wait.lock);
625 wake_up_poll(&lr->wait, EPOLLIN);
627 pr_debug_ratelimited("event FIFO is full - event dropped\n");
630 static u64 line_event_timestamp(struct line *line)
632 if (test_bit(FLAG_EVENT_CLOCK_REALTIME, &line->desc->flags))
633 return ktime_get_real_ns();
634 else if (IS_ENABLED(CONFIG_HTE) &&
635 test_bit(FLAG_EVENT_CLOCK_HTE, &line->desc->flags))
636 return line->timestamp_ns;
638 return ktime_get_ns();
641 static u32 line_event_id(int level)
643 return level ? GPIO_V2_LINE_EVENT_RISING_EDGE :
644 GPIO_V2_LINE_EVENT_FALLING_EDGE;
649 static enum hte_return process_hw_ts_thread(void *p)
653 struct gpio_v2_line_event le;
658 return HTE_CB_HANDLED;
663 memset(&le, 0, sizeof(le));
665 le.timestamp_ns = line->timestamp_ns;
666 edflags = READ_ONCE(line->edflags);
668 switch (edflags & GPIO_V2_LINE_EDGE_FLAGS) {
669 case GPIO_V2_LINE_FLAG_EDGE_BOTH:
670 level = (line->raw_level >= 0) ?
672 gpiod_get_raw_value_cansleep(line->desc);
674 if (edflags & GPIO_V2_LINE_FLAG_ACTIVE_LOW)
677 le.id = line_event_id(level);
679 case GPIO_V2_LINE_FLAG_EDGE_RISING:
680 le.id = GPIO_V2_LINE_EVENT_RISING_EDGE;
682 case GPIO_V2_LINE_FLAG_EDGE_FALLING:
683 le.id = GPIO_V2_LINE_EVENT_FALLING_EDGE;
686 return HTE_CB_HANDLED;
688 le.line_seqno = line->line_seqno;
689 le.seqno = (lr->num_lines == 1) ? le.line_seqno : line->req_seqno;
690 le.offset = gpio_chip_hwgpio(line->desc);
692 linereq_put_event(lr, &le);
694 return HTE_CB_HANDLED;
697 static enum hte_return process_hw_ts(struct hte_ts_data *ts, void *p)
704 return HTE_CB_HANDLED;
707 line->timestamp_ns = ts->tsc;
708 line->raw_level = ts->raw_level;
711 if (READ_ONCE(line->sw_debounced)) {
712 line->total_discard_seq++;
713 line->last_seqno = ts->seq;
714 mod_delayed_work(system_wq, &line->work,
715 usecs_to_jiffies(READ_ONCE(line->desc->debounce_period_us)));
717 if (unlikely(ts->seq < line->line_seqno))
718 return HTE_CB_HANDLED;
720 diff_seqno = ts->seq - line->line_seqno;
721 line->line_seqno = ts->seq;
722 if (lr->num_lines != 1)
723 line->req_seqno = atomic_add_return(diff_seqno,
726 return HTE_RUN_SECOND_CB;
729 return HTE_CB_HANDLED;
732 static int hte_edge_setup(struct line *line, u64 eflags)
735 unsigned long flags = 0;
736 struct hte_ts_desc *hdesc = &line->hdesc;
738 if (eflags & GPIO_V2_LINE_FLAG_EDGE_RISING)
739 flags |= test_bit(FLAG_ACTIVE_LOW, &line->desc->flags) ?
740 HTE_FALLING_EDGE_TS :
742 if (eflags & GPIO_V2_LINE_FLAG_EDGE_FALLING)
743 flags |= test_bit(FLAG_ACTIVE_LOW, &line->desc->flags) ?
747 line->total_discard_seq = 0;
749 hte_init_line_attr(hdesc, desc_to_gpio(line->desc), flags, NULL,
752 ret = hte_ts_get(NULL, hdesc, 0);
756 return hte_request_ts_ns(hdesc, process_hw_ts, process_hw_ts_thread,
762 static int hte_edge_setup(struct line *line, u64 eflags)
766 #endif /* CONFIG_HTE */
768 static irqreturn_t edge_irq_thread(int irq, void *p)
770 struct line *line = p;
771 struct linereq *lr = line->req;
772 struct gpio_v2_line_event le;
774 /* Do not leak kernel stack to userspace */
775 memset(&le, 0, sizeof(le));
777 if (line->timestamp_ns) {
778 le.timestamp_ns = line->timestamp_ns;
781 * We may be running from a nested threaded interrupt in
782 * which case we didn't get the timestamp from
783 * edge_irq_handler().
785 le.timestamp_ns = line_event_timestamp(line);
786 if (lr->num_lines != 1)
787 line->req_seqno = atomic_inc_return(&lr->seqno);
789 line->timestamp_ns = 0;
791 switch (READ_ONCE(line->edflags) & GPIO_V2_LINE_EDGE_FLAGS) {
792 case GPIO_V2_LINE_FLAG_EDGE_BOTH:
793 le.id = line_event_id(gpiod_get_value_cansleep(line->desc));
795 case GPIO_V2_LINE_FLAG_EDGE_RISING:
796 le.id = GPIO_V2_LINE_EVENT_RISING_EDGE;
798 case GPIO_V2_LINE_FLAG_EDGE_FALLING:
799 le.id = GPIO_V2_LINE_EVENT_FALLING_EDGE;
805 le.line_seqno = line->line_seqno;
806 le.seqno = (lr->num_lines == 1) ? le.line_seqno : line->req_seqno;
807 le.offset = gpio_chip_hwgpio(line->desc);
809 linereq_put_event(lr, &le);
814 static irqreturn_t edge_irq_handler(int irq, void *p)
816 struct line *line = p;
817 struct linereq *lr = line->req;
820 * Just store the timestamp in hardirq context so we get it as
821 * close in time as possible to the actual event.
823 line->timestamp_ns = line_event_timestamp(line);
825 if (lr->num_lines != 1)
826 line->req_seqno = atomic_inc_return(&lr->seqno);
828 return IRQ_WAKE_THREAD;
832 * returns the current debounced logical value.
834 static bool debounced_value(struct line *line)
839 * minor race - debouncer may be stopped here, so edge_detector_stop()
840 * must leave the value unchanged so the following will read the level
841 * from when the debouncer was last running.
843 value = READ_ONCE(line->level);
845 if (test_bit(FLAG_ACTIVE_LOW, &line->desc->flags))
851 static irqreturn_t debounce_irq_handler(int irq, void *p)
853 struct line *line = p;
855 mod_delayed_work(system_wq, &line->work,
856 usecs_to_jiffies(READ_ONCE(line->desc->debounce_period_us)));
861 static void debounce_work_func(struct work_struct *work)
863 struct gpio_v2_line_event le;
864 struct line *line = container_of(work, struct line, work.work);
866 u64 eflags, edflags = READ_ONCE(line->edflags);
871 if (edflags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE)
872 level = line->raw_level;
875 level = gpiod_get_raw_value_cansleep(line->desc);
877 pr_debug_ratelimited("debouncer failed to read line value\n");
881 if (READ_ONCE(line->level) == level)
884 WRITE_ONCE(line->level, level);
886 /* -- edge detection -- */
887 eflags = edflags & GPIO_V2_LINE_EDGE_FLAGS;
891 /* switch from physical level to logical - if they differ */
892 if (edflags & GPIO_V2_LINE_FLAG_ACTIVE_LOW)
895 /* ignore edges that are not being monitored */
896 if (((eflags == GPIO_V2_LINE_FLAG_EDGE_RISING) && !level) ||
897 ((eflags == GPIO_V2_LINE_FLAG_EDGE_FALLING) && level))
900 /* Do not leak kernel stack to userspace */
901 memset(&le, 0, sizeof(le));
904 le.timestamp_ns = line_event_timestamp(line);
905 le.offset = gpio_chip_hwgpio(line->desc);
907 if (edflags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE) {
908 /* discard events except the last one */
909 line->total_discard_seq -= 1;
910 diff_seqno = line->last_seqno - line->total_discard_seq -
912 line->line_seqno = line->last_seqno - line->total_discard_seq;
913 le.line_seqno = line->line_seqno;
914 le.seqno = (lr->num_lines == 1) ?
915 le.line_seqno : atomic_add_return(diff_seqno, &lr->seqno);
917 #endif /* CONFIG_HTE */
920 le.line_seqno = line->line_seqno;
921 le.seqno = (lr->num_lines == 1) ?
922 le.line_seqno : atomic_inc_return(&lr->seqno);
925 le.id = line_event_id(level);
927 linereq_put_event(lr, &le);
930 static int debounce_setup(struct line *line, unsigned int debounce_period_us)
932 unsigned long irqflags;
936 ret = gpiod_set_debounce(line->desc, debounce_period_us);
938 WRITE_ONCE(line->desc->debounce_period_us, debounce_period_us);
941 if (ret != -ENOTSUPP)
944 if (debounce_period_us) {
945 /* setup software debounce */
946 level = gpiod_get_raw_value_cansleep(line->desc);
950 if (!(IS_ENABLED(CONFIG_HTE) &&
951 test_bit(FLAG_EVENT_CLOCK_HTE, &line->desc->flags))) {
952 irq = gpiod_to_irq(line->desc);
956 irqflags = IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING;
957 ret = request_irq(irq, debounce_irq_handler, irqflags,
958 line->req->label, line);
963 ret = hte_edge_setup(line, GPIO_V2_LINE_FLAG_EDGE_BOTH);
968 WRITE_ONCE(line->level, level);
969 WRITE_ONCE(line->sw_debounced, 1);
974 static bool gpio_v2_line_config_debounced(struct gpio_v2_line_config *lc,
975 unsigned int line_idx)
978 u64 mask = BIT_ULL(line_idx);
980 for (i = 0; i < lc->num_attrs; i++) {
981 if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_DEBOUNCE) &&
982 (lc->attrs[i].mask & mask))
988 static u32 gpio_v2_line_config_debounce_period(struct gpio_v2_line_config *lc,
989 unsigned int line_idx)
992 u64 mask = BIT_ULL(line_idx);
994 for (i = 0; i < lc->num_attrs; i++) {
995 if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_DEBOUNCE) &&
996 (lc->attrs[i].mask & mask))
997 return lc->attrs[i].attr.debounce_period_us;
1002 static void edge_detector_stop(struct line *line)
1005 free_irq(line->irq, line);
1010 if (READ_ONCE(line->edflags) & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE)
1011 hte_ts_put(&line->hdesc);
1014 cancel_delayed_work_sync(&line->work);
1015 WRITE_ONCE(line->sw_debounced, 0);
1016 WRITE_ONCE(line->edflags, 0);
1018 WRITE_ONCE(line->desc->debounce_period_us, 0);
1019 /* do not change line->level - see comment in debounced_value() */
1022 static int edge_detector_setup(struct line *line,
1023 struct gpio_v2_line_config *lc,
1024 unsigned int line_idx, u64 edflags)
1026 u32 debounce_period_us;
1027 unsigned long irqflags = 0;
1031 eflags = edflags & GPIO_V2_LINE_EDGE_FLAGS;
1032 if (eflags && !kfifo_initialized(&line->req->events)) {
1033 ret = kfifo_alloc(&line->req->events,
1034 line->req->event_buffer_size, GFP_KERNEL);
1038 if (gpio_v2_line_config_debounced(lc, line_idx)) {
1039 debounce_period_us = gpio_v2_line_config_debounce_period(lc, line_idx);
1040 ret = debounce_setup(line, debounce_period_us);
1043 WRITE_ONCE(line->desc->debounce_period_us, debounce_period_us);
1046 /* detection disabled or sw debouncer will provide edge detection */
1047 if (!eflags || READ_ONCE(line->sw_debounced))
1050 if (IS_ENABLED(CONFIG_HTE) &&
1051 (edflags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE))
1052 return hte_edge_setup(line, edflags);
1054 irq = gpiod_to_irq(line->desc);
1058 if (eflags & GPIO_V2_LINE_FLAG_EDGE_RISING)
1059 irqflags |= test_bit(FLAG_ACTIVE_LOW, &line->desc->flags) ?
1060 IRQF_TRIGGER_FALLING : IRQF_TRIGGER_RISING;
1061 if (eflags & GPIO_V2_LINE_FLAG_EDGE_FALLING)
1062 irqflags |= test_bit(FLAG_ACTIVE_LOW, &line->desc->flags) ?
1063 IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING;
1064 irqflags |= IRQF_ONESHOT;
1066 /* Request a thread to read the events */
1067 ret = request_threaded_irq(irq, edge_irq_handler, edge_irq_thread,
1068 irqflags, line->req->label, line);
1076 static int edge_detector_update(struct line *line,
1077 struct gpio_v2_line_config *lc,
1078 unsigned int line_idx, u64 edflags)
1080 u64 active_edflags = READ_ONCE(line->edflags);
1081 unsigned int debounce_period_us =
1082 gpio_v2_line_config_debounce_period(lc, line_idx);
1084 if ((active_edflags == edflags) &&
1085 (READ_ONCE(line->desc->debounce_period_us) == debounce_period_us))
1088 /* sw debounced and still will be...*/
1089 if (debounce_period_us && READ_ONCE(line->sw_debounced)) {
1090 WRITE_ONCE(line->desc->debounce_period_us, debounce_period_us);
1094 /* reconfiguring edge detection or sw debounce being disabled */
1095 if ((line->irq && !READ_ONCE(line->sw_debounced)) ||
1096 (active_edflags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE) ||
1097 (!debounce_period_us && READ_ONCE(line->sw_debounced)))
1098 edge_detector_stop(line);
1100 return edge_detector_setup(line, lc, line_idx, edflags);
1103 static u64 gpio_v2_line_config_flags(struct gpio_v2_line_config *lc,
1104 unsigned int line_idx)
1107 u64 mask = BIT_ULL(line_idx);
1109 for (i = 0; i < lc->num_attrs; i++) {
1110 if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_FLAGS) &&
1111 (lc->attrs[i].mask & mask))
1112 return lc->attrs[i].attr.flags;
1117 static int gpio_v2_line_config_output_value(struct gpio_v2_line_config *lc,
1118 unsigned int line_idx)
1121 u64 mask = BIT_ULL(line_idx);
1123 for (i = 0; i < lc->num_attrs; i++) {
1124 if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_OUTPUT_VALUES) &&
1125 (lc->attrs[i].mask & mask))
1126 return !!(lc->attrs[i].attr.values & mask);
1131 static int gpio_v2_line_flags_validate(u64 flags)
1133 /* Return an error if an unknown flag is set */
1134 if (flags & ~GPIO_V2_LINE_VALID_FLAGS)
1137 if (!IS_ENABLED(CONFIG_HTE) &&
1138 (flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE))
1142 * Do not allow both INPUT and OUTPUT flags to be set as they are
1145 if ((flags & GPIO_V2_LINE_FLAG_INPUT) &&
1146 (flags & GPIO_V2_LINE_FLAG_OUTPUT))
1149 /* Only allow one event clock source */
1150 if (IS_ENABLED(CONFIG_HTE) &&
1151 (flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME) &&
1152 (flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE))
1155 /* Edge detection requires explicit input. */
1156 if ((flags & GPIO_V2_LINE_EDGE_FLAGS) &&
1157 !(flags & GPIO_V2_LINE_FLAG_INPUT))
1161 * Do not allow OPEN_SOURCE and OPEN_DRAIN flags in a single
1162 * request. If the hardware actually supports enabling both at the
1163 * same time the electrical result would be disastrous.
1165 if ((flags & GPIO_V2_LINE_FLAG_OPEN_DRAIN) &&
1166 (flags & GPIO_V2_LINE_FLAG_OPEN_SOURCE))
1169 /* Drive requires explicit output direction. */
1170 if ((flags & GPIO_V2_LINE_DRIVE_FLAGS) &&
1171 !(flags & GPIO_V2_LINE_FLAG_OUTPUT))
1174 /* Bias requires explicit direction. */
1175 if ((flags & GPIO_V2_LINE_BIAS_FLAGS) &&
1176 !(flags & GPIO_V2_LINE_DIRECTION_FLAGS))
1179 /* Only one bias flag can be set. */
1180 if (((flags & GPIO_V2_LINE_FLAG_BIAS_DISABLED) &&
1181 (flags & (GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN |
1182 GPIO_V2_LINE_FLAG_BIAS_PULL_UP))) ||
1183 ((flags & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN) &&
1184 (flags & GPIO_V2_LINE_FLAG_BIAS_PULL_UP)))
1190 static int gpio_v2_line_config_validate(struct gpio_v2_line_config *lc,
1191 unsigned int num_lines)
1197 if (lc->num_attrs > GPIO_V2_LINE_NUM_ATTRS_MAX)
1200 if (memchr_inv(lc->padding, 0, sizeof(lc->padding)))
1203 for (i = 0; i < num_lines; i++) {
1204 flags = gpio_v2_line_config_flags(lc, i);
1205 ret = gpio_v2_line_flags_validate(flags);
1209 /* debounce requires explicit input */
1210 if (gpio_v2_line_config_debounced(lc, i) &&
1211 !(flags & GPIO_V2_LINE_FLAG_INPUT))
1217 static void gpio_v2_line_config_flags_to_desc_flags(u64 flags,
1218 unsigned long *flagsp)
1220 assign_bit(FLAG_ACTIVE_LOW, flagsp,
1221 flags & GPIO_V2_LINE_FLAG_ACTIVE_LOW);
1223 if (flags & GPIO_V2_LINE_FLAG_OUTPUT)
1224 set_bit(FLAG_IS_OUT, flagsp);
1225 else if (flags & GPIO_V2_LINE_FLAG_INPUT)
1226 clear_bit(FLAG_IS_OUT, flagsp);
1228 assign_bit(FLAG_EDGE_RISING, flagsp,
1229 flags & GPIO_V2_LINE_FLAG_EDGE_RISING);
1230 assign_bit(FLAG_EDGE_FALLING, flagsp,
1231 flags & GPIO_V2_LINE_FLAG_EDGE_FALLING);
1233 assign_bit(FLAG_OPEN_DRAIN, flagsp,
1234 flags & GPIO_V2_LINE_FLAG_OPEN_DRAIN);
1235 assign_bit(FLAG_OPEN_SOURCE, flagsp,
1236 flags & GPIO_V2_LINE_FLAG_OPEN_SOURCE);
1238 assign_bit(FLAG_PULL_UP, flagsp,
1239 flags & GPIO_V2_LINE_FLAG_BIAS_PULL_UP);
1240 assign_bit(FLAG_PULL_DOWN, flagsp,
1241 flags & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN);
1242 assign_bit(FLAG_BIAS_DISABLE, flagsp,
1243 flags & GPIO_V2_LINE_FLAG_BIAS_DISABLED);
1245 assign_bit(FLAG_EVENT_CLOCK_REALTIME, flagsp,
1246 flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME);
1247 assign_bit(FLAG_EVENT_CLOCK_HTE, flagsp,
1248 flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE);
1251 static long linereq_get_values(struct linereq *lr, void __user *ip)
1253 struct gpio_v2_line_values lv;
1254 DECLARE_BITMAP(vals, GPIO_V2_LINES_MAX);
1255 struct gpio_desc **descs;
1256 unsigned int i, didx, num_get;
1260 /* NOTE: It's ok to read values of output lines. */
1261 if (copy_from_user(&lv, ip, sizeof(lv)))
1264 for (num_get = 0, i = 0; i < lr->num_lines; i++) {
1265 if (lv.mask & BIT_ULL(i)) {
1267 descs = &lr->lines[i].desc;
1275 descs = kmalloc_array(num_get, sizeof(*descs), GFP_KERNEL);
1278 for (didx = 0, i = 0; i < lr->num_lines; i++) {
1279 if (lv.mask & BIT_ULL(i)) {
1280 descs[didx] = lr->lines[i].desc;
1285 ret = gpiod_get_array_value_complex(false, true, num_get,
1294 for (didx = 0, i = 0; i < lr->num_lines; i++) {
1295 if (lv.mask & BIT_ULL(i)) {
1296 if (lr->lines[i].sw_debounced)
1297 val = debounced_value(&lr->lines[i]);
1299 val = test_bit(didx, vals);
1301 lv.bits |= BIT_ULL(i);
1306 if (copy_to_user(ip, &lv, sizeof(lv)))
1312 static long linereq_set_values_unlocked(struct linereq *lr,
1313 struct gpio_v2_line_values *lv)
1315 DECLARE_BITMAP(vals, GPIO_V2_LINES_MAX);
1316 struct gpio_desc **descs;
1317 unsigned int i, didx, num_set;
1320 bitmap_zero(vals, GPIO_V2_LINES_MAX);
1321 for (num_set = 0, i = 0; i < lr->num_lines; i++) {
1322 if (lv->mask & BIT_ULL(i)) {
1323 if (!test_bit(FLAG_IS_OUT, &lr->lines[i].desc->flags))
1325 if (lv->bits & BIT_ULL(i))
1326 __set_bit(num_set, vals);
1328 descs = &lr->lines[i].desc;
1335 /* build compacted desc array and values */
1336 descs = kmalloc_array(num_set, sizeof(*descs), GFP_KERNEL);
1339 for (didx = 0, i = 0; i < lr->num_lines; i++) {
1340 if (lv->mask & BIT_ULL(i)) {
1341 descs[didx] = lr->lines[i].desc;
1346 ret = gpiod_set_array_value_complex(false, true, num_set,
1354 static long linereq_set_values(struct linereq *lr, void __user *ip)
1356 struct gpio_v2_line_values lv;
1359 if (copy_from_user(&lv, ip, sizeof(lv)))
1362 mutex_lock(&lr->config_mutex);
1364 ret = linereq_set_values_unlocked(lr, &lv);
1366 mutex_unlock(&lr->config_mutex);
1371 static long linereq_set_config_unlocked(struct linereq *lr,
1372 struct gpio_v2_line_config *lc)
1374 struct gpio_desc *desc;
1380 for (i = 0; i < lr->num_lines; i++) {
1381 line = &lr->lines[i];
1382 desc = lr->lines[i].desc;
1383 flags = gpio_v2_line_config_flags(lc, i);
1384 gpio_v2_line_config_flags_to_desc_flags(flags, &desc->flags);
1385 edflags = flags & GPIO_V2_LINE_EDGE_DETECTOR_FLAGS;
1387 * Lines have to be requested explicitly for input
1388 * or output, else the line will be treated "as is".
1390 if (flags & GPIO_V2_LINE_FLAG_OUTPUT) {
1391 int val = gpio_v2_line_config_output_value(lc, i);
1393 edge_detector_stop(line);
1394 ret = gpiod_direction_output(desc, val);
1397 } else if (flags & GPIO_V2_LINE_FLAG_INPUT) {
1398 ret = gpiod_direction_input(desc);
1402 ret = edge_detector_update(line, lc, i, edflags);
1407 WRITE_ONCE(line->edflags, edflags);
1409 blocking_notifier_call_chain(&desc->gdev->notifier,
1410 GPIO_V2_LINE_CHANGED_CONFIG,
1416 static long linereq_set_config(struct linereq *lr, void __user *ip)
1418 struct gpio_v2_line_config lc;
1421 if (copy_from_user(&lc, ip, sizeof(lc)))
1424 ret = gpio_v2_line_config_validate(&lc, lr->num_lines);
1428 mutex_lock(&lr->config_mutex);
1430 ret = linereq_set_config_unlocked(lr, &lc);
1432 mutex_unlock(&lr->config_mutex);
1437 static long linereq_ioctl_unlocked(struct file *file, unsigned int cmd,
1440 struct linereq *lr = file->private_data;
1441 void __user *ip = (void __user *)arg;
1443 if (!lr->gdev->chip)
1447 case GPIO_V2_LINE_GET_VALUES_IOCTL:
1448 return linereq_get_values(lr, ip);
1449 case GPIO_V2_LINE_SET_VALUES_IOCTL:
1450 return linereq_set_values(lr, ip);
1451 case GPIO_V2_LINE_SET_CONFIG_IOCTL:
1452 return linereq_set_config(lr, ip);
1458 static long linereq_ioctl(struct file *file, unsigned int cmd,
1461 struct linereq *lr = file->private_data;
1463 return call_ioctl_locked(file, cmd, arg, lr->gdev,
1464 linereq_ioctl_unlocked);
1467 #ifdef CONFIG_COMPAT
1468 static long linereq_ioctl_compat(struct file *file, unsigned int cmd,
1471 return linereq_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
1475 static __poll_t linereq_poll_unlocked(struct file *file,
1476 struct poll_table_struct *wait)
1478 struct linereq *lr = file->private_data;
1479 __poll_t events = 0;
1481 if (!lr->gdev->chip)
1482 return EPOLLHUP | EPOLLERR;
1484 poll_wait(file, &lr->wait, wait);
1486 if (!kfifo_is_empty_spinlocked_noirqsave(&lr->events,
1488 events = EPOLLIN | EPOLLRDNORM;
1493 static __poll_t linereq_poll(struct file *file,
1494 struct poll_table_struct *wait)
1496 struct linereq *lr = file->private_data;
1498 return call_poll_locked(file, wait, lr->gdev, linereq_poll_unlocked);
1501 static ssize_t linereq_read_unlocked(struct file *file, char __user *buf,
1502 size_t count, loff_t *f_ps)
1504 struct linereq *lr = file->private_data;
1505 struct gpio_v2_line_event le;
1506 ssize_t bytes_read = 0;
1509 if (!lr->gdev->chip)
1512 if (count < sizeof(le))
1516 spin_lock(&lr->wait.lock);
1517 if (kfifo_is_empty(&lr->events)) {
1519 spin_unlock(&lr->wait.lock);
1523 if (file->f_flags & O_NONBLOCK) {
1524 spin_unlock(&lr->wait.lock);
1528 ret = wait_event_interruptible_locked(lr->wait,
1529 !kfifo_is_empty(&lr->events));
1531 spin_unlock(&lr->wait.lock);
1536 ret = kfifo_out(&lr->events, &le, 1);
1537 spin_unlock(&lr->wait.lock);
1540 * This should never happen - we were holding the
1541 * lock from the moment we learned the fifo is no
1542 * longer empty until now.
1548 if (copy_to_user(buf + bytes_read, &le, sizeof(le)))
1550 bytes_read += sizeof(le);
1551 } while (count >= bytes_read + sizeof(le));
1556 static ssize_t linereq_read(struct file *file, char __user *buf,
1557 size_t count, loff_t *f_ps)
1559 struct linereq *lr = file->private_data;
1561 return call_read_locked(file, buf, count, f_ps, lr->gdev,
1562 linereq_read_unlocked);
1565 static void linereq_free(struct linereq *lr)
1569 for (i = 0; i < lr->num_lines; i++) {
1570 if (lr->lines[i].desc) {
1571 edge_detector_stop(&lr->lines[i]);
1572 gpiod_free(lr->lines[i].desc);
1575 kfifo_free(&lr->events);
1577 put_device(&lr->gdev->dev);
1581 static int linereq_release(struct inode *inode, struct file *file)
1583 struct linereq *lr = file->private_data;
1589 #ifdef CONFIG_PROC_FS
1590 static void linereq_show_fdinfo(struct seq_file *out, struct file *file)
1592 struct linereq *lr = file->private_data;
1593 struct device *dev = &lr->gdev->dev;
1596 seq_printf(out, "gpio-chip:\t%s\n", dev_name(dev));
1598 for (i = 0; i < lr->num_lines; i++)
1599 seq_printf(out, "gpio-line:\t%d\n",
1600 gpio_chip_hwgpio(lr->lines[i].desc));
1604 static const struct file_operations line_fileops = {
1605 .release = linereq_release,
1606 .read = linereq_read,
1607 .poll = linereq_poll,
1608 .owner = THIS_MODULE,
1609 .llseek = noop_llseek,
1610 .unlocked_ioctl = linereq_ioctl,
1611 #ifdef CONFIG_COMPAT
1612 .compat_ioctl = linereq_ioctl_compat,
1614 #ifdef CONFIG_PROC_FS
1615 .show_fdinfo = linereq_show_fdinfo,
1619 static int linereq_create(struct gpio_device *gdev, void __user *ip)
1621 struct gpio_v2_line_request ulr;
1622 struct gpio_v2_line_config *lc;
1629 if (copy_from_user(&ulr, ip, sizeof(ulr)))
1632 if ((ulr.num_lines == 0) || (ulr.num_lines > GPIO_V2_LINES_MAX))
1635 if (memchr_inv(ulr.padding, 0, sizeof(ulr.padding)))
1639 ret = gpio_v2_line_config_validate(lc, ulr.num_lines);
1643 lr = kzalloc(struct_size(lr, lines, ulr.num_lines), GFP_KERNEL);
1648 get_device(&gdev->dev);
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 put_device(&le->gdev->dev);
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);
2096 get_device(&gdev->dev);
2098 if (eventreq.consumer_label[0] != '\0') {
2099 /* label is only initialized if consumer_label is set */
2100 le->label = kstrndup(eventreq.consumer_label,
2101 sizeof(eventreq.consumer_label) - 1,
2109 ret = gpiod_request_user(desc, le->label);
2113 le->eflags = eflags;
2115 linehandle_flags_to_desc_flags(lflags, &desc->flags);
2117 ret = gpiod_direction_input(desc);
2121 blocking_notifier_call_chain(&desc->gdev->notifier,
2122 GPIO_V2_LINE_CHANGED_REQUESTED, desc);
2124 irq = gpiod_to_irq(desc);
2130 if (eflags & GPIOEVENT_REQUEST_RISING_EDGE)
2131 irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
2132 IRQF_TRIGGER_FALLING : IRQF_TRIGGER_RISING;
2133 if (eflags & GPIOEVENT_REQUEST_FALLING_EDGE)
2134 irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
2135 IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING;
2136 irqflags |= IRQF_ONESHOT;
2138 INIT_KFIFO(le->events);
2139 init_waitqueue_head(&le->wait);
2141 /* Request a thread to read the events */
2142 ret = request_threaded_irq(irq,
2143 lineevent_irq_handler,
2144 lineevent_irq_thread,
2153 fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
2159 file = anon_inode_getfile("gpio-event",
2162 O_RDONLY | O_CLOEXEC);
2164 ret = PTR_ERR(file);
2165 goto out_put_unused_fd;
2169 if (copy_to_user(ip, &eventreq, sizeof(eventreq))) {
2171 * fput() will trigger the release() callback, so do not go onto
2172 * the regular error cleanup path here.
2179 fd_install(fd, file);
2190 static void gpio_v2_line_info_to_v1(struct gpio_v2_line_info *info_v2,
2191 struct gpioline_info *info_v1)
2193 u64 flagsv2 = info_v2->flags;
2195 memcpy(info_v1->name, info_v2->name, sizeof(info_v1->name));
2196 memcpy(info_v1->consumer, info_v2->consumer, sizeof(info_v1->consumer));
2197 info_v1->line_offset = info_v2->offset;
2200 if (flagsv2 & GPIO_V2_LINE_FLAG_USED)
2201 info_v1->flags |= GPIOLINE_FLAG_KERNEL;
2203 if (flagsv2 & GPIO_V2_LINE_FLAG_OUTPUT)
2204 info_v1->flags |= GPIOLINE_FLAG_IS_OUT;
2206 if (flagsv2 & GPIO_V2_LINE_FLAG_ACTIVE_LOW)
2207 info_v1->flags |= GPIOLINE_FLAG_ACTIVE_LOW;
2209 if (flagsv2 & GPIO_V2_LINE_FLAG_OPEN_DRAIN)
2210 info_v1->flags |= GPIOLINE_FLAG_OPEN_DRAIN;
2211 if (flagsv2 & GPIO_V2_LINE_FLAG_OPEN_SOURCE)
2212 info_v1->flags |= GPIOLINE_FLAG_OPEN_SOURCE;
2214 if (flagsv2 & GPIO_V2_LINE_FLAG_BIAS_PULL_UP)
2215 info_v1->flags |= GPIOLINE_FLAG_BIAS_PULL_UP;
2216 if (flagsv2 & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN)
2217 info_v1->flags |= GPIOLINE_FLAG_BIAS_PULL_DOWN;
2218 if (flagsv2 & GPIO_V2_LINE_FLAG_BIAS_DISABLED)
2219 info_v1->flags |= GPIOLINE_FLAG_BIAS_DISABLE;
2222 static void gpio_v2_line_info_changed_to_v1(
2223 struct gpio_v2_line_info_changed *lic_v2,
2224 struct gpioline_info_changed *lic_v1)
2226 memset(lic_v1, 0, sizeof(*lic_v1));
2227 gpio_v2_line_info_to_v1(&lic_v2->info, &lic_v1->info);
2228 lic_v1->timestamp = lic_v2->timestamp_ns;
2229 lic_v1->event_type = lic_v2->event_type;
2232 #endif /* CONFIG_GPIO_CDEV_V1 */
2234 static void gpio_desc_to_lineinfo(struct gpio_desc *desc,
2235 struct gpio_v2_line_info *info)
2237 struct gpio_chip *gc = desc->gdev->chip;
2238 bool ok_for_pinctrl;
2239 unsigned long flags;
2240 u32 debounce_period_us;
2241 unsigned int num_attrs = 0;
2243 memset(info, 0, sizeof(*info));
2244 info->offset = gpio_chip_hwgpio(desc);
2247 * This function takes a mutex so we must check this before taking
2250 * FIXME: find a non-racy way to retrieve this information. Maybe a
2251 * lock common to both frameworks?
2254 pinctrl_gpio_can_use_line(gc->base + info->offset);
2256 spin_lock_irqsave(&gpio_lock, flags);
2259 strscpy(info->name, desc->name, sizeof(info->name));
2262 strscpy(info->consumer, desc->label, sizeof(info->consumer));
2265 * Userspace only need to know that the kernel is using this GPIO so
2269 if (test_bit(FLAG_REQUESTED, &desc->flags) ||
2270 test_bit(FLAG_IS_HOGGED, &desc->flags) ||
2271 test_bit(FLAG_USED_AS_IRQ, &desc->flags) ||
2272 test_bit(FLAG_EXPORT, &desc->flags) ||
2273 test_bit(FLAG_SYSFS, &desc->flags) ||
2274 !gpiochip_line_is_valid(gc, info->offset) ||
2276 info->flags |= GPIO_V2_LINE_FLAG_USED;
2278 if (test_bit(FLAG_IS_OUT, &desc->flags))
2279 info->flags |= GPIO_V2_LINE_FLAG_OUTPUT;
2281 info->flags |= GPIO_V2_LINE_FLAG_INPUT;
2283 if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2284 info->flags |= GPIO_V2_LINE_FLAG_ACTIVE_LOW;
2286 if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
2287 info->flags |= GPIO_V2_LINE_FLAG_OPEN_DRAIN;
2288 if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
2289 info->flags |= GPIO_V2_LINE_FLAG_OPEN_SOURCE;
2291 if (test_bit(FLAG_BIAS_DISABLE, &desc->flags))
2292 info->flags |= GPIO_V2_LINE_FLAG_BIAS_DISABLED;
2293 if (test_bit(FLAG_PULL_DOWN, &desc->flags))
2294 info->flags |= GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN;
2295 if (test_bit(FLAG_PULL_UP, &desc->flags))
2296 info->flags |= GPIO_V2_LINE_FLAG_BIAS_PULL_UP;
2298 if (test_bit(FLAG_EDGE_RISING, &desc->flags))
2299 info->flags |= GPIO_V2_LINE_FLAG_EDGE_RISING;
2300 if (test_bit(FLAG_EDGE_FALLING, &desc->flags))
2301 info->flags |= GPIO_V2_LINE_FLAG_EDGE_FALLING;
2303 if (test_bit(FLAG_EVENT_CLOCK_REALTIME, &desc->flags))
2304 info->flags |= GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME;
2305 else if (test_bit(FLAG_EVENT_CLOCK_HTE, &desc->flags))
2306 info->flags |= GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE;
2308 debounce_period_us = READ_ONCE(desc->debounce_period_us);
2309 if (debounce_period_us) {
2310 info->attrs[num_attrs].id = GPIO_V2_LINE_ATTR_ID_DEBOUNCE;
2311 info->attrs[num_attrs].debounce_period_us = debounce_period_us;
2314 info->num_attrs = num_attrs;
2316 spin_unlock_irqrestore(&gpio_lock, flags);
2319 struct gpio_chardev_data {
2320 struct gpio_device *gdev;
2321 wait_queue_head_t wait;
2322 DECLARE_KFIFO(events, struct gpio_v2_line_info_changed, 32);
2323 struct notifier_block lineinfo_changed_nb;
2324 unsigned long *watched_lines;
2325 #ifdef CONFIG_GPIO_CDEV_V1
2326 atomic_t watch_abi_version;
2330 static int chipinfo_get(struct gpio_chardev_data *cdev, void __user *ip)
2332 struct gpio_device *gdev = cdev->gdev;
2333 struct gpiochip_info chipinfo;
2335 memset(&chipinfo, 0, sizeof(chipinfo));
2337 strscpy(chipinfo.name, dev_name(&gdev->dev), sizeof(chipinfo.name));
2338 strscpy(chipinfo.label, gdev->label, sizeof(chipinfo.label));
2339 chipinfo.lines = gdev->ngpio;
2340 if (copy_to_user(ip, &chipinfo, sizeof(chipinfo)))
2345 #ifdef CONFIG_GPIO_CDEV_V1
2347 * returns 0 if the versions match, else the previously selected ABI version
2349 static int lineinfo_ensure_abi_version(struct gpio_chardev_data *cdata,
2350 unsigned int version)
2352 int abiv = atomic_cmpxchg(&cdata->watch_abi_version, 0, version);
2354 if (abiv == version)
2360 static int lineinfo_get_v1(struct gpio_chardev_data *cdev, void __user *ip,
2363 struct gpio_desc *desc;
2364 struct gpioline_info lineinfo;
2365 struct gpio_v2_line_info lineinfo_v2;
2367 if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
2370 /* this doubles as a range check on line_offset */
2371 desc = gpiochip_get_desc(cdev->gdev->chip, lineinfo.line_offset);
2373 return PTR_ERR(desc);
2376 if (lineinfo_ensure_abi_version(cdev, 1))
2379 if (test_and_set_bit(lineinfo.line_offset, cdev->watched_lines))
2383 gpio_desc_to_lineinfo(desc, &lineinfo_v2);
2384 gpio_v2_line_info_to_v1(&lineinfo_v2, &lineinfo);
2386 if (copy_to_user(ip, &lineinfo, sizeof(lineinfo))) {
2388 clear_bit(lineinfo.line_offset, cdev->watched_lines);
2396 static int lineinfo_get(struct gpio_chardev_data *cdev, void __user *ip,
2399 struct gpio_desc *desc;
2400 struct gpio_v2_line_info lineinfo;
2402 if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
2405 if (memchr_inv(lineinfo.padding, 0, sizeof(lineinfo.padding)))
2408 desc = gpiochip_get_desc(cdev->gdev->chip, lineinfo.offset);
2410 return PTR_ERR(desc);
2413 #ifdef CONFIG_GPIO_CDEV_V1
2414 if (lineinfo_ensure_abi_version(cdev, 2))
2417 if (test_and_set_bit(lineinfo.offset, cdev->watched_lines))
2420 gpio_desc_to_lineinfo(desc, &lineinfo);
2422 if (copy_to_user(ip, &lineinfo, sizeof(lineinfo))) {
2424 clear_bit(lineinfo.offset, cdev->watched_lines);
2431 static int lineinfo_unwatch(struct gpio_chardev_data *cdev, void __user *ip)
2435 if (copy_from_user(&offset, ip, sizeof(offset)))
2438 if (offset >= cdev->gdev->ngpio)
2441 if (!test_and_clear_bit(offset, cdev->watched_lines))
2448 * gpio_ioctl() - ioctl handler for the GPIO chardev
2450 static long gpio_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
2452 struct gpio_chardev_data *cdev = file->private_data;
2453 struct gpio_device *gdev = cdev->gdev;
2454 void __user *ip = (void __user *)arg;
2456 /* We fail any subsequent ioctl():s when the chip is gone */
2460 /* Fill in the struct and pass to userspace */
2462 case GPIO_GET_CHIPINFO_IOCTL:
2463 return chipinfo_get(cdev, ip);
2464 #ifdef CONFIG_GPIO_CDEV_V1
2465 case GPIO_GET_LINEHANDLE_IOCTL:
2466 return linehandle_create(gdev, ip);
2467 case GPIO_GET_LINEEVENT_IOCTL:
2468 return lineevent_create(gdev, ip);
2469 case GPIO_GET_LINEINFO_IOCTL:
2470 return lineinfo_get_v1(cdev, ip, false);
2471 case GPIO_GET_LINEINFO_WATCH_IOCTL:
2472 return lineinfo_get_v1(cdev, ip, true);
2473 #endif /* CONFIG_GPIO_CDEV_V1 */
2474 case GPIO_V2_GET_LINEINFO_IOCTL:
2475 return lineinfo_get(cdev, ip, false);
2476 case GPIO_V2_GET_LINEINFO_WATCH_IOCTL:
2477 return lineinfo_get(cdev, ip, true);
2478 case GPIO_V2_GET_LINE_IOCTL:
2479 return linereq_create(gdev, ip);
2480 case GPIO_GET_LINEINFO_UNWATCH_IOCTL:
2481 return lineinfo_unwatch(cdev, ip);
2487 #ifdef CONFIG_COMPAT
2488 static long gpio_ioctl_compat(struct file *file, unsigned int cmd,
2491 return gpio_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
2495 static struct gpio_chardev_data *
2496 to_gpio_chardev_data(struct notifier_block *nb)
2498 return container_of(nb, struct gpio_chardev_data, lineinfo_changed_nb);
2501 static int lineinfo_changed_notify(struct notifier_block *nb,
2502 unsigned long action, void *data)
2504 struct gpio_chardev_data *cdev = to_gpio_chardev_data(nb);
2505 struct gpio_v2_line_info_changed chg;
2506 struct gpio_desc *desc = data;
2509 if (!test_bit(gpio_chip_hwgpio(desc), cdev->watched_lines))
2512 memset(&chg, 0, sizeof(chg));
2513 chg.event_type = action;
2514 chg.timestamp_ns = ktime_get_ns();
2515 gpio_desc_to_lineinfo(desc, &chg.info);
2517 ret = kfifo_in_spinlocked(&cdev->events, &chg, 1, &cdev->wait.lock);
2519 wake_up_poll(&cdev->wait, EPOLLIN);
2521 pr_debug_ratelimited("lineinfo event FIFO is full - event dropped\n");
2526 static __poll_t lineinfo_watch_poll_unlocked(struct file *file,
2527 struct poll_table_struct *pollt)
2529 struct gpio_chardev_data *cdev = file->private_data;
2530 __poll_t events = 0;
2532 if (!cdev->gdev->chip)
2533 return EPOLLHUP | EPOLLERR;
2535 poll_wait(file, &cdev->wait, pollt);
2537 if (!kfifo_is_empty_spinlocked_noirqsave(&cdev->events,
2539 events = EPOLLIN | EPOLLRDNORM;
2544 static __poll_t lineinfo_watch_poll(struct file *file,
2545 struct poll_table_struct *pollt)
2547 struct gpio_chardev_data *cdev = file->private_data;
2549 return call_poll_locked(file, pollt, cdev->gdev,
2550 lineinfo_watch_poll_unlocked);
2553 static ssize_t lineinfo_watch_read_unlocked(struct file *file, char __user *buf,
2554 size_t count, loff_t *off)
2556 struct gpio_chardev_data *cdev = file->private_data;
2557 struct gpio_v2_line_info_changed event;
2558 ssize_t bytes_read = 0;
2562 if (!cdev->gdev->chip)
2565 #ifndef CONFIG_GPIO_CDEV_V1
2566 event_size = sizeof(struct gpio_v2_line_info_changed);
2567 if (count < event_size)
2572 spin_lock(&cdev->wait.lock);
2573 if (kfifo_is_empty(&cdev->events)) {
2575 spin_unlock(&cdev->wait.lock);
2579 if (file->f_flags & O_NONBLOCK) {
2580 spin_unlock(&cdev->wait.lock);
2584 ret = wait_event_interruptible_locked(cdev->wait,
2585 !kfifo_is_empty(&cdev->events));
2587 spin_unlock(&cdev->wait.lock);
2591 #ifdef CONFIG_GPIO_CDEV_V1
2592 /* must be after kfifo check so watch_abi_version is set */
2593 if (atomic_read(&cdev->watch_abi_version) == 2)
2594 event_size = sizeof(struct gpio_v2_line_info_changed);
2596 event_size = sizeof(struct gpioline_info_changed);
2597 if (count < event_size) {
2598 spin_unlock(&cdev->wait.lock);
2602 ret = kfifo_out(&cdev->events, &event, 1);
2603 spin_unlock(&cdev->wait.lock);
2607 /* We should never get here. See lineevent_read(). */
2610 #ifdef CONFIG_GPIO_CDEV_V1
2611 if (event_size == sizeof(struct gpio_v2_line_info_changed)) {
2612 if (copy_to_user(buf + bytes_read, &event, event_size))
2615 struct gpioline_info_changed event_v1;
2617 gpio_v2_line_info_changed_to_v1(&event, &event_v1);
2618 if (copy_to_user(buf + bytes_read, &event_v1,
2623 if (copy_to_user(buf + bytes_read, &event, event_size))
2626 bytes_read += event_size;
2627 } while (count >= bytes_read + sizeof(event));
2632 static ssize_t lineinfo_watch_read(struct file *file, char __user *buf,
2633 size_t count, loff_t *off)
2635 struct gpio_chardev_data *cdev = file->private_data;
2637 return call_read_locked(file, buf, count, off, cdev->gdev,
2638 lineinfo_watch_read_unlocked);
2642 * gpio_chrdev_open() - open the chardev for ioctl operations
2643 * @inode: inode for this chardev
2644 * @file: file struct for storing private data
2645 * Returns 0 on success
2647 static int gpio_chrdev_open(struct inode *inode, struct file *file)
2649 struct gpio_device *gdev = container_of(inode->i_cdev,
2650 struct gpio_device, chrdev);
2651 struct gpio_chardev_data *cdev;
2654 down_read(&gdev->sem);
2656 /* Fail on open if the backing gpiochip is gone */
2662 cdev = kzalloc(sizeof(*cdev), GFP_KERNEL);
2666 cdev->watched_lines = bitmap_zalloc(gdev->chip->ngpio, GFP_KERNEL);
2667 if (!cdev->watched_lines)
2670 init_waitqueue_head(&cdev->wait);
2671 INIT_KFIFO(cdev->events);
2674 cdev->lineinfo_changed_nb.notifier_call = lineinfo_changed_notify;
2675 ret = blocking_notifier_chain_register(&gdev->notifier,
2676 &cdev->lineinfo_changed_nb);
2678 goto out_free_bitmap;
2680 get_device(&gdev->dev);
2681 file->private_data = cdev;
2683 ret = nonseekable_open(inode, file);
2685 goto out_unregister_notifier;
2687 up_read(&gdev->sem);
2691 out_unregister_notifier:
2692 blocking_notifier_chain_unregister(&gdev->notifier,
2693 &cdev->lineinfo_changed_nb);
2695 bitmap_free(cdev->watched_lines);
2699 up_read(&gdev->sem);
2704 * gpio_chrdev_release() - close chardev after ioctl operations
2705 * @inode: inode for this chardev
2706 * @file: file struct for storing private data
2707 * Returns 0 on success
2709 static int gpio_chrdev_release(struct inode *inode, struct file *file)
2711 struct gpio_chardev_data *cdev = file->private_data;
2712 struct gpio_device *gdev = cdev->gdev;
2714 bitmap_free(cdev->watched_lines);
2715 blocking_notifier_chain_unregister(&gdev->notifier,
2716 &cdev->lineinfo_changed_nb);
2717 put_device(&gdev->dev);
2723 static const struct file_operations gpio_fileops = {
2724 .release = gpio_chrdev_release,
2725 .open = gpio_chrdev_open,
2726 .poll = lineinfo_watch_poll,
2727 .read = lineinfo_watch_read,
2728 .owner = THIS_MODULE,
2729 .llseek = no_llseek,
2730 .unlocked_ioctl = gpio_ioctl,
2731 #ifdef CONFIG_COMPAT
2732 .compat_ioctl = gpio_ioctl_compat,
2736 int gpiolib_cdev_register(struct gpio_device *gdev, dev_t devt)
2740 cdev_init(&gdev->chrdev, &gpio_fileops);
2741 gdev->chrdev.owner = THIS_MODULE;
2742 gdev->dev.devt = MKDEV(MAJOR(devt), gdev->id);
2744 ret = cdev_device_add(&gdev->chrdev, &gdev->dev);
2748 chip_dbg(gdev->chip, "added GPIO chardev (%d:%d)\n",
2749 MAJOR(devt), gdev->id);
2754 void gpiolib_cdev_unregister(struct gpio_device *gdev)
2756 cdev_device_del(&gdev->chrdev, &gdev->dev);