GNU Linux-libre 6.1.24-gnu
[releases.git] / drivers / gpio / gpiolib-cdev.c
1 // SPDX-License-Identifier: GPL-2.0
2
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>
29
30 #include "gpiolib.h"
31 #include "gpiolib-cdev.h"
32
33 /*
34  * Array sizes must ensure 64-bit alignment and not create holes in the
35  * struct packing.
36  */
37 static_assert(IS_ALIGNED(GPIO_V2_LINES_MAX, 2));
38 static_assert(IS_ALIGNED(GPIO_MAX_NAME_SIZE, 8));
39
40 /*
41  * Check that uAPI structs are 64-bit aligned for 32/64-bit compatibility
42  */
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));
51
52 /* Character device interface to GPIO.
53  *
54  * The GPIO character device, /dev/gpiochipN, provides userspace an
55  * interface to gpiolib GPIOs via ioctl()s.
56  */
57
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 *);
62
63 static __poll_t call_poll_locked(struct file *file,
64                                  struct poll_table_struct *wait,
65                                  struct gpio_device *gdev, poll_fn func)
66 {
67         __poll_t ret;
68
69         down_read(&gdev->sem);
70         ret = func(file, wait);
71         up_read(&gdev->sem);
72
73         return ret;
74 }
75
76 static long call_ioctl_locked(struct file *file, unsigned int cmd,
77                               unsigned long arg, struct gpio_device *gdev,
78                               ioctl_fn func)
79 {
80         long ret;
81
82         down_read(&gdev->sem);
83         ret = func(file, cmd, arg);
84         up_read(&gdev->sem);
85
86         return ret;
87 }
88
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)
92 {
93         ssize_t ret;
94
95         down_read(&gdev->sem);
96         ret = func(file, buf, count, f_ps);
97         up_read(&gdev->sem);
98
99         return ret;
100 }
101
102 /*
103  * GPIO line handle management
104  */
105
106 #ifdef CONFIG_GPIO_CDEV_V1
107 /**
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
113  */
114 struct linehandle_state {
115         struct gpio_device *gdev;
116         const char *label;
117         struct gpio_desc *descs[GPIOHANDLES_MAX];
118         u32 num_descs;
119 };
120
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)
130
131 static int linehandle_validate_flags(u32 flags)
132 {
133         /* Return an error if an unknown flag is set */
134         if (flags & ~GPIOHANDLE_REQUEST_VALID_FLAGS)
135                 return -EINVAL;
136
137         /*
138          * Do not allow both INPUT & OUTPUT flags to be set as they are
139          * contradictory.
140          */
141         if ((flags & GPIOHANDLE_REQUEST_INPUT) &&
142             (flags & GPIOHANDLE_REQUEST_OUTPUT))
143                 return -EINVAL;
144
145         /*
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.
149          */
150         if ((flags & GPIOHANDLE_REQUEST_OPEN_DRAIN) &&
151             (flags & GPIOHANDLE_REQUEST_OPEN_SOURCE))
152                 return -EINVAL;
153
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)))
158                 return -EINVAL;
159
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)))
166                 return -EINVAL;
167
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)))
174                 return -EINVAL;
175
176         return 0;
177 }
178
179 static void linehandle_flags_to_desc_flags(u32 lflags, unsigned long *flagsp)
180 {
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);
193 }
194
195 static long linehandle_set_config(struct linehandle_state *lh,
196                                   void __user *ip)
197 {
198         struct gpiohandle_config gcnf;
199         struct gpio_desc *desc;
200         int i, ret;
201         u32 lflags;
202
203         if (copy_from_user(&gcnf, ip, sizeof(gcnf)))
204                 return -EFAULT;
205
206         lflags = gcnf.flags;
207         ret = linehandle_validate_flags(lflags);
208         if (ret)
209                 return ret;
210
211         for (i = 0; i < lh->num_descs; i++) {
212                 desc = lh->descs[i];
213                 linehandle_flags_to_desc_flags(gcnf.flags, &desc->flags);
214
215                 /*
216                  * Lines have to be requested explicitly for input
217                  * or output, else the line will be treated "as is".
218                  */
219                 if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
220                         int val = !!gcnf.default_values[i];
221
222                         ret = gpiod_direction_output(desc, val);
223                         if (ret)
224                                 return ret;
225                 } else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
226                         ret = gpiod_direction_input(desc);
227                         if (ret)
228                                 return ret;
229                 }
230
231                 blocking_notifier_call_chain(&desc->gdev->notifier,
232                                              GPIO_V2_LINE_CHANGED_CONFIG,
233                                              desc);
234         }
235         return 0;
236 }
237
238 static long linehandle_ioctl_unlocked(struct file *file, unsigned int cmd,
239                                       unsigned long arg)
240 {
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);
245         unsigned int i;
246         int ret;
247
248         if (!lh->gdev->chip)
249                 return -ENODEV;
250
251         switch (cmd) {
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,
256                                                     NULL, vals);
257                 if (ret)
258                         return ret;
259
260                 memset(&ghd, 0, sizeof(ghd));
261                 for (i = 0; i < lh->num_descs; i++)
262                         ghd.values[i] = test_bit(i, vals);
263
264                 if (copy_to_user(ip, &ghd, sizeof(ghd)))
265                         return -EFAULT;
266
267                 return 0;
268         case GPIOHANDLE_SET_LINE_VALUES_IOCTL:
269                 /*
270                  * All line descriptors were created at once with the same
271                  * flags so just check if the first one is really output.
272                  */
273                 if (!test_bit(FLAG_IS_OUT, &lh->descs[0]->flags))
274                         return -EPERM;
275
276                 if (copy_from_user(&ghd, ip, sizeof(ghd)))
277                         return -EFAULT;
278
279                 /* Clamp all values to [0,1] */
280                 for (i = 0; i < lh->num_descs; i++)
281                         __assign_bit(i, vals, ghd.values[i]);
282
283                 /* Reuse the array setting function */
284                 return gpiod_set_array_value_complex(false,
285                                                      true,
286                                                      lh->num_descs,
287                                                      lh->descs,
288                                                      NULL,
289                                                      vals);
290         case GPIOHANDLE_SET_CONFIG_IOCTL:
291                 return linehandle_set_config(lh, ip);
292         default:
293                 return -EINVAL;
294         }
295 }
296
297 static long linehandle_ioctl(struct file *file, unsigned int cmd,
298                              unsigned long arg)
299 {
300         struct linehandle_state *lh = file->private_data;
301
302         return call_ioctl_locked(file, cmd, arg, lh->gdev,
303                                  linehandle_ioctl_unlocked);
304 }
305
306 #ifdef CONFIG_COMPAT
307 static long linehandle_ioctl_compat(struct file *file, unsigned int cmd,
308                                     unsigned long arg)
309 {
310         return linehandle_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
311 }
312 #endif
313
314 static void linehandle_free(struct linehandle_state *lh)
315 {
316         int i;
317
318         for (i = 0; i < lh->num_descs; i++)
319                 if (lh->descs[i])
320                         gpiod_free(lh->descs[i]);
321         kfree(lh->label);
322         put_device(&lh->gdev->dev);
323         kfree(lh);
324 }
325
326 static int linehandle_release(struct inode *inode, struct file *file)
327 {
328         linehandle_free(file->private_data);
329         return 0;
330 }
331
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,
337 #ifdef CONFIG_COMPAT
338         .compat_ioctl = linehandle_ioctl_compat,
339 #endif
340 };
341
342 static int linehandle_create(struct gpio_device *gdev, void __user *ip)
343 {
344         struct gpiohandle_request handlereq;
345         struct linehandle_state *lh;
346         struct file *file;
347         int fd, i, ret;
348         u32 lflags;
349
350         if (copy_from_user(&handlereq, ip, sizeof(handlereq)))
351                 return -EFAULT;
352         if ((handlereq.lines == 0) || (handlereq.lines > GPIOHANDLES_MAX))
353                 return -EINVAL;
354
355         lflags = handlereq.flags;
356
357         ret = linehandle_validate_flags(lflags);
358         if (ret)
359                 return ret;
360
361         lh = kzalloc(sizeof(*lh), GFP_KERNEL);
362         if (!lh)
363                 return -ENOMEM;
364         lh->gdev = gdev;
365         get_device(&gdev->dev);
366
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,
371                                      GFP_KERNEL);
372                 if (!lh->label) {
373                         ret = -ENOMEM;
374                         goto out_free_lh;
375                 }
376         }
377
378         lh->num_descs = handlereq.lines;
379
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);
384
385                 if (IS_ERR(desc)) {
386                         ret = PTR_ERR(desc);
387                         goto out_free_lh;
388                 }
389
390                 ret = gpiod_request_user(desc, lh->label);
391                 if (ret)
392                         goto out_free_lh;
393                 lh->descs[i] = desc;
394                 linehandle_flags_to_desc_flags(handlereq.flags, &desc->flags);
395
396                 ret = gpiod_set_transitory(desc, false);
397                 if (ret < 0)
398                         goto out_free_lh;
399
400                 /*
401                  * Lines have to be requested explicitly for input
402                  * or output, else the line will be treated "as is".
403                  */
404                 if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
405                         int val = !!handlereq.default_values[i];
406
407                         ret = gpiod_direction_output(desc, val);
408                         if (ret)
409                                 goto out_free_lh;
410                 } else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
411                         ret = gpiod_direction_input(desc);
412                         if (ret)
413                                 goto out_free_lh;
414                 }
415
416                 blocking_notifier_call_chain(&desc->gdev->notifier,
417                                              GPIO_V2_LINE_CHANGED_REQUESTED, desc);
418
419                 dev_dbg(&gdev->dev, "registered chardev handle for line %d\n",
420                         offset);
421         }
422
423         fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
424         if (fd < 0) {
425                 ret = fd;
426                 goto out_free_lh;
427         }
428
429         file = anon_inode_getfile("gpio-linehandle",
430                                   &linehandle_fileops,
431                                   lh,
432                                   O_RDONLY | O_CLOEXEC);
433         if (IS_ERR(file)) {
434                 ret = PTR_ERR(file);
435                 goto out_put_unused_fd;
436         }
437
438         handlereq.fd = fd;
439         if (copy_to_user(ip, &handlereq, sizeof(handlereq))) {
440                 /*
441                  * fput() will trigger the release() callback, so do not go onto
442                  * the regular error cleanup path here.
443                  */
444                 fput(file);
445                 put_unused_fd(fd);
446                 return -EFAULT;
447         }
448
449         fd_install(fd, file);
450
451         dev_dbg(&gdev->dev, "registered chardev handle for %d lines\n",
452                 lh->num_descs);
453
454         return 0;
455
456 out_put_unused_fd:
457         put_unused_fd(fd);
458 out_free_lh:
459         linehandle_free(lh);
460         return ret;
461 }
462 #endif /* CONFIG_GPIO_CDEV_V1 */
463
464 /**
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
484  */
485 struct line {
486         struct gpio_desc *desc;
487         /*
488          * -- edge detector specific fields --
489          */
490         struct linereq *req;
491         unsigned int irq;
492         /*
493          * The flags for the active edge detector configuration.
494          *
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.
500          */
501         u64 edflags;
502         /*
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.
506          */
507         u64 timestamp_ns;
508         u32 req_seqno;
509         /*
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.
513          */
514         u32 line_seqno;
515         /*
516          * -- debouncer specific fields --
517          */
518         struct delayed_work work;
519         /*
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.
523          */
524         unsigned int sw_debounced;
525         /*
526          * level is accessed by debounce_work_func(), which is the only
527          * setter, and linereq_get_values() which can live with a slightly
528          * stale value.
529          */
530         unsigned int level;
531 #ifdef CONFIG_HTE
532         struct hte_ts_desc hdesc;
533         /*
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.
536          */
537         int raw_level;
538         /*
539          * when sw_debounce is set on HTE enabled line, this is running
540          * counter of the discarded events.
541          */
542         u32 total_discard_seq;
543         /*
544          * when sw_debounce is set on HTE enabled line, this variable records
545          * last sequence number before debounce period expires.
546          */
547         u32 last_seqno;
548 #endif /* CONFIG_HTE */
549 };
550
551 /**
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.
565  */
566 struct linereq {
567         struct gpio_device *gdev;
568         const char *label;
569         u32 num_lines;
570         wait_queue_head_t wait;
571         u32 event_buffer_size;
572         DECLARE_KFIFO_PTR(events, struct gpio_v2_line_event);
573         atomic_t seqno;
574         struct mutex config_mutex;
575         struct line lines[];
576 };
577
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)
582
583 #define GPIO_V2_LINE_DIRECTION_FLAGS \
584         (GPIO_V2_LINE_FLAG_INPUT | \
585          GPIO_V2_LINE_FLAG_OUTPUT)
586
587 #define GPIO_V2_LINE_DRIVE_FLAGS \
588         (GPIO_V2_LINE_FLAG_OPEN_DRAIN | \
589          GPIO_V2_LINE_FLAG_OPEN_SOURCE)
590
591 #define GPIO_V2_LINE_EDGE_FLAGS \
592         (GPIO_V2_LINE_FLAG_EDGE_RISING | \
593          GPIO_V2_LINE_FLAG_EDGE_FALLING)
594
595 #define GPIO_V2_LINE_FLAG_EDGE_BOTH GPIO_V2_LINE_EDGE_FLAGS
596
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)
605
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)
611
612 static void linereq_put_event(struct linereq *lr,
613                               struct gpio_v2_line_event *le)
614 {
615         bool overflow = false;
616
617         spin_lock(&lr->wait.lock);
618         if (kfifo_is_full(&lr->events)) {
619                 overflow = true;
620                 kfifo_skip(&lr->events);
621         }
622         kfifo_in(&lr->events, le, 1);
623         spin_unlock(&lr->wait.lock);
624         if (!overflow)
625                 wake_up_poll(&lr->wait, EPOLLIN);
626         else
627                 pr_debug_ratelimited("event FIFO is full - event dropped\n");
628 }
629
630 static u64 line_event_timestamp(struct line *line)
631 {
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;
637
638         return ktime_get_ns();
639 }
640
641 static u32 line_event_id(int level)
642 {
643         return level ? GPIO_V2_LINE_EVENT_RISING_EDGE :
644                        GPIO_V2_LINE_EVENT_FALLING_EDGE;
645 }
646
647 #ifdef CONFIG_HTE
648
649 static enum hte_return process_hw_ts_thread(void *p)
650 {
651         struct line *line;
652         struct linereq *lr;
653         struct gpio_v2_line_event le;
654         u64 edflags;
655         int level;
656
657         if (!p)
658                 return HTE_CB_HANDLED;
659
660         line = p;
661         lr = line->req;
662
663         memset(&le, 0, sizeof(le));
664
665         le.timestamp_ns = line->timestamp_ns;
666         edflags = READ_ONCE(line->edflags);
667
668         switch (edflags & GPIO_V2_LINE_EDGE_FLAGS) {
669         case GPIO_V2_LINE_FLAG_EDGE_BOTH:
670                 level = (line->raw_level >= 0) ?
671                                 line->raw_level :
672                                 gpiod_get_raw_value_cansleep(line->desc);
673
674                 if (edflags & GPIO_V2_LINE_FLAG_ACTIVE_LOW)
675                         level = !level;
676
677                 le.id = line_event_id(level);
678                 break;
679         case GPIO_V2_LINE_FLAG_EDGE_RISING:
680                 le.id = GPIO_V2_LINE_EVENT_RISING_EDGE;
681                 break;
682         case GPIO_V2_LINE_FLAG_EDGE_FALLING:
683                 le.id = GPIO_V2_LINE_EVENT_FALLING_EDGE;
684                 break;
685         default:
686                 return HTE_CB_HANDLED;
687         }
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);
691
692         linereq_put_event(lr, &le);
693
694         return HTE_CB_HANDLED;
695 }
696
697 static enum hte_return process_hw_ts(struct hte_ts_data *ts, void *p)
698 {
699         struct line *line;
700         struct linereq *lr;
701         int diff_seqno = 0;
702
703         if (!ts || !p)
704                 return HTE_CB_HANDLED;
705
706         line = p;
707         line->timestamp_ns = ts->tsc;
708         line->raw_level = ts->raw_level;
709         lr = line->req;
710
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)));
716         } else {
717                 if (unlikely(ts->seq < line->line_seqno))
718                         return HTE_CB_HANDLED;
719
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,
724                                                             &lr->seqno);
725
726                 return HTE_RUN_SECOND_CB;
727         }
728
729         return HTE_CB_HANDLED;
730 }
731
732 static int hte_edge_setup(struct line *line, u64 eflags)
733 {
734         int ret;
735         unsigned long flags = 0;
736         struct hte_ts_desc *hdesc = &line->hdesc;
737
738         if (eflags & GPIO_V2_LINE_FLAG_EDGE_RISING)
739                 flags |= test_bit(FLAG_ACTIVE_LOW, &line->desc->flags) ?
740                                  HTE_FALLING_EDGE_TS :
741                                  HTE_RISING_EDGE_TS;
742         if (eflags & GPIO_V2_LINE_FLAG_EDGE_FALLING)
743                 flags |= test_bit(FLAG_ACTIVE_LOW, &line->desc->flags) ?
744                                  HTE_RISING_EDGE_TS :
745                                  HTE_FALLING_EDGE_TS;
746
747         line->total_discard_seq = 0;
748
749         hte_init_line_attr(hdesc, desc_to_gpio(line->desc), flags, NULL,
750                            line->desc);
751
752         ret = hte_ts_get(NULL, hdesc, 0);
753         if (ret)
754                 return ret;
755
756         return hte_request_ts_ns(hdesc, process_hw_ts, process_hw_ts_thread,
757                                  line);
758 }
759
760 #else
761
762 static int hte_edge_setup(struct line *line, u64 eflags)
763 {
764         return 0;
765 }
766 #endif /* CONFIG_HTE */
767
768 static irqreturn_t edge_irq_thread(int irq, void *p)
769 {
770         struct line *line = p;
771         struct linereq *lr = line->req;
772         struct gpio_v2_line_event le;
773
774         /* Do not leak kernel stack to userspace */
775         memset(&le, 0, sizeof(le));
776
777         if (line->timestamp_ns) {
778                 le.timestamp_ns = line->timestamp_ns;
779         } else {
780                 /*
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().
784                  */
785                 le.timestamp_ns = line_event_timestamp(line);
786                 if (lr->num_lines != 1)
787                         line->req_seqno = atomic_inc_return(&lr->seqno);
788         }
789         line->timestamp_ns = 0;
790
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));
794                 break;
795         case GPIO_V2_LINE_FLAG_EDGE_RISING:
796                 le.id = GPIO_V2_LINE_EVENT_RISING_EDGE;
797                 break;
798         case GPIO_V2_LINE_FLAG_EDGE_FALLING:
799                 le.id = GPIO_V2_LINE_EVENT_FALLING_EDGE;
800                 break;
801         default:
802                 return IRQ_NONE;
803         }
804         line->line_seqno++;
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);
808
809         linereq_put_event(lr, &le);
810
811         return IRQ_HANDLED;
812 }
813
814 static irqreturn_t edge_irq_handler(int irq, void *p)
815 {
816         struct line *line = p;
817         struct linereq *lr = line->req;
818
819         /*
820          * Just store the timestamp in hardirq context so we get it as
821          * close in time as possible to the actual event.
822          */
823         line->timestamp_ns = line_event_timestamp(line);
824
825         if (lr->num_lines != 1)
826                 line->req_seqno = atomic_inc_return(&lr->seqno);
827
828         return IRQ_WAKE_THREAD;
829 }
830
831 /*
832  * returns the current debounced logical value.
833  */
834 static bool debounced_value(struct line *line)
835 {
836         bool value;
837
838         /*
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.
842          */
843         value = READ_ONCE(line->level);
844
845         if (test_bit(FLAG_ACTIVE_LOW, &line->desc->flags))
846                 value = !value;
847
848         return value;
849 }
850
851 static irqreturn_t debounce_irq_handler(int irq, void *p)
852 {
853         struct line *line = p;
854
855         mod_delayed_work(system_wq, &line->work,
856                 usecs_to_jiffies(READ_ONCE(line->desc->debounce_period_us)));
857
858         return IRQ_HANDLED;
859 }
860
861 static void debounce_work_func(struct work_struct *work)
862 {
863         struct gpio_v2_line_event le;
864         struct line *line = container_of(work, struct line, work.work);
865         struct linereq *lr;
866         u64 eflags, edflags = READ_ONCE(line->edflags);
867         int level = -1;
868 #ifdef CONFIG_HTE
869         int diff_seqno;
870
871         if (edflags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE)
872                 level = line->raw_level;
873 #endif
874         if (level < 0)
875                 level = gpiod_get_raw_value_cansleep(line->desc);
876         if (level < 0) {
877                 pr_debug_ratelimited("debouncer failed to read line value\n");
878                 return;
879         }
880
881         if (READ_ONCE(line->level) == level)
882                 return;
883
884         WRITE_ONCE(line->level, level);
885
886         /* -- edge detection -- */
887         eflags = edflags & GPIO_V2_LINE_EDGE_FLAGS;
888         if (!eflags)
889                 return;
890
891         /* switch from physical level to logical - if they differ */
892         if (edflags & GPIO_V2_LINE_FLAG_ACTIVE_LOW)
893                 level = !level;
894
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))
898                 return;
899
900         /* Do not leak kernel stack to userspace */
901         memset(&le, 0, sizeof(le));
902
903         lr = line->req;
904         le.timestamp_ns = line_event_timestamp(line);
905         le.offset = gpio_chip_hwgpio(line->desc);
906 #ifdef CONFIG_HTE
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 -
911                                 line->line_seqno;
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);
916         } else
917 #endif /* CONFIG_HTE */
918         {
919                 line->line_seqno++;
920                 le.line_seqno = line->line_seqno;
921                 le.seqno = (lr->num_lines == 1) ?
922                         le.line_seqno : atomic_inc_return(&lr->seqno);
923         }
924
925         le.id = line_event_id(level);
926
927         linereq_put_event(lr, &le);
928 }
929
930 static int debounce_setup(struct line *line, unsigned int debounce_period_us)
931 {
932         unsigned long irqflags;
933         int ret, level, irq;
934
935         /* try hardware */
936         ret = gpiod_set_debounce(line->desc, debounce_period_us);
937         if (!ret) {
938                 WRITE_ONCE(line->desc->debounce_period_us, debounce_period_us);
939                 return ret;
940         }
941         if (ret != -ENOTSUPP)
942                 return ret;
943
944         if (debounce_period_us) {
945                 /* setup software debounce */
946                 level = gpiod_get_raw_value_cansleep(line->desc);
947                 if (level < 0)
948                         return level;
949
950                 if (!(IS_ENABLED(CONFIG_HTE) &&
951                       test_bit(FLAG_EVENT_CLOCK_HTE, &line->desc->flags))) {
952                         irq = gpiod_to_irq(line->desc);
953                         if (irq < 0)
954                                 return -ENXIO;
955
956                         irqflags = IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING;
957                         ret = request_irq(irq, debounce_irq_handler, irqflags,
958                                           line->req->label, line);
959                         if (ret)
960                                 return ret;
961                         line->irq = irq;
962                 } else {
963                         ret = hte_edge_setup(line, GPIO_V2_LINE_FLAG_EDGE_BOTH);
964                         if (ret)
965                                 return ret;
966                 }
967
968                 WRITE_ONCE(line->level, level);
969                 WRITE_ONCE(line->sw_debounced, 1);
970         }
971         return 0;
972 }
973
974 static bool gpio_v2_line_config_debounced(struct gpio_v2_line_config *lc,
975                                           unsigned int line_idx)
976 {
977         unsigned int i;
978         u64 mask = BIT_ULL(line_idx);
979
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))
983                         return true;
984         }
985         return false;
986 }
987
988 static u32 gpio_v2_line_config_debounce_period(struct gpio_v2_line_config *lc,
989                                                unsigned int line_idx)
990 {
991         unsigned int i;
992         u64 mask = BIT_ULL(line_idx);
993
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;
998         }
999         return 0;
1000 }
1001
1002 static void edge_detector_stop(struct line *line)
1003 {
1004         if (line->irq) {
1005                 free_irq(line->irq, line);
1006                 line->irq = 0;
1007         }
1008
1009 #ifdef CONFIG_HTE
1010         if (READ_ONCE(line->edflags) & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE)
1011                 hte_ts_put(&line->hdesc);
1012 #endif
1013
1014         cancel_delayed_work_sync(&line->work);
1015         WRITE_ONCE(line->sw_debounced, 0);
1016         WRITE_ONCE(line->edflags, 0);
1017         if (line->desc)
1018                 WRITE_ONCE(line->desc->debounce_period_us, 0);
1019         /* do not change line->level - see comment in debounced_value() */
1020 }
1021
1022 static int edge_detector_setup(struct line *line,
1023                                struct gpio_v2_line_config *lc,
1024                                unsigned int line_idx, u64 edflags)
1025 {
1026         u32 debounce_period_us;
1027         unsigned long irqflags = 0;
1028         u64 eflags;
1029         int irq, ret;
1030
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);
1035                 if (ret)
1036                         return ret;
1037         }
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);
1041                 if (ret)
1042                         return ret;
1043                 WRITE_ONCE(line->desc->debounce_period_us, debounce_period_us);
1044         }
1045
1046         /* detection disabled or sw debouncer will provide edge detection */
1047         if (!eflags || READ_ONCE(line->sw_debounced))
1048                 return 0;
1049
1050         if (IS_ENABLED(CONFIG_HTE) &&
1051             (edflags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE))
1052                 return hte_edge_setup(line, edflags);
1053
1054         irq = gpiod_to_irq(line->desc);
1055         if (irq < 0)
1056                 return -ENXIO;
1057
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;
1065
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);
1069         if (ret)
1070                 return ret;
1071
1072         line->irq = irq;
1073         return 0;
1074 }
1075
1076 static int edge_detector_update(struct line *line,
1077                                 struct gpio_v2_line_config *lc,
1078                                 unsigned int line_idx, u64 edflags)
1079 {
1080         u64 active_edflags = READ_ONCE(line->edflags);
1081         unsigned int debounce_period_us =
1082                         gpio_v2_line_config_debounce_period(lc, line_idx);
1083
1084         if ((active_edflags == edflags) &&
1085             (READ_ONCE(line->desc->debounce_period_us) == debounce_period_us))
1086                 return 0;
1087
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);
1091                 return 0;
1092         }
1093
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);
1099
1100         return edge_detector_setup(line, lc, line_idx, edflags);
1101 }
1102
1103 static u64 gpio_v2_line_config_flags(struct gpio_v2_line_config *lc,
1104                                      unsigned int line_idx)
1105 {
1106         unsigned int i;
1107         u64 mask = BIT_ULL(line_idx);
1108
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;
1113         }
1114         return lc->flags;
1115 }
1116
1117 static int gpio_v2_line_config_output_value(struct gpio_v2_line_config *lc,
1118                                             unsigned int line_idx)
1119 {
1120         unsigned int i;
1121         u64 mask = BIT_ULL(line_idx);
1122
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);
1127         }
1128         return 0;
1129 }
1130
1131 static int gpio_v2_line_flags_validate(u64 flags)
1132 {
1133         /* Return an error if an unknown flag is set */
1134         if (flags & ~GPIO_V2_LINE_VALID_FLAGS)
1135                 return -EINVAL;
1136
1137         if (!IS_ENABLED(CONFIG_HTE) &&
1138             (flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE))
1139                 return -EOPNOTSUPP;
1140
1141         /*
1142          * Do not allow both INPUT and OUTPUT flags to be set as they are
1143          * contradictory.
1144          */
1145         if ((flags & GPIO_V2_LINE_FLAG_INPUT) &&
1146             (flags & GPIO_V2_LINE_FLAG_OUTPUT))
1147                 return -EINVAL;
1148
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))
1153                 return -EINVAL;
1154
1155         /* Edge detection requires explicit input. */
1156         if ((flags & GPIO_V2_LINE_EDGE_FLAGS) &&
1157             !(flags & GPIO_V2_LINE_FLAG_INPUT))
1158                 return -EINVAL;
1159
1160         /*
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.
1164          */
1165         if ((flags & GPIO_V2_LINE_FLAG_OPEN_DRAIN) &&
1166             (flags & GPIO_V2_LINE_FLAG_OPEN_SOURCE))
1167                 return -EINVAL;
1168
1169         /* Drive requires explicit output direction. */
1170         if ((flags & GPIO_V2_LINE_DRIVE_FLAGS) &&
1171             !(flags & GPIO_V2_LINE_FLAG_OUTPUT))
1172                 return -EINVAL;
1173
1174         /* Bias requires explicit direction. */
1175         if ((flags & GPIO_V2_LINE_BIAS_FLAGS) &&
1176             !(flags & GPIO_V2_LINE_DIRECTION_FLAGS))
1177                 return -EINVAL;
1178
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)))
1185                 return -EINVAL;
1186
1187         return 0;
1188 }
1189
1190 static int gpio_v2_line_config_validate(struct gpio_v2_line_config *lc,
1191                                         unsigned int num_lines)
1192 {
1193         unsigned int i;
1194         u64 flags;
1195         int ret;
1196
1197         if (lc->num_attrs > GPIO_V2_LINE_NUM_ATTRS_MAX)
1198                 return -EINVAL;
1199
1200         if (memchr_inv(lc->padding, 0, sizeof(lc->padding)))
1201                 return -EINVAL;
1202
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);
1206                 if (ret)
1207                         return ret;
1208
1209                 /* debounce requires explicit input */
1210                 if (gpio_v2_line_config_debounced(lc, i) &&
1211                     !(flags & GPIO_V2_LINE_FLAG_INPUT))
1212                         return -EINVAL;
1213         }
1214         return 0;
1215 }
1216
1217 static void gpio_v2_line_config_flags_to_desc_flags(u64 flags,
1218                                                     unsigned long *flagsp)
1219 {
1220         assign_bit(FLAG_ACTIVE_LOW, flagsp,
1221                    flags & GPIO_V2_LINE_FLAG_ACTIVE_LOW);
1222
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);
1227
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);
1232
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);
1237
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);
1244
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);
1249 }
1250
1251 static long linereq_get_values(struct linereq *lr, void __user *ip)
1252 {
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;
1257         bool val;
1258         int ret;
1259
1260         /* NOTE: It's ok to read values of output lines. */
1261         if (copy_from_user(&lv, ip, sizeof(lv)))
1262                 return -EFAULT;
1263
1264         for (num_get = 0, i = 0; i < lr->num_lines; i++) {
1265                 if (lv.mask & BIT_ULL(i)) {
1266                         num_get++;
1267                         descs = &lr->lines[i].desc;
1268                 }
1269         }
1270
1271         if (num_get == 0)
1272                 return -EINVAL;
1273
1274         if (num_get != 1) {
1275                 descs = kmalloc_array(num_get, sizeof(*descs), GFP_KERNEL);
1276                 if (!descs)
1277                         return -ENOMEM;
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;
1281                                 didx++;
1282                         }
1283                 }
1284         }
1285         ret = gpiod_get_array_value_complex(false, true, num_get,
1286                                             descs, NULL, vals);
1287
1288         if (num_get != 1)
1289                 kfree(descs);
1290         if (ret)
1291                 return ret;
1292
1293         lv.bits = 0;
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]);
1298                         else
1299                                 val = test_bit(didx, vals);
1300                         if (val)
1301                                 lv.bits |= BIT_ULL(i);
1302                         didx++;
1303                 }
1304         }
1305
1306         if (copy_to_user(ip, &lv, sizeof(lv)))
1307                 return -EFAULT;
1308
1309         return 0;
1310 }
1311
1312 static long linereq_set_values_unlocked(struct linereq *lr,
1313                                         struct gpio_v2_line_values *lv)
1314 {
1315         DECLARE_BITMAP(vals, GPIO_V2_LINES_MAX);
1316         struct gpio_desc **descs;
1317         unsigned int i, didx, num_set;
1318         int ret;
1319
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))
1324                                 return -EPERM;
1325                         if (lv->bits & BIT_ULL(i))
1326                                 __set_bit(num_set, vals);
1327                         num_set++;
1328                         descs = &lr->lines[i].desc;
1329                 }
1330         }
1331         if (num_set == 0)
1332                 return -EINVAL;
1333
1334         if (num_set != 1) {
1335                 /* build compacted desc array and values */
1336                 descs = kmalloc_array(num_set, sizeof(*descs), GFP_KERNEL);
1337                 if (!descs)
1338                         return -ENOMEM;
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;
1342                                 didx++;
1343                         }
1344                 }
1345         }
1346         ret = gpiod_set_array_value_complex(false, true, num_set,
1347                                             descs, NULL, vals);
1348
1349         if (num_set != 1)
1350                 kfree(descs);
1351         return ret;
1352 }
1353
1354 static long linereq_set_values(struct linereq *lr, void __user *ip)
1355 {
1356         struct gpio_v2_line_values lv;
1357         int ret;
1358
1359         if (copy_from_user(&lv, ip, sizeof(lv)))
1360                 return -EFAULT;
1361
1362         mutex_lock(&lr->config_mutex);
1363
1364         ret = linereq_set_values_unlocked(lr, &lv);
1365
1366         mutex_unlock(&lr->config_mutex);
1367
1368         return ret;
1369 }
1370
1371 static long linereq_set_config_unlocked(struct linereq *lr,
1372                                         struct gpio_v2_line_config *lc)
1373 {
1374         struct gpio_desc *desc;
1375         struct line *line;
1376         unsigned int i;
1377         u64 flags, edflags;
1378         int ret;
1379
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;
1386                 /*
1387                  * Lines have to be requested explicitly for input
1388                  * or output, else the line will be treated "as is".
1389                  */
1390                 if (flags & GPIO_V2_LINE_FLAG_OUTPUT) {
1391                         int val = gpio_v2_line_config_output_value(lc, i);
1392
1393                         edge_detector_stop(line);
1394                         ret = gpiod_direction_output(desc, val);
1395                         if (ret)
1396                                 return ret;
1397                 } else if (flags & GPIO_V2_LINE_FLAG_INPUT) {
1398                         ret = gpiod_direction_input(desc);
1399                         if (ret)
1400                                 return ret;
1401
1402                         ret = edge_detector_update(line, lc, i, edflags);
1403                         if (ret)
1404                                 return ret;
1405                 }
1406
1407                 WRITE_ONCE(line->edflags, edflags);
1408
1409                 blocking_notifier_call_chain(&desc->gdev->notifier,
1410                                              GPIO_V2_LINE_CHANGED_CONFIG,
1411                                              desc);
1412         }
1413         return 0;
1414 }
1415
1416 static long linereq_set_config(struct linereq *lr, void __user *ip)
1417 {
1418         struct gpio_v2_line_config lc;
1419         int ret;
1420
1421         if (copy_from_user(&lc, ip, sizeof(lc)))
1422                 return -EFAULT;
1423
1424         ret = gpio_v2_line_config_validate(&lc, lr->num_lines);
1425         if (ret)
1426                 return ret;
1427
1428         mutex_lock(&lr->config_mutex);
1429
1430         ret = linereq_set_config_unlocked(lr, &lc);
1431
1432         mutex_unlock(&lr->config_mutex);
1433
1434         return ret;
1435 }
1436
1437 static long linereq_ioctl_unlocked(struct file *file, unsigned int cmd,
1438                                    unsigned long arg)
1439 {
1440         struct linereq *lr = file->private_data;
1441         void __user *ip = (void __user *)arg;
1442
1443         if (!lr->gdev->chip)
1444                 return -ENODEV;
1445
1446         switch (cmd) {
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);
1453         default:
1454                 return -EINVAL;
1455         }
1456 }
1457
1458 static long linereq_ioctl(struct file *file, unsigned int cmd,
1459                           unsigned long arg)
1460 {
1461         struct linereq *lr = file->private_data;
1462
1463         return call_ioctl_locked(file, cmd, arg, lr->gdev,
1464                                  linereq_ioctl_unlocked);
1465 }
1466
1467 #ifdef CONFIG_COMPAT
1468 static long linereq_ioctl_compat(struct file *file, unsigned int cmd,
1469                                  unsigned long arg)
1470 {
1471         return linereq_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
1472 }
1473 #endif
1474
1475 static __poll_t linereq_poll_unlocked(struct file *file,
1476                                       struct poll_table_struct *wait)
1477 {
1478         struct linereq *lr = file->private_data;
1479         __poll_t events = 0;
1480
1481         if (!lr->gdev->chip)
1482                 return EPOLLHUP | EPOLLERR;
1483
1484         poll_wait(file, &lr->wait, wait);
1485
1486         if (!kfifo_is_empty_spinlocked_noirqsave(&lr->events,
1487                                                  &lr->wait.lock))
1488                 events = EPOLLIN | EPOLLRDNORM;
1489
1490         return events;
1491 }
1492
1493 static __poll_t linereq_poll(struct file *file,
1494                              struct poll_table_struct *wait)
1495 {
1496         struct linereq *lr = file->private_data;
1497
1498         return call_poll_locked(file, wait, lr->gdev, linereq_poll_unlocked);
1499 }
1500
1501 static ssize_t linereq_read_unlocked(struct file *file, char __user *buf,
1502                                      size_t count, loff_t *f_ps)
1503 {
1504         struct linereq *lr = file->private_data;
1505         struct gpio_v2_line_event le;
1506         ssize_t bytes_read = 0;
1507         int ret;
1508
1509         if (!lr->gdev->chip)
1510                 return -ENODEV;
1511
1512         if (count < sizeof(le))
1513                 return -EINVAL;
1514
1515         do {
1516                 spin_lock(&lr->wait.lock);
1517                 if (kfifo_is_empty(&lr->events)) {
1518                         if (bytes_read) {
1519                                 spin_unlock(&lr->wait.lock);
1520                                 return bytes_read;
1521                         }
1522
1523                         if (file->f_flags & O_NONBLOCK) {
1524                                 spin_unlock(&lr->wait.lock);
1525                                 return -EAGAIN;
1526                         }
1527
1528                         ret = wait_event_interruptible_locked(lr->wait,
1529                                         !kfifo_is_empty(&lr->events));
1530                         if (ret) {
1531                                 spin_unlock(&lr->wait.lock);
1532                                 return ret;
1533                         }
1534                 }
1535
1536                 ret = kfifo_out(&lr->events, &le, 1);
1537                 spin_unlock(&lr->wait.lock);
1538                 if (ret != 1) {
1539                         /*
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.
1543                          */
1544                         ret = -EIO;
1545                         break;
1546                 }
1547
1548                 if (copy_to_user(buf + bytes_read, &le, sizeof(le)))
1549                         return -EFAULT;
1550                 bytes_read += sizeof(le);
1551         } while (count >= bytes_read + sizeof(le));
1552
1553         return bytes_read;
1554 }
1555
1556 static ssize_t linereq_read(struct file *file, char __user *buf,
1557                             size_t count, loff_t *f_ps)
1558 {
1559         struct linereq *lr = file->private_data;
1560
1561         return call_read_locked(file, buf, count, f_ps, lr->gdev,
1562                                 linereq_read_unlocked);
1563 }
1564
1565 static void linereq_free(struct linereq *lr)
1566 {
1567         unsigned int i;
1568
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);
1573                 }
1574         }
1575         kfifo_free(&lr->events);
1576         kfree(lr->label);
1577         put_device(&lr->gdev->dev);
1578         kfree(lr);
1579 }
1580
1581 static int linereq_release(struct inode *inode, struct file *file)
1582 {
1583         struct linereq *lr = file->private_data;
1584
1585         linereq_free(lr);
1586         return 0;
1587 }
1588
1589 #ifdef CONFIG_PROC_FS
1590 static void linereq_show_fdinfo(struct seq_file *out, struct file *file)
1591 {
1592         struct linereq *lr = file->private_data;
1593         struct device *dev = &lr->gdev->dev;
1594         u16 i;
1595
1596         seq_printf(out, "gpio-chip:\t%s\n", dev_name(dev));
1597
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));
1601 }
1602 #endif
1603
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,
1613 #endif
1614 #ifdef CONFIG_PROC_FS
1615         .show_fdinfo = linereq_show_fdinfo,
1616 #endif
1617 };
1618
1619 static int linereq_create(struct gpio_device *gdev, void __user *ip)
1620 {
1621         struct gpio_v2_line_request ulr;
1622         struct gpio_v2_line_config *lc;
1623         struct linereq *lr;
1624         struct file *file;
1625         u64 flags, edflags;
1626         unsigned int i;
1627         int fd, ret;
1628
1629         if (copy_from_user(&ulr, ip, sizeof(ulr)))
1630                 return -EFAULT;
1631
1632         if ((ulr.num_lines == 0) || (ulr.num_lines > GPIO_V2_LINES_MAX))
1633                 return -EINVAL;
1634
1635         if (memchr_inv(ulr.padding, 0, sizeof(ulr.padding)))
1636                 return -EINVAL;
1637
1638         lc = &ulr.config;
1639         ret = gpio_v2_line_config_validate(lc, ulr.num_lines);
1640         if (ret)
1641                 return ret;
1642
1643         lr = kzalloc(struct_size(lr, lines, ulr.num_lines), GFP_KERNEL);
1644         if (!lr)
1645                 return -ENOMEM;
1646
1647         lr->gdev = gdev;
1648         get_device(&gdev->dev);
1649
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);
1654         }
1655
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,
1659                                      GFP_KERNEL);
1660                 if (!lr->label) {
1661                         ret = -ENOMEM;
1662                         goto out_free_linereq;
1663                 }
1664         }
1665
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;
1673
1674         atomic_set(&lr->seqno, 0);
1675         lr->num_lines = ulr.num_lines;
1676
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);
1681
1682                 if (IS_ERR(desc)) {
1683                         ret = PTR_ERR(desc);
1684                         goto out_free_linereq;
1685                 }
1686
1687                 ret = gpiod_request_user(desc, lr->label);
1688                 if (ret)
1689                         goto out_free_linereq;
1690
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);
1694
1695                 ret = gpiod_set_transitory(desc, false);
1696                 if (ret < 0)
1697                         goto out_free_linereq;
1698
1699                 edflags = flags & GPIO_V2_LINE_EDGE_DETECTOR_FLAGS;
1700                 /*
1701                  * Lines have to be requested explicitly for input
1702                  * or output, else the line will be treated "as is".
1703                  */
1704                 if (flags & GPIO_V2_LINE_FLAG_OUTPUT) {
1705                         int val = gpio_v2_line_config_output_value(lc, i);
1706
1707                         ret = gpiod_direction_output(desc, val);
1708                         if (ret)
1709                                 goto out_free_linereq;
1710                 } else if (flags & GPIO_V2_LINE_FLAG_INPUT) {
1711                         ret = gpiod_direction_input(desc);
1712                         if (ret)
1713                                 goto out_free_linereq;
1714
1715                         ret = edge_detector_setup(&lr->lines[i], lc, i,
1716                                                   edflags);
1717                         if (ret)
1718                                 goto out_free_linereq;
1719                 }
1720
1721                 lr->lines[i].edflags = edflags;
1722
1723                 blocking_notifier_call_chain(&desc->gdev->notifier,
1724                                              GPIO_V2_LINE_CHANGED_REQUESTED, desc);
1725
1726                 dev_dbg(&gdev->dev, "registered chardev handle for line %d\n",
1727                         offset);
1728         }
1729
1730         fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
1731         if (fd < 0) {
1732                 ret = fd;
1733                 goto out_free_linereq;
1734         }
1735
1736         file = anon_inode_getfile("gpio-line", &line_fileops, lr,
1737                                   O_RDONLY | O_CLOEXEC);
1738         if (IS_ERR(file)) {
1739                 ret = PTR_ERR(file);
1740                 goto out_put_unused_fd;
1741         }
1742
1743         ulr.fd = fd;
1744         if (copy_to_user(ip, &ulr, sizeof(ulr))) {
1745                 /*
1746                  * fput() will trigger the release() callback, so do not go onto
1747                  * the regular error cleanup path here.
1748                  */
1749                 fput(file);
1750                 put_unused_fd(fd);
1751                 return -EFAULT;
1752         }
1753
1754         fd_install(fd, file);
1755
1756         dev_dbg(&gdev->dev, "registered chardev handle for %d lines\n",
1757                 lr->num_lines);
1758
1759         return 0;
1760
1761 out_put_unused_fd:
1762         put_unused_fd(fd);
1763 out_free_linereq:
1764         linereq_free(lr);
1765         return ret;
1766 }
1767
1768 #ifdef CONFIG_GPIO_CDEV_V1
1769
1770 /*
1771  * GPIO line event management
1772  */
1773
1774 /**
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
1785  * event
1786  */
1787 struct lineevent_state {
1788         struct gpio_device *gdev;
1789         const char *label;
1790         struct gpio_desc *desc;
1791         u32 eflags;
1792         int irq;
1793         wait_queue_head_t wait;
1794         DECLARE_KFIFO(events, struct gpioevent_data, 16);
1795         u64 timestamp;
1796 };
1797
1798 #define GPIOEVENT_REQUEST_VALID_FLAGS \
1799         (GPIOEVENT_REQUEST_RISING_EDGE | \
1800         GPIOEVENT_REQUEST_FALLING_EDGE)
1801
1802 static __poll_t lineevent_poll_unlocked(struct file *file,
1803                                         struct poll_table_struct *wait)
1804 {
1805         struct lineevent_state *le = file->private_data;
1806         __poll_t events = 0;
1807
1808         if (!le->gdev->chip)
1809                 return EPOLLHUP | EPOLLERR;
1810
1811         poll_wait(file, &le->wait, wait);
1812
1813         if (!kfifo_is_empty_spinlocked_noirqsave(&le->events, &le->wait.lock))
1814                 events = EPOLLIN | EPOLLRDNORM;
1815
1816         return events;
1817 }
1818
1819 static __poll_t lineevent_poll(struct file *file,
1820                                struct poll_table_struct *wait)
1821 {
1822         struct lineevent_state *le = file->private_data;
1823
1824         return call_poll_locked(file, wait, le->gdev, lineevent_poll_unlocked);
1825 }
1826
1827 struct compat_gpioeevent_data {
1828         compat_u64      timestamp;
1829         u32             id;
1830 };
1831
1832 static ssize_t lineevent_read_unlocked(struct file *file, char __user *buf,
1833                                        size_t count, loff_t *f_ps)
1834 {
1835         struct lineevent_state *le = file->private_data;
1836         struct gpioevent_data ge;
1837         ssize_t bytes_read = 0;
1838         ssize_t ge_size;
1839         int ret;
1840
1841         if (!le->gdev->chip)
1842                 return -ENODEV;
1843
1844         /*
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.
1852          */
1853         if (compat_need_64bit_alignment_fixup())
1854                 ge_size = sizeof(struct compat_gpioeevent_data);
1855         else
1856                 ge_size = sizeof(struct gpioevent_data);
1857         if (count < ge_size)
1858                 return -EINVAL;
1859
1860         do {
1861                 spin_lock(&le->wait.lock);
1862                 if (kfifo_is_empty(&le->events)) {
1863                         if (bytes_read) {
1864                                 spin_unlock(&le->wait.lock);
1865                                 return bytes_read;
1866                         }
1867
1868                         if (file->f_flags & O_NONBLOCK) {
1869                                 spin_unlock(&le->wait.lock);
1870                                 return -EAGAIN;
1871                         }
1872
1873                         ret = wait_event_interruptible_locked(le->wait,
1874                                         !kfifo_is_empty(&le->events));
1875                         if (ret) {
1876                                 spin_unlock(&le->wait.lock);
1877                                 return ret;
1878                         }
1879                 }
1880
1881                 ret = kfifo_out(&le->events, &ge, 1);
1882                 spin_unlock(&le->wait.lock);
1883                 if (ret != 1) {
1884                         /*
1885                          * This should never happen - we were holding the lock
1886                          * from the moment we learned the fifo is no longer
1887                          * empty until now.
1888                          */
1889                         ret = -EIO;
1890                         break;
1891                 }
1892
1893                 if (copy_to_user(buf + bytes_read, &ge, ge_size))
1894                         return -EFAULT;
1895                 bytes_read += ge_size;
1896         } while (count >= bytes_read + ge_size);
1897
1898         return bytes_read;
1899 }
1900
1901 static ssize_t lineevent_read(struct file *file, char __user *buf,
1902                               size_t count, loff_t *f_ps)
1903 {
1904         struct lineevent_state *le = file->private_data;
1905
1906         return call_read_locked(file, buf, count, f_ps, le->gdev,
1907                                 lineevent_read_unlocked);
1908 }
1909
1910 static void lineevent_free(struct lineevent_state *le)
1911 {
1912         if (le->irq)
1913                 free_irq(le->irq, le);
1914         if (le->desc)
1915                 gpiod_free(le->desc);
1916         kfree(le->label);
1917         put_device(&le->gdev->dev);
1918         kfree(le);
1919 }
1920
1921 static int lineevent_release(struct inode *inode, struct file *file)
1922 {
1923         lineevent_free(file->private_data);
1924         return 0;
1925 }
1926
1927 static long lineevent_ioctl_unlocked(struct file *file, unsigned int cmd,
1928                                      unsigned long arg)
1929 {
1930         struct lineevent_state *le = file->private_data;
1931         void __user *ip = (void __user *)arg;
1932         struct gpiohandle_data ghd;
1933
1934         if (!le->gdev->chip)
1935                 return -ENODEV;
1936
1937         /*
1938          * We can get the value for an event line but not set it,
1939          * because it is input by definition.
1940          */
1941         if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
1942                 int val;
1943
1944                 memset(&ghd, 0, sizeof(ghd));
1945
1946                 val = gpiod_get_value_cansleep(le->desc);
1947                 if (val < 0)
1948                         return val;
1949                 ghd.values[0] = val;
1950
1951                 if (copy_to_user(ip, &ghd, sizeof(ghd)))
1952                         return -EFAULT;
1953
1954                 return 0;
1955         }
1956         return -EINVAL;
1957 }
1958
1959 static long lineevent_ioctl(struct file *file, unsigned int cmd,
1960                             unsigned long arg)
1961 {
1962         struct lineevent_state *le = file->private_data;
1963
1964         return call_ioctl_locked(file, cmd, arg, le->gdev,
1965                                  lineevent_ioctl_unlocked);
1966 }
1967
1968 #ifdef CONFIG_COMPAT
1969 static long lineevent_ioctl_compat(struct file *file, unsigned int cmd,
1970                                    unsigned long arg)
1971 {
1972         return lineevent_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
1973 }
1974 #endif
1975
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,
1985 #endif
1986 };
1987
1988 static irqreturn_t lineevent_irq_thread(int irq, void *p)
1989 {
1990         struct lineevent_state *le = p;
1991         struct gpioevent_data ge;
1992         int ret;
1993
1994         /* Do not leak kernel stack to userspace */
1995         memset(&ge, 0, sizeof(ge));
1996
1997         /*
1998          * We may be running from a nested threaded interrupt in which case
1999          * we didn't get the timestamp from lineevent_irq_handler().
2000          */
2001         if (!le->timestamp)
2002                 ge.timestamp = ktime_get_ns();
2003         else
2004                 ge.timestamp = le->timestamp;
2005
2006         if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE
2007             && le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
2008                 int level = gpiod_get_value_cansleep(le->desc);
2009
2010                 if (level)
2011                         /* Emit low-to-high event */
2012                         ge.id = GPIOEVENT_EVENT_RISING_EDGE;
2013                 else
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;
2022         } else {
2023                 return IRQ_NONE;
2024         }
2025
2026         ret = kfifo_in_spinlocked_noirqsave(&le->events, &ge,
2027                                             1, &le->wait.lock);
2028         if (ret)
2029                 wake_up_poll(&le->wait, EPOLLIN);
2030         else
2031                 pr_debug_ratelimited("event FIFO is full - event dropped\n");
2032
2033         return IRQ_HANDLED;
2034 }
2035
2036 static irqreturn_t lineevent_irq_handler(int irq, void *p)
2037 {
2038         struct lineevent_state *le = p;
2039
2040         /*
2041          * Just store the timestamp in hardirq context so we get it as
2042          * close in time as possible to the actual event.
2043          */
2044         le->timestamp = ktime_get_ns();
2045
2046         return IRQ_WAKE_THREAD;
2047 }
2048
2049 static int lineevent_create(struct gpio_device *gdev, void __user *ip)
2050 {
2051         struct gpioevent_request eventreq;
2052         struct lineevent_state *le;
2053         struct gpio_desc *desc;
2054         struct file *file;
2055         u32 offset;
2056         u32 lflags;
2057         u32 eflags;
2058         int fd;
2059         int ret;
2060         int irq, irqflags = 0;
2061
2062         if (copy_from_user(&eventreq, ip, sizeof(eventreq)))
2063                 return -EFAULT;
2064
2065         offset = eventreq.lineoffset;
2066         lflags = eventreq.handleflags;
2067         eflags = eventreq.eventflags;
2068
2069         desc = gpiochip_get_desc(gdev->chip, offset);
2070         if (IS_ERR(desc))
2071                 return PTR_ERR(desc);
2072
2073         /* Return an error if a unknown flag is set */
2074         if ((lflags & ~GPIOHANDLE_REQUEST_VALID_FLAGS) ||
2075             (eflags & ~GPIOEVENT_REQUEST_VALID_FLAGS))
2076                 return -EINVAL;
2077
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))
2082                 return -EINVAL;
2083
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)))
2090                 return -EINVAL;
2091
2092         le = kzalloc(sizeof(*le), GFP_KERNEL);
2093         if (!le)
2094                 return -ENOMEM;
2095         le->gdev = gdev;
2096         get_device(&gdev->dev);
2097
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,
2102                                      GFP_KERNEL);
2103                 if (!le->label) {
2104                         ret = -ENOMEM;
2105                         goto out_free_le;
2106                 }
2107         }
2108
2109         ret = gpiod_request_user(desc, le->label);
2110         if (ret)
2111                 goto out_free_le;
2112         le->desc = desc;
2113         le->eflags = eflags;
2114
2115         linehandle_flags_to_desc_flags(lflags, &desc->flags);
2116
2117         ret = gpiod_direction_input(desc);
2118         if (ret)
2119                 goto out_free_le;
2120
2121         blocking_notifier_call_chain(&desc->gdev->notifier,
2122                                      GPIO_V2_LINE_CHANGED_REQUESTED, desc);
2123
2124         irq = gpiod_to_irq(desc);
2125         if (irq <= 0) {
2126                 ret = -ENODEV;
2127                 goto out_free_le;
2128         }
2129
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;
2137
2138         INIT_KFIFO(le->events);
2139         init_waitqueue_head(&le->wait);
2140
2141         /* Request a thread to read the events */
2142         ret = request_threaded_irq(irq,
2143                                    lineevent_irq_handler,
2144                                    lineevent_irq_thread,
2145                                    irqflags,
2146                                    le->label,
2147                                    le);
2148         if (ret)
2149                 goto out_free_le;
2150
2151         le->irq = irq;
2152
2153         fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
2154         if (fd < 0) {
2155                 ret = fd;
2156                 goto out_free_le;
2157         }
2158
2159         file = anon_inode_getfile("gpio-event",
2160                                   &lineevent_fileops,
2161                                   le,
2162                                   O_RDONLY | O_CLOEXEC);
2163         if (IS_ERR(file)) {
2164                 ret = PTR_ERR(file);
2165                 goto out_put_unused_fd;
2166         }
2167
2168         eventreq.fd = fd;
2169         if (copy_to_user(ip, &eventreq, sizeof(eventreq))) {
2170                 /*
2171                  * fput() will trigger the release() callback, so do not go onto
2172                  * the regular error cleanup path here.
2173                  */
2174                 fput(file);
2175                 put_unused_fd(fd);
2176                 return -EFAULT;
2177         }
2178
2179         fd_install(fd, file);
2180
2181         return 0;
2182
2183 out_put_unused_fd:
2184         put_unused_fd(fd);
2185 out_free_le:
2186         lineevent_free(le);
2187         return ret;
2188 }
2189
2190 static void gpio_v2_line_info_to_v1(struct gpio_v2_line_info *info_v2,
2191                                     struct gpioline_info *info_v1)
2192 {
2193         u64 flagsv2 = info_v2->flags;
2194
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;
2198         info_v1->flags = 0;
2199
2200         if (flagsv2 & GPIO_V2_LINE_FLAG_USED)
2201                 info_v1->flags |= GPIOLINE_FLAG_KERNEL;
2202
2203         if (flagsv2 & GPIO_V2_LINE_FLAG_OUTPUT)
2204                 info_v1->flags |= GPIOLINE_FLAG_IS_OUT;
2205
2206         if (flagsv2 & GPIO_V2_LINE_FLAG_ACTIVE_LOW)
2207                 info_v1->flags |= GPIOLINE_FLAG_ACTIVE_LOW;
2208
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;
2213
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;
2220 }
2221
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)
2225 {
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;
2230 }
2231
2232 #endif /* CONFIG_GPIO_CDEV_V1 */
2233
2234 static void gpio_desc_to_lineinfo(struct gpio_desc *desc,
2235                                   struct gpio_v2_line_info *info)
2236 {
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;
2242
2243         memset(info, 0, sizeof(*info));
2244         info->offset = gpio_chip_hwgpio(desc);
2245
2246         /*
2247          * This function takes a mutex so we must check this before taking
2248          * the spinlock.
2249          *
2250          * FIXME: find a non-racy way to retrieve this information. Maybe a
2251          * lock common to both frameworks?
2252          */
2253         ok_for_pinctrl =
2254                 pinctrl_gpio_can_use_line(gc->base + info->offset);
2255
2256         spin_lock_irqsave(&gpio_lock, flags);
2257
2258         if (desc->name)
2259                 strscpy(info->name, desc->name, sizeof(info->name));
2260
2261         if (desc->label)
2262                 strscpy(info->consumer, desc->label, sizeof(info->consumer));
2263
2264         /*
2265          * Userspace only need to know that the kernel is using this GPIO so
2266          * it can't use it.
2267          */
2268         info->flags = 0;
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) ||
2275             !ok_for_pinctrl)
2276                 info->flags |= GPIO_V2_LINE_FLAG_USED;
2277
2278         if (test_bit(FLAG_IS_OUT, &desc->flags))
2279                 info->flags |= GPIO_V2_LINE_FLAG_OUTPUT;
2280         else
2281                 info->flags |= GPIO_V2_LINE_FLAG_INPUT;
2282
2283         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2284                 info->flags |= GPIO_V2_LINE_FLAG_ACTIVE_LOW;
2285
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;
2290
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;
2297
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;
2302
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;
2307
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;
2312                 num_attrs++;
2313         }
2314         info->num_attrs = num_attrs;
2315
2316         spin_unlock_irqrestore(&gpio_lock, flags);
2317 }
2318
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;
2327 #endif
2328 };
2329
2330 static int chipinfo_get(struct gpio_chardev_data *cdev, void __user *ip)
2331 {
2332         struct gpio_device *gdev = cdev->gdev;
2333         struct gpiochip_info chipinfo;
2334
2335         memset(&chipinfo, 0, sizeof(chipinfo));
2336
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)))
2341                 return -EFAULT;
2342         return 0;
2343 }
2344
2345 #ifdef CONFIG_GPIO_CDEV_V1
2346 /*
2347  * returns 0 if the versions match, else the previously selected ABI version
2348  */
2349 static int lineinfo_ensure_abi_version(struct gpio_chardev_data *cdata,
2350                                        unsigned int version)
2351 {
2352         int abiv = atomic_cmpxchg(&cdata->watch_abi_version, 0, version);
2353
2354         if (abiv == version)
2355                 return 0;
2356
2357         return abiv;
2358 }
2359
2360 static int lineinfo_get_v1(struct gpio_chardev_data *cdev, void __user *ip,
2361                            bool watch)
2362 {
2363         struct gpio_desc *desc;
2364         struct gpioline_info lineinfo;
2365         struct gpio_v2_line_info lineinfo_v2;
2366
2367         if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
2368                 return -EFAULT;
2369
2370         /* this doubles as a range check on line_offset */
2371         desc = gpiochip_get_desc(cdev->gdev->chip, lineinfo.line_offset);
2372         if (IS_ERR(desc))
2373                 return PTR_ERR(desc);
2374
2375         if (watch) {
2376                 if (lineinfo_ensure_abi_version(cdev, 1))
2377                         return -EPERM;
2378
2379                 if (test_and_set_bit(lineinfo.line_offset, cdev->watched_lines))
2380                         return -EBUSY;
2381         }
2382
2383         gpio_desc_to_lineinfo(desc, &lineinfo_v2);
2384         gpio_v2_line_info_to_v1(&lineinfo_v2, &lineinfo);
2385
2386         if (copy_to_user(ip, &lineinfo, sizeof(lineinfo))) {
2387                 if (watch)
2388                         clear_bit(lineinfo.line_offset, cdev->watched_lines);
2389                 return -EFAULT;
2390         }
2391
2392         return 0;
2393 }
2394 #endif
2395
2396 static int lineinfo_get(struct gpio_chardev_data *cdev, void __user *ip,
2397                         bool watch)
2398 {
2399         struct gpio_desc *desc;
2400         struct gpio_v2_line_info lineinfo;
2401
2402         if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
2403                 return -EFAULT;
2404
2405         if (memchr_inv(lineinfo.padding, 0, sizeof(lineinfo.padding)))
2406                 return -EINVAL;
2407
2408         desc = gpiochip_get_desc(cdev->gdev->chip, lineinfo.offset);
2409         if (IS_ERR(desc))
2410                 return PTR_ERR(desc);
2411
2412         if (watch) {
2413 #ifdef CONFIG_GPIO_CDEV_V1
2414                 if (lineinfo_ensure_abi_version(cdev, 2))
2415                         return -EPERM;
2416 #endif
2417                 if (test_and_set_bit(lineinfo.offset, cdev->watched_lines))
2418                         return -EBUSY;
2419         }
2420         gpio_desc_to_lineinfo(desc, &lineinfo);
2421
2422         if (copy_to_user(ip, &lineinfo, sizeof(lineinfo))) {
2423                 if (watch)
2424                         clear_bit(lineinfo.offset, cdev->watched_lines);
2425                 return -EFAULT;
2426         }
2427
2428         return 0;
2429 }
2430
2431 static int lineinfo_unwatch(struct gpio_chardev_data *cdev, void __user *ip)
2432 {
2433         __u32 offset;
2434
2435         if (copy_from_user(&offset, ip, sizeof(offset)))
2436                 return -EFAULT;
2437
2438         if (offset >= cdev->gdev->ngpio)
2439                 return -EINVAL;
2440
2441         if (!test_and_clear_bit(offset, cdev->watched_lines))
2442                 return -EBUSY;
2443
2444         return 0;
2445 }
2446
2447 /*
2448  * gpio_ioctl() - ioctl handler for the GPIO chardev
2449  */
2450 static long gpio_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
2451 {
2452         struct gpio_chardev_data *cdev = file->private_data;
2453         struct gpio_device *gdev = cdev->gdev;
2454         void __user *ip = (void __user *)arg;
2455
2456         /* We fail any subsequent ioctl():s when the chip is gone */
2457         if (!gdev->chip)
2458                 return -ENODEV;
2459
2460         /* Fill in the struct and pass to userspace */
2461         switch (cmd) {
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);
2482         default:
2483                 return -EINVAL;
2484         }
2485 }
2486
2487 #ifdef CONFIG_COMPAT
2488 static long gpio_ioctl_compat(struct file *file, unsigned int cmd,
2489                               unsigned long arg)
2490 {
2491         return gpio_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
2492 }
2493 #endif
2494
2495 static struct gpio_chardev_data *
2496 to_gpio_chardev_data(struct notifier_block *nb)
2497 {
2498         return container_of(nb, struct gpio_chardev_data, lineinfo_changed_nb);
2499 }
2500
2501 static int lineinfo_changed_notify(struct notifier_block *nb,
2502                                    unsigned long action, void *data)
2503 {
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;
2507         int ret;
2508
2509         if (!test_bit(gpio_chip_hwgpio(desc), cdev->watched_lines))
2510                 return NOTIFY_DONE;
2511
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);
2516
2517         ret = kfifo_in_spinlocked(&cdev->events, &chg, 1, &cdev->wait.lock);
2518         if (ret)
2519                 wake_up_poll(&cdev->wait, EPOLLIN);
2520         else
2521                 pr_debug_ratelimited("lineinfo event FIFO is full - event dropped\n");
2522
2523         return NOTIFY_OK;
2524 }
2525
2526 static __poll_t lineinfo_watch_poll_unlocked(struct file *file,
2527                                              struct poll_table_struct *pollt)
2528 {
2529         struct gpio_chardev_data *cdev = file->private_data;
2530         __poll_t events = 0;
2531
2532         if (!cdev->gdev->chip)
2533                 return EPOLLHUP | EPOLLERR;
2534
2535         poll_wait(file, &cdev->wait, pollt);
2536
2537         if (!kfifo_is_empty_spinlocked_noirqsave(&cdev->events,
2538                                                  &cdev->wait.lock))
2539                 events = EPOLLIN | EPOLLRDNORM;
2540
2541         return events;
2542 }
2543
2544 static __poll_t lineinfo_watch_poll(struct file *file,
2545                                     struct poll_table_struct *pollt)
2546 {
2547         struct gpio_chardev_data *cdev = file->private_data;
2548
2549         return call_poll_locked(file, pollt, cdev->gdev,
2550                                 lineinfo_watch_poll_unlocked);
2551 }
2552
2553 static ssize_t lineinfo_watch_read_unlocked(struct file *file, char __user *buf,
2554                                             size_t count, loff_t *off)
2555 {
2556         struct gpio_chardev_data *cdev = file->private_data;
2557         struct gpio_v2_line_info_changed event;
2558         ssize_t bytes_read = 0;
2559         int ret;
2560         size_t event_size;
2561
2562         if (!cdev->gdev->chip)
2563                 return -ENODEV;
2564
2565 #ifndef CONFIG_GPIO_CDEV_V1
2566         event_size = sizeof(struct gpio_v2_line_info_changed);
2567         if (count < event_size)
2568                 return -EINVAL;
2569 #endif
2570
2571         do {
2572                 spin_lock(&cdev->wait.lock);
2573                 if (kfifo_is_empty(&cdev->events)) {
2574                         if (bytes_read) {
2575                                 spin_unlock(&cdev->wait.lock);
2576                                 return bytes_read;
2577                         }
2578
2579                         if (file->f_flags & O_NONBLOCK) {
2580                                 spin_unlock(&cdev->wait.lock);
2581                                 return -EAGAIN;
2582                         }
2583
2584                         ret = wait_event_interruptible_locked(cdev->wait,
2585                                         !kfifo_is_empty(&cdev->events));
2586                         if (ret) {
2587                                 spin_unlock(&cdev->wait.lock);
2588                                 return ret;
2589                         }
2590                 }
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);
2595                 else
2596                         event_size = sizeof(struct gpioline_info_changed);
2597                 if (count < event_size) {
2598                         spin_unlock(&cdev->wait.lock);
2599                         return -EINVAL;
2600                 }
2601 #endif
2602                 ret = kfifo_out(&cdev->events, &event, 1);
2603                 spin_unlock(&cdev->wait.lock);
2604                 if (ret != 1) {
2605                         ret = -EIO;
2606                         break;
2607                         /* We should never get here. See lineevent_read(). */
2608                 }
2609
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))
2613                                 return -EFAULT;
2614                 } else {
2615                         struct gpioline_info_changed event_v1;
2616
2617                         gpio_v2_line_info_changed_to_v1(&event, &event_v1);
2618                         if (copy_to_user(buf + bytes_read, &event_v1,
2619                                          event_size))
2620                                 return -EFAULT;
2621                 }
2622 #else
2623                 if (copy_to_user(buf + bytes_read, &event, event_size))
2624                         return -EFAULT;
2625 #endif
2626                 bytes_read += event_size;
2627         } while (count >= bytes_read + sizeof(event));
2628
2629         return bytes_read;
2630 }
2631
2632 static ssize_t lineinfo_watch_read(struct file *file, char __user *buf,
2633                                    size_t count, loff_t *off)
2634 {
2635         struct gpio_chardev_data *cdev = file->private_data;
2636
2637         return call_read_locked(file, buf, count, off, cdev->gdev,
2638                                 lineinfo_watch_read_unlocked);
2639 }
2640
2641 /**
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
2646  */
2647 static int gpio_chrdev_open(struct inode *inode, struct file *file)
2648 {
2649         struct gpio_device *gdev = container_of(inode->i_cdev,
2650                                                 struct gpio_device, chrdev);
2651         struct gpio_chardev_data *cdev;
2652         int ret = -ENOMEM;
2653
2654         down_read(&gdev->sem);
2655
2656         /* Fail on open if the backing gpiochip is gone */
2657         if (!gdev->chip) {
2658                 ret = -ENODEV;
2659                 goto out_unlock;
2660         }
2661
2662         cdev = kzalloc(sizeof(*cdev), GFP_KERNEL);
2663         if (!cdev)
2664                 goto out_unlock;
2665
2666         cdev->watched_lines = bitmap_zalloc(gdev->chip->ngpio, GFP_KERNEL);
2667         if (!cdev->watched_lines)
2668                 goto out_free_cdev;
2669
2670         init_waitqueue_head(&cdev->wait);
2671         INIT_KFIFO(cdev->events);
2672         cdev->gdev = gdev;
2673
2674         cdev->lineinfo_changed_nb.notifier_call = lineinfo_changed_notify;
2675         ret = blocking_notifier_chain_register(&gdev->notifier,
2676                                                &cdev->lineinfo_changed_nb);
2677         if (ret)
2678                 goto out_free_bitmap;
2679
2680         get_device(&gdev->dev);
2681         file->private_data = cdev;
2682
2683         ret = nonseekable_open(inode, file);
2684         if (ret)
2685                 goto out_unregister_notifier;
2686
2687         up_read(&gdev->sem);
2688
2689         return ret;
2690
2691 out_unregister_notifier:
2692         blocking_notifier_chain_unregister(&gdev->notifier,
2693                                            &cdev->lineinfo_changed_nb);
2694 out_free_bitmap:
2695         bitmap_free(cdev->watched_lines);
2696 out_free_cdev:
2697         kfree(cdev);
2698 out_unlock:
2699         up_read(&gdev->sem);
2700         return ret;
2701 }
2702
2703 /**
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
2708  */
2709 static int gpio_chrdev_release(struct inode *inode, struct file *file)
2710 {
2711         struct gpio_chardev_data *cdev = file->private_data;
2712         struct gpio_device *gdev = cdev->gdev;
2713
2714         bitmap_free(cdev->watched_lines);
2715         blocking_notifier_chain_unregister(&gdev->notifier,
2716                                            &cdev->lineinfo_changed_nb);
2717         put_device(&gdev->dev);
2718         kfree(cdev);
2719
2720         return 0;
2721 }
2722
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,
2733 #endif
2734 };
2735
2736 int gpiolib_cdev_register(struct gpio_device *gdev, dev_t devt)
2737 {
2738         int ret;
2739
2740         cdev_init(&gdev->chrdev, &gpio_fileops);
2741         gdev->chrdev.owner = THIS_MODULE;
2742         gdev->dev.devt = MKDEV(MAJOR(devt), gdev->id);
2743
2744         ret = cdev_device_add(&gdev->chrdev, &gdev->dev);
2745         if (ret)
2746                 return ret;
2747
2748         chip_dbg(gdev->chip, "added GPIO chardev (%d:%d)\n",
2749                  MAJOR(devt), gdev->id);
2750
2751         return 0;
2752 }
2753
2754 void gpiolib_cdev_unregister(struct gpio_device *gdev)
2755 {
2756         cdev_device_del(&gdev->chrdev, &gdev->dev);
2757 }