ACPI: processor idle: Practically limit "Dummy wait" workaround to old Intel systems
[platform/kernel/linux-rpi.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 <uapi/linux/gpio.h>
28
29 #include "gpiolib.h"
30 #include "gpiolib-cdev.h"
31
32 /*
33  * Array sizes must ensure 64-bit alignment and not create holes in the
34  * struct packing.
35  */
36 static_assert(IS_ALIGNED(GPIO_V2_LINES_MAX, 2));
37 static_assert(IS_ALIGNED(GPIO_MAX_NAME_SIZE, 8));
38
39 /*
40  * Check that uAPI structs are 64-bit aligned for 32/64-bit compatibility
41  */
42 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_attribute), 8));
43 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_config_attribute), 8));
44 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_config), 8));
45 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_request), 8));
46 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_info), 8));
47 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_info_changed), 8));
48 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_event), 8));
49 static_assert(IS_ALIGNED(sizeof(struct gpio_v2_line_values), 8));
50
51 /* Character device interface to GPIO.
52  *
53  * The GPIO character device, /dev/gpiochipN, provides userspace an
54  * interface to gpiolib GPIOs via ioctl()s.
55  */
56
57 typedef __poll_t (*poll_fn)(struct file *, struct poll_table_struct *);
58 typedef long (*ioctl_fn)(struct file *, unsigned int, unsigned long);
59 typedef ssize_t (*read_fn)(struct file *, char __user *,
60                            size_t count, loff_t *);
61
62 static __poll_t call_poll_locked(struct file *file,
63                                  struct poll_table_struct *wait,
64                                  struct gpio_device *gdev, poll_fn func)
65 {
66         __poll_t ret;
67
68         down_read(&gdev->sem);
69         ret = func(file, wait);
70         up_read(&gdev->sem);
71
72         return ret;
73 }
74
75 static long call_ioctl_locked(struct file *file, unsigned int cmd,
76                               unsigned long arg, struct gpio_device *gdev,
77                               ioctl_fn func)
78 {
79         long ret;
80
81         down_read(&gdev->sem);
82         ret = func(file, cmd, arg);
83         up_read(&gdev->sem);
84
85         return ret;
86 }
87
88 static ssize_t call_read_locked(struct file *file, char __user *buf,
89                                 size_t count, loff_t *f_ps,
90                                 struct gpio_device *gdev, read_fn func)
91 {
92         ssize_t ret;
93
94         down_read(&gdev->sem);
95         ret = func(file, buf, count, f_ps);
96         up_read(&gdev->sem);
97
98         return ret;
99 }
100
101 /*
102  * GPIO line handle management
103  */
104
105 #ifdef CONFIG_GPIO_CDEV_V1
106 /**
107  * struct linehandle_state - contains the state of a userspace handle
108  * @gdev: the GPIO device the handle pertains to
109  * @label: consumer label used to tag descriptors
110  * @descs: the GPIO descriptors held by this handle
111  * @num_descs: the number of descriptors held in the descs array
112  */
113 struct linehandle_state {
114         struct gpio_device *gdev;
115         const char *label;
116         struct gpio_desc *descs[GPIOHANDLES_MAX];
117         u32 num_descs;
118 };
119
120 #define GPIOHANDLE_REQUEST_VALID_FLAGS \
121         (GPIOHANDLE_REQUEST_INPUT | \
122         GPIOHANDLE_REQUEST_OUTPUT | \
123         GPIOHANDLE_REQUEST_ACTIVE_LOW | \
124         GPIOHANDLE_REQUEST_BIAS_PULL_UP | \
125         GPIOHANDLE_REQUEST_BIAS_PULL_DOWN | \
126         GPIOHANDLE_REQUEST_BIAS_DISABLE | \
127         GPIOHANDLE_REQUEST_OPEN_DRAIN | \
128         GPIOHANDLE_REQUEST_OPEN_SOURCE)
129
130 static int linehandle_validate_flags(u32 flags)
131 {
132         /* Return an error if an unknown flag is set */
133         if (flags & ~GPIOHANDLE_REQUEST_VALID_FLAGS)
134                 return -EINVAL;
135
136         /*
137          * Do not allow both INPUT & OUTPUT flags to be set as they are
138          * contradictory.
139          */
140         if ((flags & GPIOHANDLE_REQUEST_INPUT) &&
141             (flags & GPIOHANDLE_REQUEST_OUTPUT))
142                 return -EINVAL;
143
144         /*
145          * Do not allow OPEN_SOURCE & OPEN_DRAIN flags in a single request. If
146          * the hardware actually supports enabling both at the same time the
147          * electrical result would be disastrous.
148          */
149         if ((flags & GPIOHANDLE_REQUEST_OPEN_DRAIN) &&
150             (flags & GPIOHANDLE_REQUEST_OPEN_SOURCE))
151                 return -EINVAL;
152
153         /* OPEN_DRAIN and OPEN_SOURCE flags only make sense for output mode. */
154         if (!(flags & GPIOHANDLE_REQUEST_OUTPUT) &&
155             ((flags & GPIOHANDLE_REQUEST_OPEN_DRAIN) ||
156              (flags & GPIOHANDLE_REQUEST_OPEN_SOURCE)))
157                 return -EINVAL;
158
159         /* Bias flags only allowed for input or output mode. */
160         if (!((flags & GPIOHANDLE_REQUEST_INPUT) ||
161               (flags & GPIOHANDLE_REQUEST_OUTPUT)) &&
162             ((flags & GPIOHANDLE_REQUEST_BIAS_DISABLE) ||
163              (flags & GPIOHANDLE_REQUEST_BIAS_PULL_UP) ||
164              (flags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN)))
165                 return -EINVAL;
166
167         /* Only one bias flag can be set. */
168         if (((flags & GPIOHANDLE_REQUEST_BIAS_DISABLE) &&
169              (flags & (GPIOHANDLE_REQUEST_BIAS_PULL_DOWN |
170                        GPIOHANDLE_REQUEST_BIAS_PULL_UP))) ||
171             ((flags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN) &&
172              (flags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)))
173                 return -EINVAL;
174
175         return 0;
176 }
177
178 static void linehandle_flags_to_desc_flags(u32 lflags, unsigned long *flagsp)
179 {
180         assign_bit(FLAG_ACTIVE_LOW, flagsp,
181                    lflags & GPIOHANDLE_REQUEST_ACTIVE_LOW);
182         assign_bit(FLAG_OPEN_DRAIN, flagsp,
183                    lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN);
184         assign_bit(FLAG_OPEN_SOURCE, flagsp,
185                    lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE);
186         assign_bit(FLAG_PULL_UP, flagsp,
187                    lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP);
188         assign_bit(FLAG_PULL_DOWN, flagsp,
189                    lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN);
190         assign_bit(FLAG_BIAS_DISABLE, flagsp,
191                    lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE);
192 }
193
194 static long linehandle_set_config(struct linehandle_state *lh,
195                                   void __user *ip)
196 {
197         struct gpiohandle_config gcnf;
198         struct gpio_desc *desc;
199         int i, ret;
200         u32 lflags;
201
202         if (copy_from_user(&gcnf, ip, sizeof(gcnf)))
203                 return -EFAULT;
204
205         lflags = gcnf.flags;
206         ret = linehandle_validate_flags(lflags);
207         if (ret)
208                 return ret;
209
210         for (i = 0; i < lh->num_descs; i++) {
211                 desc = lh->descs[i];
212                 linehandle_flags_to_desc_flags(gcnf.flags, &desc->flags);
213
214                 /*
215                  * Lines have to be requested explicitly for input
216                  * or output, else the line will be treated "as is".
217                  */
218                 if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
219                         int val = !!gcnf.default_values[i];
220
221                         ret = gpiod_direction_output(desc, val);
222                         if (ret)
223                                 return ret;
224                 } else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
225                         ret = gpiod_direction_input(desc);
226                         if (ret)
227                                 return ret;
228                 }
229
230                 blocking_notifier_call_chain(&desc->gdev->notifier,
231                                              GPIO_V2_LINE_CHANGED_CONFIG,
232                                              desc);
233         }
234         return 0;
235 }
236
237 static long linehandle_ioctl_unlocked(struct file *file, unsigned int cmd,
238                                       unsigned long arg)
239 {
240         struct linehandle_state *lh = file->private_data;
241         void __user *ip = (void __user *)arg;
242         struct gpiohandle_data ghd;
243         DECLARE_BITMAP(vals, GPIOHANDLES_MAX);
244         unsigned int i;
245         int ret;
246
247         if (!lh->gdev->chip)
248                 return -ENODEV;
249
250         switch (cmd) {
251         case GPIOHANDLE_GET_LINE_VALUES_IOCTL:
252                 /* NOTE: It's okay to read values of output lines */
253                 ret = gpiod_get_array_value_complex(false, true,
254                                                     lh->num_descs, lh->descs,
255                                                     NULL, vals);
256                 if (ret)
257                         return ret;
258
259                 memset(&ghd, 0, sizeof(ghd));
260                 for (i = 0; i < lh->num_descs; i++)
261                         ghd.values[i] = test_bit(i, vals);
262
263                 if (copy_to_user(ip, &ghd, sizeof(ghd)))
264                         return -EFAULT;
265
266                 return 0;
267         case GPIOHANDLE_SET_LINE_VALUES_IOCTL:
268                 /*
269                  * All line descriptors were created at once with the same
270                  * flags so just check if the first one is really output.
271                  */
272                 if (!test_bit(FLAG_IS_OUT, &lh->descs[0]->flags))
273                         return -EPERM;
274
275                 if (copy_from_user(&ghd, ip, sizeof(ghd)))
276                         return -EFAULT;
277
278                 /* Clamp all values to [0,1] */
279                 for (i = 0; i < lh->num_descs; i++)
280                         __assign_bit(i, vals, ghd.values[i]);
281
282                 /* Reuse the array setting function */
283                 return gpiod_set_array_value_complex(false,
284                                                      true,
285                                                      lh->num_descs,
286                                                      lh->descs,
287                                                      NULL,
288                                                      vals);
289         case GPIOHANDLE_SET_CONFIG_IOCTL:
290                 return linehandle_set_config(lh, ip);
291         default:
292                 return -EINVAL;
293         }
294 }
295
296 static long linehandle_ioctl(struct file *file, unsigned int cmd,
297                              unsigned long arg)
298 {
299         struct linehandle_state *lh = file->private_data;
300
301         return call_ioctl_locked(file, cmd, arg, lh->gdev,
302                                  linehandle_ioctl_unlocked);
303 }
304
305 #ifdef CONFIG_COMPAT
306 static long linehandle_ioctl_compat(struct file *file, unsigned int cmd,
307                                     unsigned long arg)
308 {
309         return linehandle_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
310 }
311 #endif
312
313 static void linehandle_free(struct linehandle_state *lh)
314 {
315         int i;
316
317         for (i = 0; i < lh->num_descs; i++)
318                 if (lh->descs[i])
319                         gpiod_free(lh->descs[i]);
320         kfree(lh->label);
321         put_device(&lh->gdev->dev);
322         kfree(lh);
323 }
324
325 static int linehandle_release(struct inode *inode, struct file *file)
326 {
327         linehandle_free(file->private_data);
328         return 0;
329 }
330
331 static const struct file_operations linehandle_fileops = {
332         .release = linehandle_release,
333         .owner = THIS_MODULE,
334         .llseek = noop_llseek,
335         .unlocked_ioctl = linehandle_ioctl,
336 #ifdef CONFIG_COMPAT
337         .compat_ioctl = linehandle_ioctl_compat,
338 #endif
339 };
340
341 static int linehandle_create(struct gpio_device *gdev, void __user *ip)
342 {
343         struct gpiohandle_request handlereq;
344         struct linehandle_state *lh;
345         struct file *file;
346         int fd, i, ret;
347         u32 lflags;
348
349         if (copy_from_user(&handlereq, ip, sizeof(handlereq)))
350                 return -EFAULT;
351         if ((handlereq.lines == 0) || (handlereq.lines > GPIOHANDLES_MAX))
352                 return -EINVAL;
353
354         lflags = handlereq.flags;
355
356         ret = linehandle_validate_flags(lflags);
357         if (ret)
358                 return ret;
359
360         lh = kzalloc(sizeof(*lh), GFP_KERNEL);
361         if (!lh)
362                 return -ENOMEM;
363         lh->gdev = gdev;
364         get_device(&gdev->dev);
365
366         if (handlereq.consumer_label[0] != '\0') {
367                 /* label is only initialized if consumer_label is set */
368                 lh->label = kstrndup(handlereq.consumer_label,
369                                      sizeof(handlereq.consumer_label) - 1,
370                                      GFP_KERNEL);
371                 if (!lh->label) {
372                         ret = -ENOMEM;
373                         goto out_free_lh;
374                 }
375         }
376
377         lh->num_descs = handlereq.lines;
378
379         /* Request each GPIO */
380         for (i = 0; i < handlereq.lines; i++) {
381                 u32 offset = handlereq.lineoffsets[i];
382                 struct gpio_desc *desc = gpiochip_get_desc(gdev->chip, offset);
383
384                 if (IS_ERR(desc)) {
385                         ret = PTR_ERR(desc);
386                         goto out_free_lh;
387                 }
388
389                 ret = gpiod_request_user(desc, lh->label);
390                 if (ret)
391                         goto out_free_lh;
392                 lh->descs[i] = desc;
393                 linehandle_flags_to_desc_flags(handlereq.flags, &desc->flags);
394
395                 ret = gpiod_set_transitory(desc, false);
396                 if (ret < 0)
397                         goto out_free_lh;
398
399                 /*
400                  * Lines have to be requested explicitly for input
401                  * or output, else the line will be treated "as is".
402                  */
403                 if (lflags & GPIOHANDLE_REQUEST_OUTPUT) {
404                         int val = !!handlereq.default_values[i];
405
406                         ret = gpiod_direction_output(desc, val);
407                         if (ret)
408                                 goto out_free_lh;
409                 } else if (lflags & GPIOHANDLE_REQUEST_INPUT) {
410                         ret = gpiod_direction_input(desc);
411                         if (ret)
412                                 goto out_free_lh;
413                 }
414
415                 blocking_notifier_call_chain(&desc->gdev->notifier,
416                                              GPIO_V2_LINE_CHANGED_REQUESTED, desc);
417
418                 dev_dbg(&gdev->dev, "registered chardev handle for line %d\n",
419                         offset);
420         }
421
422         fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
423         if (fd < 0) {
424                 ret = fd;
425                 goto out_free_lh;
426         }
427
428         file = anon_inode_getfile("gpio-linehandle",
429                                   &linehandle_fileops,
430                                   lh,
431                                   O_RDONLY | O_CLOEXEC);
432         if (IS_ERR(file)) {
433                 ret = PTR_ERR(file);
434                 goto out_put_unused_fd;
435         }
436
437         handlereq.fd = fd;
438         if (copy_to_user(ip, &handlereq, sizeof(handlereq))) {
439                 /*
440                  * fput() will trigger the release() callback, so do not go onto
441                  * the regular error cleanup path here.
442                  */
443                 fput(file);
444                 put_unused_fd(fd);
445                 return -EFAULT;
446         }
447
448         fd_install(fd, file);
449
450         dev_dbg(&gdev->dev, "registered chardev handle for %d lines\n",
451                 lh->num_descs);
452
453         return 0;
454
455 out_put_unused_fd:
456         put_unused_fd(fd);
457 out_free_lh:
458         linehandle_free(lh);
459         return ret;
460 }
461 #endif /* CONFIG_GPIO_CDEV_V1 */
462
463 /**
464  * struct line - contains the state of a requested line
465  * @desc: the GPIO descriptor for this line.
466  * @req: the corresponding line request
467  * @irq: the interrupt triggered in response to events on this GPIO
468  * @eflags: the edge flags, GPIO_V2_LINE_FLAG_EDGE_RISING and/or
469  * GPIO_V2_LINE_FLAG_EDGE_FALLING, indicating the edge detection applied
470  * @timestamp_ns: cache for the timestamp storing it between hardirq and
471  * IRQ thread, used to bring the timestamp close to the actual event
472  * @req_seqno: the seqno for the current edge event in the sequence of
473  * events for the corresponding line request. This is drawn from the @req.
474  * @line_seqno: the seqno for the current edge event in the sequence of
475  * events for this line.
476  * @work: the worker that implements software debouncing
477  * @sw_debounced: flag indicating if the software debouncer is active
478  * @level: the current debounced physical level of the line
479  */
480 struct line {
481         struct gpio_desc *desc;
482         /*
483          * -- edge detector specific fields --
484          */
485         struct linereq *req;
486         unsigned int irq;
487         /*
488          * eflags is set by edge_detector_setup(), edge_detector_stop() and
489          * edge_detector_update(), which are themselves mutually exclusive,
490          * and is accessed by edge_irq_thread() and debounce_work_func(),
491          * which can both live with a slightly stale value.
492          */
493         u64 eflags;
494         /*
495          * timestamp_ns and req_seqno are accessed only by
496          * edge_irq_handler() and edge_irq_thread(), which are themselves
497          * mutually exclusive, so no additional protection is necessary.
498          */
499         u64 timestamp_ns;
500         u32 req_seqno;
501         /*
502          * line_seqno is accessed by either edge_irq_thread() or
503          * debounce_work_func(), which are themselves mutually exclusive,
504          * so no additional protection is necessary.
505          */
506         u32 line_seqno;
507         /*
508          * -- debouncer specific fields --
509          */
510         struct delayed_work work;
511         /*
512          * sw_debounce is accessed by linereq_set_config(), which is the
513          * only setter, and linereq_get_values(), which can live with a
514          * slightly stale value.
515          */
516         unsigned int sw_debounced;
517         /*
518          * level is accessed by debounce_work_func(), which is the only
519          * setter, and linereq_get_values() which can live with a slightly
520          * stale value.
521          */
522         unsigned int level;
523 };
524
525 /**
526  * struct linereq - contains the state of a userspace line request
527  * @gdev: the GPIO device the line request pertains to
528  * @label: consumer label used to tag GPIO descriptors
529  * @num_lines: the number of lines in the lines array
530  * @wait: wait queue that handles blocking reads of events
531  * @event_buffer_size: the number of elements allocated in @events
532  * @events: KFIFO for the GPIO events
533  * @seqno: the sequence number for edge events generated on all lines in
534  * this line request.  Note that this is not used when @num_lines is 1, as
535  * the line_seqno is then the same and is cheaper to calculate.
536  * @config_mutex: mutex for serializing ioctl() calls to ensure consistency
537  * of configuration, particularly multi-step accesses to desc flags.
538  * @lines: the lines held by this line request, with @num_lines elements.
539  */
540 struct linereq {
541         struct gpio_device *gdev;
542         const char *label;
543         u32 num_lines;
544         wait_queue_head_t wait;
545         u32 event_buffer_size;
546         DECLARE_KFIFO_PTR(events, struct gpio_v2_line_event);
547         atomic_t seqno;
548         struct mutex config_mutex;
549         struct line lines[];
550 };
551
552 #define GPIO_V2_LINE_BIAS_FLAGS \
553         (GPIO_V2_LINE_FLAG_BIAS_PULL_UP | \
554          GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN | \
555          GPIO_V2_LINE_FLAG_BIAS_DISABLED)
556
557 #define GPIO_V2_LINE_DIRECTION_FLAGS \
558         (GPIO_V2_LINE_FLAG_INPUT | \
559          GPIO_V2_LINE_FLAG_OUTPUT)
560
561 #define GPIO_V2_LINE_DRIVE_FLAGS \
562         (GPIO_V2_LINE_FLAG_OPEN_DRAIN | \
563          GPIO_V2_LINE_FLAG_OPEN_SOURCE)
564
565 #define GPIO_V2_LINE_EDGE_FLAGS \
566         (GPIO_V2_LINE_FLAG_EDGE_RISING | \
567          GPIO_V2_LINE_FLAG_EDGE_FALLING)
568
569 #define GPIO_V2_LINE_FLAG_EDGE_BOTH GPIO_V2_LINE_EDGE_FLAGS
570
571 #define GPIO_V2_LINE_VALID_FLAGS \
572         (GPIO_V2_LINE_FLAG_ACTIVE_LOW | \
573          GPIO_V2_LINE_DIRECTION_FLAGS | \
574          GPIO_V2_LINE_DRIVE_FLAGS | \
575          GPIO_V2_LINE_EDGE_FLAGS | \
576          GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME | \
577          GPIO_V2_LINE_BIAS_FLAGS)
578
579 static void linereq_put_event(struct linereq *lr,
580                               struct gpio_v2_line_event *le)
581 {
582         bool overflow = false;
583
584         spin_lock(&lr->wait.lock);
585         if (kfifo_is_full(&lr->events)) {
586                 overflow = true;
587                 kfifo_skip(&lr->events);
588         }
589         kfifo_in(&lr->events, le, 1);
590         spin_unlock(&lr->wait.lock);
591         if (!overflow)
592                 wake_up_poll(&lr->wait, EPOLLIN);
593         else
594                 pr_debug_ratelimited("event FIFO is full - event dropped\n");
595 }
596
597 static u64 line_event_timestamp(struct line *line)
598 {
599         if (test_bit(FLAG_EVENT_CLOCK_REALTIME, &line->desc->flags))
600                 return ktime_get_real_ns();
601
602         return ktime_get_ns();
603 }
604
605 static irqreturn_t edge_irq_thread(int irq, void *p)
606 {
607         struct line *line = p;
608         struct linereq *lr = line->req;
609         struct gpio_v2_line_event le;
610         u64 eflags;
611
612         /* Do not leak kernel stack to userspace */
613         memset(&le, 0, sizeof(le));
614
615         if (line->timestamp_ns) {
616                 le.timestamp_ns = line->timestamp_ns;
617         } else {
618                 /*
619                  * We may be running from a nested threaded interrupt in
620                  * which case we didn't get the timestamp from
621                  * edge_irq_handler().
622                  */
623                 le.timestamp_ns = line_event_timestamp(line);
624                 if (lr->num_lines != 1)
625                         line->req_seqno = atomic_inc_return(&lr->seqno);
626         }
627         line->timestamp_ns = 0;
628
629         eflags = READ_ONCE(line->eflags);
630         if (eflags == GPIO_V2_LINE_FLAG_EDGE_BOTH) {
631                 int level = gpiod_get_value_cansleep(line->desc);
632
633                 if (level)
634                         /* Emit low-to-high event */
635                         le.id = GPIO_V2_LINE_EVENT_RISING_EDGE;
636                 else
637                         /* Emit high-to-low event */
638                         le.id = GPIO_V2_LINE_EVENT_FALLING_EDGE;
639         } else if (eflags == GPIO_V2_LINE_FLAG_EDGE_RISING) {
640                 /* Emit low-to-high event */
641                 le.id = GPIO_V2_LINE_EVENT_RISING_EDGE;
642         } else if (eflags == GPIO_V2_LINE_FLAG_EDGE_FALLING) {
643                 /* Emit high-to-low event */
644                 le.id = GPIO_V2_LINE_EVENT_FALLING_EDGE;
645         } else {
646                 return IRQ_NONE;
647         }
648         line->line_seqno++;
649         le.line_seqno = line->line_seqno;
650         le.seqno = (lr->num_lines == 1) ? le.line_seqno : line->req_seqno;
651         le.offset = gpio_chip_hwgpio(line->desc);
652
653         linereq_put_event(lr, &le);
654
655         return IRQ_HANDLED;
656 }
657
658 static irqreturn_t edge_irq_handler(int irq, void *p)
659 {
660         struct line *line = p;
661         struct linereq *lr = line->req;
662
663         /*
664          * Just store the timestamp in hardirq context so we get it as
665          * close in time as possible to the actual event.
666          */
667         line->timestamp_ns = line_event_timestamp(line);
668
669         if (lr->num_lines != 1)
670                 line->req_seqno = atomic_inc_return(&lr->seqno);
671
672         return IRQ_WAKE_THREAD;
673 }
674
675 /*
676  * returns the current debounced logical value.
677  */
678 static bool debounced_value(struct line *line)
679 {
680         bool value;
681
682         /*
683          * minor race - debouncer may be stopped here, so edge_detector_stop()
684          * must leave the value unchanged so the following will read the level
685          * from when the debouncer was last running.
686          */
687         value = READ_ONCE(line->level);
688
689         if (test_bit(FLAG_ACTIVE_LOW, &line->desc->flags))
690                 value = !value;
691
692         return value;
693 }
694
695 static irqreturn_t debounce_irq_handler(int irq, void *p)
696 {
697         struct line *line = p;
698
699         mod_delayed_work(system_wq, &line->work,
700                 usecs_to_jiffies(READ_ONCE(line->desc->debounce_period_us)));
701
702         return IRQ_HANDLED;
703 }
704
705 static void debounce_work_func(struct work_struct *work)
706 {
707         struct gpio_v2_line_event le;
708         struct line *line = container_of(work, struct line, work.work);
709         struct linereq *lr;
710         int level;
711         u64 eflags;
712
713         level = gpiod_get_raw_value_cansleep(line->desc);
714         if (level < 0) {
715                 pr_debug_ratelimited("debouncer failed to read line value\n");
716                 return;
717         }
718
719         if (READ_ONCE(line->level) == level)
720                 return;
721
722         WRITE_ONCE(line->level, level);
723
724         /* -- edge detection -- */
725         eflags = READ_ONCE(line->eflags);
726         if (!eflags)
727                 return;
728
729         /* switch from physical level to logical - if they differ */
730         if (test_bit(FLAG_ACTIVE_LOW, &line->desc->flags))
731                 level = !level;
732
733         /* ignore edges that are not being monitored */
734         if (((eflags == GPIO_V2_LINE_FLAG_EDGE_RISING) && !level) ||
735             ((eflags == GPIO_V2_LINE_FLAG_EDGE_FALLING) && level))
736                 return;
737
738         /* Do not leak kernel stack to userspace */
739         memset(&le, 0, sizeof(le));
740
741         lr = line->req;
742         le.timestamp_ns = line_event_timestamp(line);
743         le.offset = gpio_chip_hwgpio(line->desc);
744         line->line_seqno++;
745         le.line_seqno = line->line_seqno;
746         le.seqno = (lr->num_lines == 1) ?
747                 le.line_seqno : atomic_inc_return(&lr->seqno);
748
749         if (level)
750                 /* Emit low-to-high event */
751                 le.id = GPIO_V2_LINE_EVENT_RISING_EDGE;
752         else
753                 /* Emit high-to-low event */
754                 le.id = GPIO_V2_LINE_EVENT_FALLING_EDGE;
755
756         linereq_put_event(lr, &le);
757 }
758
759 static int debounce_setup(struct line *line,
760                           unsigned int debounce_period_us)
761 {
762         unsigned long irqflags;
763         int ret, level, irq;
764
765         /* try hardware */
766         ret = gpiod_set_debounce(line->desc, debounce_period_us);
767         if (!ret) {
768                 WRITE_ONCE(line->desc->debounce_period_us, debounce_period_us);
769                 return ret;
770         }
771         if (ret != -ENOTSUPP)
772                 return ret;
773
774         if (debounce_period_us) {
775                 /* setup software debounce */
776                 level = gpiod_get_raw_value_cansleep(line->desc);
777                 if (level < 0)
778                         return level;
779
780                 irq = gpiod_to_irq(line->desc);
781                 if (irq < 0)
782                         return -ENXIO;
783
784                 WRITE_ONCE(line->level, level);
785                 irqflags = IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING;
786                 ret = request_irq(irq, debounce_irq_handler, irqflags,
787                                   line->req->label, line);
788                 if (ret)
789                         return ret;
790
791                 WRITE_ONCE(line->sw_debounced, 1);
792                 line->irq = irq;
793         }
794         return 0;
795 }
796
797 static bool gpio_v2_line_config_debounced(struct gpio_v2_line_config *lc,
798                                           unsigned int line_idx)
799 {
800         unsigned int i;
801         u64 mask = BIT_ULL(line_idx);
802
803         for (i = 0; i < lc->num_attrs; i++) {
804                 if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_DEBOUNCE) &&
805                     (lc->attrs[i].mask & mask))
806                         return true;
807         }
808         return false;
809 }
810
811 static u32 gpio_v2_line_config_debounce_period(struct gpio_v2_line_config *lc,
812                                                unsigned int line_idx)
813 {
814         unsigned int i;
815         u64 mask = BIT_ULL(line_idx);
816
817         for (i = 0; i < lc->num_attrs; i++) {
818                 if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_DEBOUNCE) &&
819                     (lc->attrs[i].mask & mask))
820                         return lc->attrs[i].attr.debounce_period_us;
821         }
822         return 0;
823 }
824
825 static void edge_detector_stop(struct line *line)
826 {
827         if (line->irq) {
828                 free_irq(line->irq, line);
829                 line->irq = 0;
830         }
831
832         cancel_delayed_work_sync(&line->work);
833         WRITE_ONCE(line->sw_debounced, 0);
834         WRITE_ONCE(line->eflags, 0);
835         if (line->desc)
836                 WRITE_ONCE(line->desc->debounce_period_us, 0);
837         /* do not change line->level - see comment in debounced_value() */
838 }
839
840 static int edge_detector_setup(struct line *line,
841                                struct gpio_v2_line_config *lc,
842                                unsigned int line_idx,
843                                u64 eflags)
844 {
845         u32 debounce_period_us;
846         unsigned long irqflags = 0;
847         int irq, ret;
848
849         if (eflags && !kfifo_initialized(&line->req->events)) {
850                 ret = kfifo_alloc(&line->req->events,
851                                   line->req->event_buffer_size, GFP_KERNEL);
852                 if (ret)
853                         return ret;
854         }
855         WRITE_ONCE(line->eflags, eflags);
856         if (gpio_v2_line_config_debounced(lc, line_idx)) {
857                 debounce_period_us = gpio_v2_line_config_debounce_period(lc, line_idx);
858                 ret = debounce_setup(line, debounce_period_us);
859                 if (ret)
860                         return ret;
861                 WRITE_ONCE(line->desc->debounce_period_us, debounce_period_us);
862         }
863
864         /* detection disabled or sw debouncer will provide edge detection */
865         if (!eflags || READ_ONCE(line->sw_debounced))
866                 return 0;
867
868         irq = gpiod_to_irq(line->desc);
869         if (irq < 0)
870                 return -ENXIO;
871
872         if (eflags & GPIO_V2_LINE_FLAG_EDGE_RISING)
873                 irqflags |= test_bit(FLAG_ACTIVE_LOW, &line->desc->flags) ?
874                         IRQF_TRIGGER_FALLING : IRQF_TRIGGER_RISING;
875         if (eflags & GPIO_V2_LINE_FLAG_EDGE_FALLING)
876                 irqflags |= test_bit(FLAG_ACTIVE_LOW, &line->desc->flags) ?
877                         IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING;
878         irqflags |= IRQF_ONESHOT;
879
880         /* Request a thread to read the events */
881         ret = request_threaded_irq(irq, edge_irq_handler, edge_irq_thread,
882                                    irqflags, line->req->label, line);
883         if (ret)
884                 return ret;
885
886         line->irq = irq;
887         return 0;
888 }
889
890 static int edge_detector_update(struct line *line,
891                                 struct gpio_v2_line_config *lc,
892                                 unsigned int line_idx,
893                                 u64 eflags, bool polarity_change)
894 {
895         unsigned int debounce_period_us =
896                 gpio_v2_line_config_debounce_period(lc, line_idx);
897
898         if ((READ_ONCE(line->eflags) == eflags) && !polarity_change &&
899             (READ_ONCE(line->desc->debounce_period_us) == debounce_period_us))
900                 return 0;
901
902         /* sw debounced and still will be...*/
903         if (debounce_period_us && READ_ONCE(line->sw_debounced)) {
904                 WRITE_ONCE(line->eflags, eflags);
905                 WRITE_ONCE(line->desc->debounce_period_us, debounce_period_us);
906                 return 0;
907         }
908
909         /* reconfiguring edge detection or sw debounce being disabled */
910         if ((line->irq && !READ_ONCE(line->sw_debounced)) ||
911             (!debounce_period_us && READ_ONCE(line->sw_debounced)))
912                 edge_detector_stop(line);
913
914         return edge_detector_setup(line, lc, line_idx, eflags);
915 }
916
917 static u64 gpio_v2_line_config_flags(struct gpio_v2_line_config *lc,
918                                      unsigned int line_idx)
919 {
920         unsigned int i;
921         u64 mask = BIT_ULL(line_idx);
922
923         for (i = 0; i < lc->num_attrs; i++) {
924                 if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_FLAGS) &&
925                     (lc->attrs[i].mask & mask))
926                         return lc->attrs[i].attr.flags;
927         }
928         return lc->flags;
929 }
930
931 static int gpio_v2_line_config_output_value(struct gpio_v2_line_config *lc,
932                                             unsigned int line_idx)
933 {
934         unsigned int i;
935         u64 mask = BIT_ULL(line_idx);
936
937         for (i = 0; i < lc->num_attrs; i++) {
938                 if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_OUTPUT_VALUES) &&
939                     (lc->attrs[i].mask & mask))
940                         return !!(lc->attrs[i].attr.values & mask);
941         }
942         return 0;
943 }
944
945 static int gpio_v2_line_flags_validate(u64 flags)
946 {
947         /* Return an error if an unknown flag is set */
948         if (flags & ~GPIO_V2_LINE_VALID_FLAGS)
949                 return -EINVAL;
950
951         /*
952          * Do not allow both INPUT and OUTPUT flags to be set as they are
953          * contradictory.
954          */
955         if ((flags & GPIO_V2_LINE_FLAG_INPUT) &&
956             (flags & GPIO_V2_LINE_FLAG_OUTPUT))
957                 return -EINVAL;
958
959         /* Edge detection requires explicit input. */
960         if ((flags & GPIO_V2_LINE_EDGE_FLAGS) &&
961             !(flags & GPIO_V2_LINE_FLAG_INPUT))
962                 return -EINVAL;
963
964         /*
965          * Do not allow OPEN_SOURCE and OPEN_DRAIN flags in a single
966          * request. If the hardware actually supports enabling both at the
967          * same time the electrical result would be disastrous.
968          */
969         if ((flags & GPIO_V2_LINE_FLAG_OPEN_DRAIN) &&
970             (flags & GPIO_V2_LINE_FLAG_OPEN_SOURCE))
971                 return -EINVAL;
972
973         /* Drive requires explicit output direction. */
974         if ((flags & GPIO_V2_LINE_DRIVE_FLAGS) &&
975             !(flags & GPIO_V2_LINE_FLAG_OUTPUT))
976                 return -EINVAL;
977
978         /* Bias requires explicit direction. */
979         if ((flags & GPIO_V2_LINE_BIAS_FLAGS) &&
980             !(flags & GPIO_V2_LINE_DIRECTION_FLAGS))
981                 return -EINVAL;
982
983         /* Only one bias flag can be set. */
984         if (((flags & GPIO_V2_LINE_FLAG_BIAS_DISABLED) &&
985              (flags & (GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN |
986                        GPIO_V2_LINE_FLAG_BIAS_PULL_UP))) ||
987             ((flags & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN) &&
988              (flags & GPIO_V2_LINE_FLAG_BIAS_PULL_UP)))
989                 return -EINVAL;
990
991         return 0;
992 }
993
994 static int gpio_v2_line_config_validate(struct gpio_v2_line_config *lc,
995                                         unsigned int num_lines)
996 {
997         unsigned int i;
998         u64 flags;
999         int ret;
1000
1001         if (lc->num_attrs > GPIO_V2_LINE_NUM_ATTRS_MAX)
1002                 return -EINVAL;
1003
1004         if (memchr_inv(lc->padding, 0, sizeof(lc->padding)))
1005                 return -EINVAL;
1006
1007         for (i = 0; i < num_lines; i++) {
1008                 flags = gpio_v2_line_config_flags(lc, i);
1009                 ret = gpio_v2_line_flags_validate(flags);
1010                 if (ret)
1011                         return ret;
1012
1013                 /* debounce requires explicit input */
1014                 if (gpio_v2_line_config_debounced(lc, i) &&
1015                     !(flags & GPIO_V2_LINE_FLAG_INPUT))
1016                         return -EINVAL;
1017         }
1018         return 0;
1019 }
1020
1021 static void gpio_v2_line_config_flags_to_desc_flags(u64 flags,
1022                                                     unsigned long *flagsp)
1023 {
1024         assign_bit(FLAG_ACTIVE_LOW, flagsp,
1025                    flags & GPIO_V2_LINE_FLAG_ACTIVE_LOW);
1026
1027         if (flags & GPIO_V2_LINE_FLAG_OUTPUT)
1028                 set_bit(FLAG_IS_OUT, flagsp);
1029         else if (flags & GPIO_V2_LINE_FLAG_INPUT)
1030                 clear_bit(FLAG_IS_OUT, flagsp);
1031
1032         assign_bit(FLAG_EDGE_RISING, flagsp,
1033                    flags & GPIO_V2_LINE_FLAG_EDGE_RISING);
1034         assign_bit(FLAG_EDGE_FALLING, flagsp,
1035                    flags & GPIO_V2_LINE_FLAG_EDGE_FALLING);
1036
1037         assign_bit(FLAG_OPEN_DRAIN, flagsp,
1038                    flags & GPIO_V2_LINE_FLAG_OPEN_DRAIN);
1039         assign_bit(FLAG_OPEN_SOURCE, flagsp,
1040                    flags & GPIO_V2_LINE_FLAG_OPEN_SOURCE);
1041
1042         assign_bit(FLAG_PULL_UP, flagsp,
1043                    flags & GPIO_V2_LINE_FLAG_BIAS_PULL_UP);
1044         assign_bit(FLAG_PULL_DOWN, flagsp,
1045                    flags & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN);
1046         assign_bit(FLAG_BIAS_DISABLE, flagsp,
1047                    flags & GPIO_V2_LINE_FLAG_BIAS_DISABLED);
1048
1049         assign_bit(FLAG_EVENT_CLOCK_REALTIME, flagsp,
1050                    flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME);
1051 }
1052
1053 static long linereq_get_values(struct linereq *lr, void __user *ip)
1054 {
1055         struct gpio_v2_line_values lv;
1056         DECLARE_BITMAP(vals, GPIO_V2_LINES_MAX);
1057         struct gpio_desc **descs;
1058         unsigned int i, didx, num_get;
1059         bool val;
1060         int ret;
1061
1062         /* NOTE: It's ok to read values of output lines. */
1063         if (copy_from_user(&lv, ip, sizeof(lv)))
1064                 return -EFAULT;
1065
1066         for (num_get = 0, i = 0; i < lr->num_lines; i++) {
1067                 if (lv.mask & BIT_ULL(i)) {
1068                         num_get++;
1069                         descs = &lr->lines[i].desc;
1070                 }
1071         }
1072
1073         if (num_get == 0)
1074                 return -EINVAL;
1075
1076         if (num_get != 1) {
1077                 descs = kmalloc_array(num_get, sizeof(*descs), GFP_KERNEL);
1078                 if (!descs)
1079                         return -ENOMEM;
1080                 for (didx = 0, i = 0; i < lr->num_lines; i++) {
1081                         if (lv.mask & BIT_ULL(i)) {
1082                                 descs[didx] = lr->lines[i].desc;
1083                                 didx++;
1084                         }
1085                 }
1086         }
1087         ret = gpiod_get_array_value_complex(false, true, num_get,
1088                                             descs, NULL, vals);
1089
1090         if (num_get != 1)
1091                 kfree(descs);
1092         if (ret)
1093                 return ret;
1094
1095         lv.bits = 0;
1096         for (didx = 0, i = 0; i < lr->num_lines; i++) {
1097                 if (lv.mask & BIT_ULL(i)) {
1098                         if (lr->lines[i].sw_debounced)
1099                                 val = debounced_value(&lr->lines[i]);
1100                         else
1101                                 val = test_bit(didx, vals);
1102                         if (val)
1103                                 lv.bits |= BIT_ULL(i);
1104                         didx++;
1105                 }
1106         }
1107
1108         if (copy_to_user(ip, &lv, sizeof(lv)))
1109                 return -EFAULT;
1110
1111         return 0;
1112 }
1113
1114 static long linereq_set_values_unlocked(struct linereq *lr,
1115                                         struct gpio_v2_line_values *lv)
1116 {
1117         DECLARE_BITMAP(vals, GPIO_V2_LINES_MAX);
1118         struct gpio_desc **descs;
1119         unsigned int i, didx, num_set;
1120         int ret;
1121
1122         bitmap_zero(vals, GPIO_V2_LINES_MAX);
1123         for (num_set = 0, i = 0; i < lr->num_lines; i++) {
1124                 if (lv->mask & BIT_ULL(i)) {
1125                         if (!test_bit(FLAG_IS_OUT, &lr->lines[i].desc->flags))
1126                                 return -EPERM;
1127                         if (lv->bits & BIT_ULL(i))
1128                                 __set_bit(num_set, vals);
1129                         num_set++;
1130                         descs = &lr->lines[i].desc;
1131                 }
1132         }
1133         if (num_set == 0)
1134                 return -EINVAL;
1135
1136         if (num_set != 1) {
1137                 /* build compacted desc array and values */
1138                 descs = kmalloc_array(num_set, sizeof(*descs), GFP_KERNEL);
1139                 if (!descs)
1140                         return -ENOMEM;
1141                 for (didx = 0, i = 0; i < lr->num_lines; i++) {
1142                         if (lv->mask & BIT_ULL(i)) {
1143                                 descs[didx] = lr->lines[i].desc;
1144                                 didx++;
1145                         }
1146                 }
1147         }
1148         ret = gpiod_set_array_value_complex(false, true, num_set,
1149                                             descs, NULL, vals);
1150
1151         if (num_set != 1)
1152                 kfree(descs);
1153         return ret;
1154 }
1155
1156 static long linereq_set_values(struct linereq *lr, void __user *ip)
1157 {
1158         struct gpio_v2_line_values lv;
1159         int ret;
1160
1161         if (copy_from_user(&lv, ip, sizeof(lv)))
1162                 return -EFAULT;
1163
1164         mutex_lock(&lr->config_mutex);
1165
1166         ret = linereq_set_values_unlocked(lr, &lv);
1167
1168         mutex_unlock(&lr->config_mutex);
1169
1170         return ret;
1171 }
1172
1173 static long linereq_set_config_unlocked(struct linereq *lr,
1174                                         struct gpio_v2_line_config *lc)
1175 {
1176         struct gpio_desc *desc;
1177         unsigned int i;
1178         u64 flags;
1179         bool polarity_change;
1180         int ret;
1181
1182         for (i = 0; i < lr->num_lines; i++) {
1183                 desc = lr->lines[i].desc;
1184                 flags = gpio_v2_line_config_flags(lc, i);
1185                 polarity_change =
1186                         (!!test_bit(FLAG_ACTIVE_LOW, &desc->flags) !=
1187                          ((flags & GPIO_V2_LINE_FLAG_ACTIVE_LOW) != 0));
1188
1189                 gpio_v2_line_config_flags_to_desc_flags(flags, &desc->flags);
1190                 /*
1191                  * Lines have to be requested explicitly for input
1192                  * or output, else the line will be treated "as is".
1193                  */
1194                 if (flags & GPIO_V2_LINE_FLAG_OUTPUT) {
1195                         int val = gpio_v2_line_config_output_value(lc, i);
1196
1197                         edge_detector_stop(&lr->lines[i]);
1198                         ret = gpiod_direction_output(desc, val);
1199                         if (ret)
1200                                 return ret;
1201                 } else if (flags & GPIO_V2_LINE_FLAG_INPUT) {
1202                         ret = gpiod_direction_input(desc);
1203                         if (ret)
1204                                 return ret;
1205
1206                         ret = edge_detector_update(&lr->lines[i], lc, i,
1207                                         flags & GPIO_V2_LINE_EDGE_FLAGS,
1208                                         polarity_change);
1209                         if (ret)
1210                                 return ret;
1211                 }
1212
1213                 blocking_notifier_call_chain(&desc->gdev->notifier,
1214                                              GPIO_V2_LINE_CHANGED_CONFIG,
1215                                              desc);
1216         }
1217         return 0;
1218 }
1219
1220 static long linereq_set_config(struct linereq *lr, void __user *ip)
1221 {
1222         struct gpio_v2_line_config lc;
1223         int ret;
1224
1225         if (copy_from_user(&lc, ip, sizeof(lc)))
1226                 return -EFAULT;
1227
1228         ret = gpio_v2_line_config_validate(&lc, lr->num_lines);
1229         if (ret)
1230                 return ret;
1231
1232         mutex_lock(&lr->config_mutex);
1233
1234         ret = linereq_set_config_unlocked(lr, &lc);
1235
1236         mutex_unlock(&lr->config_mutex);
1237
1238         return ret;
1239 }
1240
1241 static long linereq_ioctl_unlocked(struct file *file, unsigned int cmd,
1242                                    unsigned long arg)
1243 {
1244         struct linereq *lr = file->private_data;
1245         void __user *ip = (void __user *)arg;
1246
1247         if (!lr->gdev->chip)
1248                 return -ENODEV;
1249
1250         switch (cmd) {
1251         case GPIO_V2_LINE_GET_VALUES_IOCTL:
1252                 return linereq_get_values(lr, ip);
1253         case GPIO_V2_LINE_SET_VALUES_IOCTL:
1254                 return linereq_set_values(lr, ip);
1255         case GPIO_V2_LINE_SET_CONFIG_IOCTL:
1256                 return linereq_set_config(lr, ip);
1257         default:
1258                 return -EINVAL;
1259         }
1260 }
1261
1262 static long linereq_ioctl(struct file *file, unsigned int cmd,
1263                           unsigned long arg)
1264 {
1265         struct linereq *lr = file->private_data;
1266
1267         return call_ioctl_locked(file, cmd, arg, lr->gdev,
1268                                  linereq_ioctl_unlocked);
1269 }
1270
1271 #ifdef CONFIG_COMPAT
1272 static long linereq_ioctl_compat(struct file *file, unsigned int cmd,
1273                                  unsigned long arg)
1274 {
1275         return linereq_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
1276 }
1277 #endif
1278
1279 static __poll_t linereq_poll_unlocked(struct file *file,
1280                                       struct poll_table_struct *wait)
1281 {
1282         struct linereq *lr = file->private_data;
1283         __poll_t events = 0;
1284
1285         if (!lr->gdev->chip)
1286                 return EPOLLHUP | EPOLLERR;
1287
1288         poll_wait(file, &lr->wait, wait);
1289
1290         if (!kfifo_is_empty_spinlocked_noirqsave(&lr->events,
1291                                                  &lr->wait.lock))
1292                 events = EPOLLIN | EPOLLRDNORM;
1293
1294         return events;
1295 }
1296
1297 static __poll_t linereq_poll(struct file *file,
1298                              struct poll_table_struct *wait)
1299 {
1300         struct linereq *lr = file->private_data;
1301
1302         return call_poll_locked(file, wait, lr->gdev, linereq_poll_unlocked);
1303 }
1304
1305 static ssize_t linereq_read_unlocked(struct file *file, char __user *buf,
1306                                      size_t count, loff_t *f_ps)
1307 {
1308         struct linereq *lr = file->private_data;
1309         struct gpio_v2_line_event le;
1310         ssize_t bytes_read = 0;
1311         int ret;
1312
1313         if (!lr->gdev->chip)
1314                 return -ENODEV;
1315
1316         if (count < sizeof(le))
1317                 return -EINVAL;
1318
1319         do {
1320                 spin_lock(&lr->wait.lock);
1321                 if (kfifo_is_empty(&lr->events)) {
1322                         if (bytes_read) {
1323                                 spin_unlock(&lr->wait.lock);
1324                                 return bytes_read;
1325                         }
1326
1327                         if (file->f_flags & O_NONBLOCK) {
1328                                 spin_unlock(&lr->wait.lock);
1329                                 return -EAGAIN;
1330                         }
1331
1332                         ret = wait_event_interruptible_locked(lr->wait,
1333                                         !kfifo_is_empty(&lr->events));
1334                         if (ret) {
1335                                 spin_unlock(&lr->wait.lock);
1336                                 return ret;
1337                         }
1338                 }
1339
1340                 ret = kfifo_out(&lr->events, &le, 1);
1341                 spin_unlock(&lr->wait.lock);
1342                 if (ret != 1) {
1343                         /*
1344                          * This should never happen - we were holding the
1345                          * lock from the moment we learned the fifo is no
1346                          * longer empty until now.
1347                          */
1348                         ret = -EIO;
1349                         break;
1350                 }
1351
1352                 if (copy_to_user(buf + bytes_read, &le, sizeof(le)))
1353                         return -EFAULT;
1354                 bytes_read += sizeof(le);
1355         } while (count >= bytes_read + sizeof(le));
1356
1357         return bytes_read;
1358 }
1359
1360 static ssize_t linereq_read(struct file *file, char __user *buf,
1361                             size_t count, loff_t *f_ps)
1362 {
1363         struct linereq *lr = file->private_data;
1364
1365         return call_read_locked(file, buf, count, f_ps, lr->gdev,
1366                                 linereq_read_unlocked);
1367 }
1368
1369 static void linereq_free(struct linereq *lr)
1370 {
1371         unsigned int i;
1372
1373         for (i = 0; i < lr->num_lines; i++) {
1374                 edge_detector_stop(&lr->lines[i]);
1375                 if (lr->lines[i].desc)
1376                         gpiod_free(lr->lines[i].desc);
1377         }
1378         kfifo_free(&lr->events);
1379         kfree(lr->label);
1380         put_device(&lr->gdev->dev);
1381         kfree(lr);
1382 }
1383
1384 static int linereq_release(struct inode *inode, struct file *file)
1385 {
1386         struct linereq *lr = file->private_data;
1387
1388         linereq_free(lr);
1389         return 0;
1390 }
1391
1392 static const struct file_operations line_fileops = {
1393         .release = linereq_release,
1394         .read = linereq_read,
1395         .poll = linereq_poll,
1396         .owner = THIS_MODULE,
1397         .llseek = noop_llseek,
1398         .unlocked_ioctl = linereq_ioctl,
1399 #ifdef CONFIG_COMPAT
1400         .compat_ioctl = linereq_ioctl_compat,
1401 #endif
1402 };
1403
1404 static int linereq_create(struct gpio_device *gdev, void __user *ip)
1405 {
1406         struct gpio_v2_line_request ulr;
1407         struct gpio_v2_line_config *lc;
1408         struct linereq *lr;
1409         struct file *file;
1410         u64 flags;
1411         unsigned int i;
1412         int fd, ret;
1413
1414         if (copy_from_user(&ulr, ip, sizeof(ulr)))
1415                 return -EFAULT;
1416
1417         if ((ulr.num_lines == 0) || (ulr.num_lines > GPIO_V2_LINES_MAX))
1418                 return -EINVAL;
1419
1420         if (memchr_inv(ulr.padding, 0, sizeof(ulr.padding)))
1421                 return -EINVAL;
1422
1423         lc = &ulr.config;
1424         ret = gpio_v2_line_config_validate(lc, ulr.num_lines);
1425         if (ret)
1426                 return ret;
1427
1428         lr = kzalloc(struct_size(lr, lines, ulr.num_lines), GFP_KERNEL);
1429         if (!lr)
1430                 return -ENOMEM;
1431
1432         lr->gdev = gdev;
1433         get_device(&gdev->dev);
1434
1435         for (i = 0; i < ulr.num_lines; i++) {
1436                 lr->lines[i].req = lr;
1437                 WRITE_ONCE(lr->lines[i].sw_debounced, 0);
1438                 INIT_DELAYED_WORK(&lr->lines[i].work, debounce_work_func);
1439         }
1440
1441         if (ulr.consumer[0] != '\0') {
1442                 /* label is only initialized if consumer is set */
1443                 lr->label = kstrndup(ulr.consumer, sizeof(ulr.consumer) - 1,
1444                                      GFP_KERNEL);
1445                 if (!lr->label) {
1446                         ret = -ENOMEM;
1447                         goto out_free_linereq;
1448                 }
1449         }
1450
1451         mutex_init(&lr->config_mutex);
1452         init_waitqueue_head(&lr->wait);
1453         lr->event_buffer_size = ulr.event_buffer_size;
1454         if (lr->event_buffer_size == 0)
1455                 lr->event_buffer_size = ulr.num_lines * 16;
1456         else if (lr->event_buffer_size > GPIO_V2_LINES_MAX * 16)
1457                 lr->event_buffer_size = GPIO_V2_LINES_MAX * 16;
1458
1459         atomic_set(&lr->seqno, 0);
1460         lr->num_lines = ulr.num_lines;
1461
1462         /* Request each GPIO */
1463         for (i = 0; i < ulr.num_lines; i++) {
1464                 u32 offset = ulr.offsets[i];
1465                 struct gpio_desc *desc = gpiochip_get_desc(gdev->chip, offset);
1466
1467                 if (IS_ERR(desc)) {
1468                         ret = PTR_ERR(desc);
1469                         goto out_free_linereq;
1470                 }
1471
1472                 ret = gpiod_request_user(desc, lr->label);
1473                 if (ret)
1474                         goto out_free_linereq;
1475
1476                 lr->lines[i].desc = desc;
1477                 flags = gpio_v2_line_config_flags(lc, i);
1478                 gpio_v2_line_config_flags_to_desc_flags(flags, &desc->flags);
1479
1480                 ret = gpiod_set_transitory(desc, false);
1481                 if (ret < 0)
1482                         goto out_free_linereq;
1483
1484                 /*
1485                  * Lines have to be requested explicitly for input
1486                  * or output, else the line will be treated "as is".
1487                  */
1488                 if (flags & GPIO_V2_LINE_FLAG_OUTPUT) {
1489                         int val = gpio_v2_line_config_output_value(lc, i);
1490
1491                         ret = gpiod_direction_output(desc, val);
1492                         if (ret)
1493                                 goto out_free_linereq;
1494                 } else if (flags & GPIO_V2_LINE_FLAG_INPUT) {
1495                         ret = gpiod_direction_input(desc);
1496                         if (ret)
1497                                 goto out_free_linereq;
1498
1499                         ret = edge_detector_setup(&lr->lines[i], lc, i,
1500                                         flags & GPIO_V2_LINE_EDGE_FLAGS);
1501                         if (ret)
1502                                 goto out_free_linereq;
1503                 }
1504
1505                 blocking_notifier_call_chain(&desc->gdev->notifier,
1506                                              GPIO_V2_LINE_CHANGED_REQUESTED, desc);
1507
1508                 dev_dbg(&gdev->dev, "registered chardev handle for line %d\n",
1509                         offset);
1510         }
1511
1512         fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
1513         if (fd < 0) {
1514                 ret = fd;
1515                 goto out_free_linereq;
1516         }
1517
1518         file = anon_inode_getfile("gpio-line", &line_fileops, lr,
1519                                   O_RDONLY | O_CLOEXEC);
1520         if (IS_ERR(file)) {
1521                 ret = PTR_ERR(file);
1522                 goto out_put_unused_fd;
1523         }
1524
1525         ulr.fd = fd;
1526         if (copy_to_user(ip, &ulr, sizeof(ulr))) {
1527                 /*
1528                  * fput() will trigger the release() callback, so do not go onto
1529                  * the regular error cleanup path here.
1530                  */
1531                 fput(file);
1532                 put_unused_fd(fd);
1533                 return -EFAULT;
1534         }
1535
1536         fd_install(fd, file);
1537
1538         dev_dbg(&gdev->dev, "registered chardev handle for %d lines\n",
1539                 lr->num_lines);
1540
1541         return 0;
1542
1543 out_put_unused_fd:
1544         put_unused_fd(fd);
1545 out_free_linereq:
1546         linereq_free(lr);
1547         return ret;
1548 }
1549
1550 #ifdef CONFIG_GPIO_CDEV_V1
1551
1552 /*
1553  * GPIO line event management
1554  */
1555
1556 /**
1557  * struct lineevent_state - contains the state of a userspace event
1558  * @gdev: the GPIO device the event pertains to
1559  * @label: consumer label used to tag descriptors
1560  * @desc: the GPIO descriptor held by this event
1561  * @eflags: the event flags this line was requested with
1562  * @irq: the interrupt that trigger in response to events on this GPIO
1563  * @wait: wait queue that handles blocking reads of events
1564  * @events: KFIFO for the GPIO events
1565  * @timestamp: cache for the timestamp storing it between hardirq
1566  * and IRQ thread, used to bring the timestamp close to the actual
1567  * event
1568  */
1569 struct lineevent_state {
1570         struct gpio_device *gdev;
1571         const char *label;
1572         struct gpio_desc *desc;
1573         u32 eflags;
1574         int irq;
1575         wait_queue_head_t wait;
1576         DECLARE_KFIFO(events, struct gpioevent_data, 16);
1577         u64 timestamp;
1578 };
1579
1580 #define GPIOEVENT_REQUEST_VALID_FLAGS \
1581         (GPIOEVENT_REQUEST_RISING_EDGE | \
1582         GPIOEVENT_REQUEST_FALLING_EDGE)
1583
1584 static __poll_t lineevent_poll_unlocked(struct file *file,
1585                                         struct poll_table_struct *wait)
1586 {
1587         struct lineevent_state *le = file->private_data;
1588         __poll_t events = 0;
1589
1590         if (!le->gdev->chip)
1591                 return EPOLLHUP | EPOLLERR;
1592
1593         poll_wait(file, &le->wait, wait);
1594
1595         if (!kfifo_is_empty_spinlocked_noirqsave(&le->events, &le->wait.lock))
1596                 events = EPOLLIN | EPOLLRDNORM;
1597
1598         return events;
1599 }
1600
1601 static __poll_t lineevent_poll(struct file *file,
1602                                struct poll_table_struct *wait)
1603 {
1604         struct lineevent_state *le = file->private_data;
1605
1606         return call_poll_locked(file, wait, le->gdev, lineevent_poll_unlocked);
1607 }
1608
1609 struct compat_gpioeevent_data {
1610         compat_u64      timestamp;
1611         u32             id;
1612 };
1613
1614 static ssize_t lineevent_read_unlocked(struct file *file, char __user *buf,
1615                                        size_t count, loff_t *f_ps)
1616 {
1617         struct lineevent_state *le = file->private_data;
1618         struct gpioevent_data ge;
1619         ssize_t bytes_read = 0;
1620         ssize_t ge_size;
1621         int ret;
1622
1623         if (!le->gdev->chip)
1624                 return -ENODEV;
1625
1626         /*
1627          * When compatible system call is being used the struct gpioevent_data,
1628          * in case of at least ia32, has different size due to the alignment
1629          * differences. Because we have first member 64 bits followed by one of
1630          * 32 bits there is no gap between them. The only difference is the
1631          * padding at the end of the data structure. Hence, we calculate the
1632          * actual sizeof() and pass this as an argument to copy_to_user() to
1633          * drop unneeded bytes from the output.
1634          */
1635         if (compat_need_64bit_alignment_fixup())
1636                 ge_size = sizeof(struct compat_gpioeevent_data);
1637         else
1638                 ge_size = sizeof(struct gpioevent_data);
1639         if (count < ge_size)
1640                 return -EINVAL;
1641
1642         do {
1643                 spin_lock(&le->wait.lock);
1644                 if (kfifo_is_empty(&le->events)) {
1645                         if (bytes_read) {
1646                                 spin_unlock(&le->wait.lock);
1647                                 return bytes_read;
1648                         }
1649
1650                         if (file->f_flags & O_NONBLOCK) {
1651                                 spin_unlock(&le->wait.lock);
1652                                 return -EAGAIN;
1653                         }
1654
1655                         ret = wait_event_interruptible_locked(le->wait,
1656                                         !kfifo_is_empty(&le->events));
1657                         if (ret) {
1658                                 spin_unlock(&le->wait.lock);
1659                                 return ret;
1660                         }
1661                 }
1662
1663                 ret = kfifo_out(&le->events, &ge, 1);
1664                 spin_unlock(&le->wait.lock);
1665                 if (ret != 1) {
1666                         /*
1667                          * This should never happen - we were holding the lock
1668                          * from the moment we learned the fifo is no longer
1669                          * empty until now.
1670                          */
1671                         ret = -EIO;
1672                         break;
1673                 }
1674
1675                 if (copy_to_user(buf + bytes_read, &ge, ge_size))
1676                         return -EFAULT;
1677                 bytes_read += ge_size;
1678         } while (count >= bytes_read + ge_size);
1679
1680         return bytes_read;
1681 }
1682
1683 static ssize_t lineevent_read(struct file *file, char __user *buf,
1684                               size_t count, loff_t *f_ps)
1685 {
1686         struct lineevent_state *le = file->private_data;
1687
1688         return call_read_locked(file, buf, count, f_ps, le->gdev,
1689                                 lineevent_read_unlocked);
1690 }
1691
1692 static void lineevent_free(struct lineevent_state *le)
1693 {
1694         if (le->irq)
1695                 free_irq(le->irq, le);
1696         if (le->desc)
1697                 gpiod_free(le->desc);
1698         kfree(le->label);
1699         put_device(&le->gdev->dev);
1700         kfree(le);
1701 }
1702
1703 static int lineevent_release(struct inode *inode, struct file *file)
1704 {
1705         lineevent_free(file->private_data);
1706         return 0;
1707 }
1708
1709 static long lineevent_ioctl_unlocked(struct file *file, unsigned int cmd,
1710                                      unsigned long arg)
1711 {
1712         struct lineevent_state *le = file->private_data;
1713         void __user *ip = (void __user *)arg;
1714         struct gpiohandle_data ghd;
1715
1716         if (!le->gdev->chip)
1717                 return -ENODEV;
1718
1719         /*
1720          * We can get the value for an event line but not set it,
1721          * because it is input by definition.
1722          */
1723         if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
1724                 int val;
1725
1726                 memset(&ghd, 0, sizeof(ghd));
1727
1728                 val = gpiod_get_value_cansleep(le->desc);
1729                 if (val < 0)
1730                         return val;
1731                 ghd.values[0] = val;
1732
1733                 if (copy_to_user(ip, &ghd, sizeof(ghd)))
1734                         return -EFAULT;
1735
1736                 return 0;
1737         }
1738         return -EINVAL;
1739 }
1740
1741 static long lineevent_ioctl(struct file *file, unsigned int cmd,
1742                             unsigned long arg)
1743 {
1744         struct lineevent_state *le = file->private_data;
1745
1746         return call_ioctl_locked(file, cmd, arg, le->gdev,
1747                                  lineevent_ioctl_unlocked);
1748 }
1749
1750 #ifdef CONFIG_COMPAT
1751 static long lineevent_ioctl_compat(struct file *file, unsigned int cmd,
1752                                    unsigned long arg)
1753 {
1754         return lineevent_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
1755 }
1756 #endif
1757
1758 static const struct file_operations lineevent_fileops = {
1759         .release = lineevent_release,
1760         .read = lineevent_read,
1761         .poll = lineevent_poll,
1762         .owner = THIS_MODULE,
1763         .llseek = noop_llseek,
1764         .unlocked_ioctl = lineevent_ioctl,
1765 #ifdef CONFIG_COMPAT
1766         .compat_ioctl = lineevent_ioctl_compat,
1767 #endif
1768 };
1769
1770 static irqreturn_t lineevent_irq_thread(int irq, void *p)
1771 {
1772         struct lineevent_state *le = p;
1773         struct gpioevent_data ge;
1774         int ret;
1775
1776         /* Do not leak kernel stack to userspace */
1777         memset(&ge, 0, sizeof(ge));
1778
1779         /*
1780          * We may be running from a nested threaded interrupt in which case
1781          * we didn't get the timestamp from lineevent_irq_handler().
1782          */
1783         if (!le->timestamp)
1784                 ge.timestamp = ktime_get_ns();
1785         else
1786                 ge.timestamp = le->timestamp;
1787
1788         if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE
1789             && le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
1790                 int level = gpiod_get_value_cansleep(le->desc);
1791
1792                 if (level)
1793                         /* Emit low-to-high event */
1794                         ge.id = GPIOEVENT_EVENT_RISING_EDGE;
1795                 else
1796                         /* Emit high-to-low event */
1797                         ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
1798         } else if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE) {
1799                 /* Emit low-to-high event */
1800                 ge.id = GPIOEVENT_EVENT_RISING_EDGE;
1801         } else if (le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
1802                 /* Emit high-to-low event */
1803                 ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
1804         } else {
1805                 return IRQ_NONE;
1806         }
1807
1808         ret = kfifo_in_spinlocked_noirqsave(&le->events, &ge,
1809                                             1, &le->wait.lock);
1810         if (ret)
1811                 wake_up_poll(&le->wait, EPOLLIN);
1812         else
1813                 pr_debug_ratelimited("event FIFO is full - event dropped\n");
1814
1815         return IRQ_HANDLED;
1816 }
1817
1818 static irqreturn_t lineevent_irq_handler(int irq, void *p)
1819 {
1820         struct lineevent_state *le = p;
1821
1822         /*
1823          * Just store the timestamp in hardirq context so we get it as
1824          * close in time as possible to the actual event.
1825          */
1826         le->timestamp = ktime_get_ns();
1827
1828         return IRQ_WAKE_THREAD;
1829 }
1830
1831 static int lineevent_create(struct gpio_device *gdev, void __user *ip)
1832 {
1833         struct gpioevent_request eventreq;
1834         struct lineevent_state *le;
1835         struct gpio_desc *desc;
1836         struct file *file;
1837         u32 offset;
1838         u32 lflags;
1839         u32 eflags;
1840         int fd;
1841         int ret;
1842         int irq, irqflags = 0;
1843
1844         if (copy_from_user(&eventreq, ip, sizeof(eventreq)))
1845                 return -EFAULT;
1846
1847         offset = eventreq.lineoffset;
1848         lflags = eventreq.handleflags;
1849         eflags = eventreq.eventflags;
1850
1851         desc = gpiochip_get_desc(gdev->chip, offset);
1852         if (IS_ERR(desc))
1853                 return PTR_ERR(desc);
1854
1855         /* Return an error if a unknown flag is set */
1856         if ((lflags & ~GPIOHANDLE_REQUEST_VALID_FLAGS) ||
1857             (eflags & ~GPIOEVENT_REQUEST_VALID_FLAGS))
1858                 return -EINVAL;
1859
1860         /* This is just wrong: we don't look for events on output lines */
1861         if ((lflags & GPIOHANDLE_REQUEST_OUTPUT) ||
1862             (lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN) ||
1863             (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE))
1864                 return -EINVAL;
1865
1866         /* Only one bias flag can be set. */
1867         if (((lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE) &&
1868              (lflags & (GPIOHANDLE_REQUEST_BIAS_PULL_DOWN |
1869                         GPIOHANDLE_REQUEST_BIAS_PULL_UP))) ||
1870             ((lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN) &&
1871              (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)))
1872                 return -EINVAL;
1873
1874         le = kzalloc(sizeof(*le), GFP_KERNEL);
1875         if (!le)
1876                 return -ENOMEM;
1877         le->gdev = gdev;
1878         get_device(&gdev->dev);
1879
1880         if (eventreq.consumer_label[0] != '\0') {
1881                 /* label is only initialized if consumer_label is set */
1882                 le->label = kstrndup(eventreq.consumer_label,
1883                                      sizeof(eventreq.consumer_label) - 1,
1884                                      GFP_KERNEL);
1885                 if (!le->label) {
1886                         ret = -ENOMEM;
1887                         goto out_free_le;
1888                 }
1889         }
1890
1891         ret = gpiod_request_user(desc, le->label);
1892         if (ret)
1893                 goto out_free_le;
1894         le->desc = desc;
1895         le->eflags = eflags;
1896
1897         linehandle_flags_to_desc_flags(lflags, &desc->flags);
1898
1899         ret = gpiod_direction_input(desc);
1900         if (ret)
1901                 goto out_free_le;
1902
1903         blocking_notifier_call_chain(&desc->gdev->notifier,
1904                                      GPIO_V2_LINE_CHANGED_REQUESTED, desc);
1905
1906         irq = gpiod_to_irq(desc);
1907         if (irq <= 0) {
1908                 ret = -ENODEV;
1909                 goto out_free_le;
1910         }
1911
1912         if (eflags & GPIOEVENT_REQUEST_RISING_EDGE)
1913                 irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
1914                         IRQF_TRIGGER_FALLING : IRQF_TRIGGER_RISING;
1915         if (eflags & GPIOEVENT_REQUEST_FALLING_EDGE)
1916                 irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
1917                         IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING;
1918         irqflags |= IRQF_ONESHOT;
1919
1920         INIT_KFIFO(le->events);
1921         init_waitqueue_head(&le->wait);
1922
1923         /* Request a thread to read the events */
1924         ret = request_threaded_irq(irq,
1925                                    lineevent_irq_handler,
1926                                    lineevent_irq_thread,
1927                                    irqflags,
1928                                    le->label,
1929                                    le);
1930         if (ret)
1931                 goto out_free_le;
1932
1933         le->irq = irq;
1934
1935         fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
1936         if (fd < 0) {
1937                 ret = fd;
1938                 goto out_free_le;
1939         }
1940
1941         file = anon_inode_getfile("gpio-event",
1942                                   &lineevent_fileops,
1943                                   le,
1944                                   O_RDONLY | O_CLOEXEC);
1945         if (IS_ERR(file)) {
1946                 ret = PTR_ERR(file);
1947                 goto out_put_unused_fd;
1948         }
1949
1950         eventreq.fd = fd;
1951         if (copy_to_user(ip, &eventreq, sizeof(eventreq))) {
1952                 /*
1953                  * fput() will trigger the release() callback, so do not go onto
1954                  * the regular error cleanup path here.
1955                  */
1956                 fput(file);
1957                 put_unused_fd(fd);
1958                 return -EFAULT;
1959         }
1960
1961         fd_install(fd, file);
1962
1963         return 0;
1964
1965 out_put_unused_fd:
1966         put_unused_fd(fd);
1967 out_free_le:
1968         lineevent_free(le);
1969         return ret;
1970 }
1971
1972 static void gpio_v2_line_info_to_v1(struct gpio_v2_line_info *info_v2,
1973                                     struct gpioline_info *info_v1)
1974 {
1975         u64 flagsv2 = info_v2->flags;
1976
1977         memcpy(info_v1->name, info_v2->name, sizeof(info_v1->name));
1978         memcpy(info_v1->consumer, info_v2->consumer, sizeof(info_v1->consumer));
1979         info_v1->line_offset = info_v2->offset;
1980         info_v1->flags = 0;
1981
1982         if (flagsv2 & GPIO_V2_LINE_FLAG_USED)
1983                 info_v1->flags |= GPIOLINE_FLAG_KERNEL;
1984
1985         if (flagsv2 & GPIO_V2_LINE_FLAG_OUTPUT)
1986                 info_v1->flags |= GPIOLINE_FLAG_IS_OUT;
1987
1988         if (flagsv2 & GPIO_V2_LINE_FLAG_ACTIVE_LOW)
1989                 info_v1->flags |= GPIOLINE_FLAG_ACTIVE_LOW;
1990
1991         if (flagsv2 & GPIO_V2_LINE_FLAG_OPEN_DRAIN)
1992                 info_v1->flags |= GPIOLINE_FLAG_OPEN_DRAIN;
1993         if (flagsv2 & GPIO_V2_LINE_FLAG_OPEN_SOURCE)
1994                 info_v1->flags |= GPIOLINE_FLAG_OPEN_SOURCE;
1995
1996         if (flagsv2 & GPIO_V2_LINE_FLAG_BIAS_PULL_UP)
1997                 info_v1->flags |= GPIOLINE_FLAG_BIAS_PULL_UP;
1998         if (flagsv2 & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN)
1999                 info_v1->flags |= GPIOLINE_FLAG_BIAS_PULL_DOWN;
2000         if (flagsv2 & GPIO_V2_LINE_FLAG_BIAS_DISABLED)
2001                 info_v1->flags |= GPIOLINE_FLAG_BIAS_DISABLE;
2002 }
2003
2004 static void gpio_v2_line_info_changed_to_v1(
2005                 struct gpio_v2_line_info_changed *lic_v2,
2006                 struct gpioline_info_changed *lic_v1)
2007 {
2008         memset(lic_v1, 0, sizeof(*lic_v1));
2009         gpio_v2_line_info_to_v1(&lic_v2->info, &lic_v1->info);
2010         lic_v1->timestamp = lic_v2->timestamp_ns;
2011         lic_v1->event_type = lic_v2->event_type;
2012 }
2013
2014 #endif /* CONFIG_GPIO_CDEV_V1 */
2015
2016 static void gpio_desc_to_lineinfo(struct gpio_desc *desc,
2017                                   struct gpio_v2_line_info *info)
2018 {
2019         struct gpio_chip *gc = desc->gdev->chip;
2020         bool ok_for_pinctrl;
2021         unsigned long flags;
2022         u32 debounce_period_us;
2023         unsigned int num_attrs = 0;
2024
2025         memset(info, 0, sizeof(*info));
2026         info->offset = gpio_chip_hwgpio(desc);
2027
2028         /*
2029          * This function takes a mutex so we must check this before taking
2030          * the spinlock.
2031          *
2032          * FIXME: find a non-racy way to retrieve this information. Maybe a
2033          * lock common to both frameworks?
2034          */
2035         ok_for_pinctrl =
2036                 pinctrl_gpio_can_use_line(gc->base + info->offset);
2037
2038         spin_lock_irqsave(&gpio_lock, flags);
2039
2040         if (desc->name)
2041                 strscpy(info->name, desc->name, sizeof(info->name));
2042
2043         if (desc->label)
2044                 strscpy(info->consumer, desc->label, sizeof(info->consumer));
2045
2046         /*
2047          * Userspace only need to know that the kernel is using this GPIO so
2048          * it can't use it.
2049          */
2050         info->flags = 0;
2051         if (test_bit(FLAG_REQUESTED, &desc->flags) ||
2052             test_bit(FLAG_IS_HOGGED, &desc->flags) ||
2053             test_bit(FLAG_USED_AS_IRQ, &desc->flags) ||
2054             test_bit(FLAG_EXPORT, &desc->flags) ||
2055             test_bit(FLAG_SYSFS, &desc->flags) ||
2056             !gpiochip_line_is_valid(gc, info->offset) ||
2057             !ok_for_pinctrl)
2058                 info->flags |= GPIO_V2_LINE_FLAG_USED;
2059
2060         if (test_bit(FLAG_IS_OUT, &desc->flags))
2061                 info->flags |= GPIO_V2_LINE_FLAG_OUTPUT;
2062         else
2063                 info->flags |= GPIO_V2_LINE_FLAG_INPUT;
2064
2065         if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2066                 info->flags |= GPIO_V2_LINE_FLAG_ACTIVE_LOW;
2067
2068         if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
2069                 info->flags |= GPIO_V2_LINE_FLAG_OPEN_DRAIN;
2070         if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
2071                 info->flags |= GPIO_V2_LINE_FLAG_OPEN_SOURCE;
2072
2073         if (test_bit(FLAG_BIAS_DISABLE, &desc->flags))
2074                 info->flags |= GPIO_V2_LINE_FLAG_BIAS_DISABLED;
2075         if (test_bit(FLAG_PULL_DOWN, &desc->flags))
2076                 info->flags |= GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN;
2077         if (test_bit(FLAG_PULL_UP, &desc->flags))
2078                 info->flags |= GPIO_V2_LINE_FLAG_BIAS_PULL_UP;
2079
2080         if (test_bit(FLAG_EDGE_RISING, &desc->flags))
2081                 info->flags |= GPIO_V2_LINE_FLAG_EDGE_RISING;
2082         if (test_bit(FLAG_EDGE_FALLING, &desc->flags))
2083                 info->flags |= GPIO_V2_LINE_FLAG_EDGE_FALLING;
2084
2085         if (test_bit(FLAG_EVENT_CLOCK_REALTIME, &desc->flags))
2086                 info->flags |= GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME;
2087
2088         debounce_period_us = READ_ONCE(desc->debounce_period_us);
2089         if (debounce_period_us) {
2090                 info->attrs[num_attrs].id = GPIO_V2_LINE_ATTR_ID_DEBOUNCE;
2091                 info->attrs[num_attrs].debounce_period_us = debounce_period_us;
2092                 num_attrs++;
2093         }
2094         info->num_attrs = num_attrs;
2095
2096         spin_unlock_irqrestore(&gpio_lock, flags);
2097 }
2098
2099 struct gpio_chardev_data {
2100         struct gpio_device *gdev;
2101         wait_queue_head_t wait;
2102         DECLARE_KFIFO(events, struct gpio_v2_line_info_changed, 32);
2103         struct notifier_block lineinfo_changed_nb;
2104         unsigned long *watched_lines;
2105 #ifdef CONFIG_GPIO_CDEV_V1
2106         atomic_t watch_abi_version;
2107 #endif
2108 };
2109
2110 static int chipinfo_get(struct gpio_chardev_data *cdev, void __user *ip)
2111 {
2112         struct gpio_device *gdev = cdev->gdev;
2113         struct gpiochip_info chipinfo;
2114
2115         memset(&chipinfo, 0, sizeof(chipinfo));
2116
2117         strscpy(chipinfo.name, dev_name(&gdev->dev), sizeof(chipinfo.name));
2118         strscpy(chipinfo.label, gdev->label, sizeof(chipinfo.label));
2119         chipinfo.lines = gdev->ngpio;
2120         if (copy_to_user(ip, &chipinfo, sizeof(chipinfo)))
2121                 return -EFAULT;
2122         return 0;
2123 }
2124
2125 #ifdef CONFIG_GPIO_CDEV_V1
2126 /*
2127  * returns 0 if the versions match, else the previously selected ABI version
2128  */
2129 static int lineinfo_ensure_abi_version(struct gpio_chardev_data *cdata,
2130                                        unsigned int version)
2131 {
2132         int abiv = atomic_cmpxchg(&cdata->watch_abi_version, 0, version);
2133
2134         if (abiv == version)
2135                 return 0;
2136
2137         return abiv;
2138 }
2139
2140 static int lineinfo_get_v1(struct gpio_chardev_data *cdev, void __user *ip,
2141                            bool watch)
2142 {
2143         struct gpio_desc *desc;
2144         struct gpioline_info lineinfo;
2145         struct gpio_v2_line_info lineinfo_v2;
2146
2147         if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
2148                 return -EFAULT;
2149
2150         /* this doubles as a range check on line_offset */
2151         desc = gpiochip_get_desc(cdev->gdev->chip, lineinfo.line_offset);
2152         if (IS_ERR(desc))
2153                 return PTR_ERR(desc);
2154
2155         if (watch) {
2156                 if (lineinfo_ensure_abi_version(cdev, 1))
2157                         return -EPERM;
2158
2159                 if (test_and_set_bit(lineinfo.line_offset, cdev->watched_lines))
2160                         return -EBUSY;
2161         }
2162
2163         gpio_desc_to_lineinfo(desc, &lineinfo_v2);
2164         gpio_v2_line_info_to_v1(&lineinfo_v2, &lineinfo);
2165
2166         if (copy_to_user(ip, &lineinfo, sizeof(lineinfo))) {
2167                 if (watch)
2168                         clear_bit(lineinfo.line_offset, cdev->watched_lines);
2169                 return -EFAULT;
2170         }
2171
2172         return 0;
2173 }
2174 #endif
2175
2176 static int lineinfo_get(struct gpio_chardev_data *cdev, void __user *ip,
2177                         bool watch)
2178 {
2179         struct gpio_desc *desc;
2180         struct gpio_v2_line_info lineinfo;
2181
2182         if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
2183                 return -EFAULT;
2184
2185         if (memchr_inv(lineinfo.padding, 0, sizeof(lineinfo.padding)))
2186                 return -EINVAL;
2187
2188         desc = gpiochip_get_desc(cdev->gdev->chip, lineinfo.offset);
2189         if (IS_ERR(desc))
2190                 return PTR_ERR(desc);
2191
2192         if (watch) {
2193 #ifdef CONFIG_GPIO_CDEV_V1
2194                 if (lineinfo_ensure_abi_version(cdev, 2))
2195                         return -EPERM;
2196 #endif
2197                 if (test_and_set_bit(lineinfo.offset, cdev->watched_lines))
2198                         return -EBUSY;
2199         }
2200         gpio_desc_to_lineinfo(desc, &lineinfo);
2201
2202         if (copy_to_user(ip, &lineinfo, sizeof(lineinfo))) {
2203                 if (watch)
2204                         clear_bit(lineinfo.offset, cdev->watched_lines);
2205                 return -EFAULT;
2206         }
2207
2208         return 0;
2209 }
2210
2211 static int lineinfo_unwatch(struct gpio_chardev_data *cdev, void __user *ip)
2212 {
2213         __u32 offset;
2214
2215         if (copy_from_user(&offset, ip, sizeof(offset)))
2216                 return -EFAULT;
2217
2218         if (offset >= cdev->gdev->ngpio)
2219                 return -EINVAL;
2220
2221         if (!test_and_clear_bit(offset, cdev->watched_lines))
2222                 return -EBUSY;
2223
2224         return 0;
2225 }
2226
2227 /*
2228  * gpio_ioctl() - ioctl handler for the GPIO chardev
2229  */
2230 static long gpio_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
2231 {
2232         struct gpio_chardev_data *cdev = file->private_data;
2233         struct gpio_device *gdev = cdev->gdev;
2234         void __user *ip = (void __user *)arg;
2235
2236         /* We fail any subsequent ioctl():s when the chip is gone */
2237         if (!gdev->chip)
2238                 return -ENODEV;
2239
2240         /* Fill in the struct and pass to userspace */
2241         switch (cmd) {
2242         case GPIO_GET_CHIPINFO_IOCTL:
2243                 return chipinfo_get(cdev, ip);
2244 #ifdef CONFIG_GPIO_CDEV_V1
2245         case GPIO_GET_LINEHANDLE_IOCTL:
2246                 return linehandle_create(gdev, ip);
2247         case GPIO_GET_LINEEVENT_IOCTL:
2248                 return lineevent_create(gdev, ip);
2249         case GPIO_GET_LINEINFO_IOCTL:
2250                 return lineinfo_get_v1(cdev, ip, false);
2251         case GPIO_GET_LINEINFO_WATCH_IOCTL:
2252                 return lineinfo_get_v1(cdev, ip, true);
2253 #endif /* CONFIG_GPIO_CDEV_V1 */
2254         case GPIO_V2_GET_LINEINFO_IOCTL:
2255                 return lineinfo_get(cdev, ip, false);
2256         case GPIO_V2_GET_LINEINFO_WATCH_IOCTL:
2257                 return lineinfo_get(cdev, ip, true);
2258         case GPIO_V2_GET_LINE_IOCTL:
2259                 return linereq_create(gdev, ip);
2260         case GPIO_GET_LINEINFO_UNWATCH_IOCTL:
2261                 return lineinfo_unwatch(cdev, ip);
2262         default:
2263                 return -EINVAL;
2264         }
2265 }
2266
2267 #ifdef CONFIG_COMPAT
2268 static long gpio_ioctl_compat(struct file *file, unsigned int cmd,
2269                               unsigned long arg)
2270 {
2271         return gpio_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
2272 }
2273 #endif
2274
2275 static struct gpio_chardev_data *
2276 to_gpio_chardev_data(struct notifier_block *nb)
2277 {
2278         return container_of(nb, struct gpio_chardev_data, lineinfo_changed_nb);
2279 }
2280
2281 static int lineinfo_changed_notify(struct notifier_block *nb,
2282                                    unsigned long action, void *data)
2283 {
2284         struct gpio_chardev_data *cdev = to_gpio_chardev_data(nb);
2285         struct gpio_v2_line_info_changed chg;
2286         struct gpio_desc *desc = data;
2287         int ret;
2288
2289         if (!test_bit(gpio_chip_hwgpio(desc), cdev->watched_lines))
2290                 return NOTIFY_DONE;
2291
2292         memset(&chg, 0, sizeof(chg));
2293         chg.event_type = action;
2294         chg.timestamp_ns = ktime_get_ns();
2295         gpio_desc_to_lineinfo(desc, &chg.info);
2296
2297         ret = kfifo_in_spinlocked(&cdev->events, &chg, 1, &cdev->wait.lock);
2298         if (ret)
2299                 wake_up_poll(&cdev->wait, EPOLLIN);
2300         else
2301                 pr_debug_ratelimited("lineinfo event FIFO is full - event dropped\n");
2302
2303         return NOTIFY_OK;
2304 }
2305
2306 static __poll_t lineinfo_watch_poll_unlocked(struct file *file,
2307                                              struct poll_table_struct *pollt)
2308 {
2309         struct gpio_chardev_data *cdev = file->private_data;
2310         __poll_t events = 0;
2311
2312         if (!cdev->gdev->chip)
2313                 return EPOLLHUP | EPOLLERR;
2314
2315         poll_wait(file, &cdev->wait, pollt);
2316
2317         if (!kfifo_is_empty_spinlocked_noirqsave(&cdev->events,
2318                                                  &cdev->wait.lock))
2319                 events = EPOLLIN | EPOLLRDNORM;
2320
2321         return events;
2322 }
2323
2324 static __poll_t lineinfo_watch_poll(struct file *file,
2325                                     struct poll_table_struct *pollt)
2326 {
2327         struct gpio_chardev_data *cdev = file->private_data;
2328
2329         return call_poll_locked(file, pollt, cdev->gdev,
2330                                 lineinfo_watch_poll_unlocked);
2331 }
2332
2333 static ssize_t lineinfo_watch_read_unlocked(struct file *file, char __user *buf,
2334                                             size_t count, loff_t *off)
2335 {
2336         struct gpio_chardev_data *cdev = file->private_data;
2337         struct gpio_v2_line_info_changed event;
2338         ssize_t bytes_read = 0;
2339         int ret;
2340         size_t event_size;
2341
2342         if (!cdev->gdev->chip)
2343                 return -ENODEV;
2344
2345 #ifndef CONFIG_GPIO_CDEV_V1
2346         event_size = sizeof(struct gpio_v2_line_info_changed);
2347         if (count < event_size)
2348                 return -EINVAL;
2349 #endif
2350
2351         do {
2352                 spin_lock(&cdev->wait.lock);
2353                 if (kfifo_is_empty(&cdev->events)) {
2354                         if (bytes_read) {
2355                                 spin_unlock(&cdev->wait.lock);
2356                                 return bytes_read;
2357                         }
2358
2359                         if (file->f_flags & O_NONBLOCK) {
2360                                 spin_unlock(&cdev->wait.lock);
2361                                 return -EAGAIN;
2362                         }
2363
2364                         ret = wait_event_interruptible_locked(cdev->wait,
2365                                         !kfifo_is_empty(&cdev->events));
2366                         if (ret) {
2367                                 spin_unlock(&cdev->wait.lock);
2368                                 return ret;
2369                         }
2370                 }
2371 #ifdef CONFIG_GPIO_CDEV_V1
2372                 /* must be after kfifo check so watch_abi_version is set */
2373                 if (atomic_read(&cdev->watch_abi_version) == 2)
2374                         event_size = sizeof(struct gpio_v2_line_info_changed);
2375                 else
2376                         event_size = sizeof(struct gpioline_info_changed);
2377                 if (count < event_size) {
2378                         spin_unlock(&cdev->wait.lock);
2379                         return -EINVAL;
2380                 }
2381 #endif
2382                 ret = kfifo_out(&cdev->events, &event, 1);
2383                 spin_unlock(&cdev->wait.lock);
2384                 if (ret != 1) {
2385                         ret = -EIO;
2386                         break;
2387                         /* We should never get here. See lineevent_read(). */
2388                 }
2389
2390 #ifdef CONFIG_GPIO_CDEV_V1
2391                 if (event_size == sizeof(struct gpio_v2_line_info_changed)) {
2392                         if (copy_to_user(buf + bytes_read, &event, event_size))
2393                                 return -EFAULT;
2394                 } else {
2395                         struct gpioline_info_changed event_v1;
2396
2397                         gpio_v2_line_info_changed_to_v1(&event, &event_v1);
2398                         if (copy_to_user(buf + bytes_read, &event_v1,
2399                                          event_size))
2400                                 return -EFAULT;
2401                 }
2402 #else
2403                 if (copy_to_user(buf + bytes_read, &event, event_size))
2404                         return -EFAULT;
2405 #endif
2406                 bytes_read += event_size;
2407         } while (count >= bytes_read + sizeof(event));
2408
2409         return bytes_read;
2410 }
2411
2412 static ssize_t lineinfo_watch_read(struct file *file, char __user *buf,
2413                                    size_t count, loff_t *off)
2414 {
2415         struct gpio_chardev_data *cdev = file->private_data;
2416
2417         return call_read_locked(file, buf, count, off, cdev->gdev,
2418                                 lineinfo_watch_read_unlocked);
2419 }
2420
2421 /**
2422  * gpio_chrdev_open() - open the chardev for ioctl operations
2423  * @inode: inode for this chardev
2424  * @file: file struct for storing private data
2425  * Returns 0 on success
2426  */
2427 static int gpio_chrdev_open(struct inode *inode, struct file *file)
2428 {
2429         struct gpio_device *gdev = container_of(inode->i_cdev,
2430                                                 struct gpio_device, chrdev);
2431         struct gpio_chardev_data *cdev;
2432         int ret = -ENOMEM;
2433
2434         down_read(&gdev->sem);
2435
2436         /* Fail on open if the backing gpiochip is gone */
2437         if (!gdev->chip) {
2438                 ret = -ENODEV;
2439                 goto out_unlock;
2440         }
2441
2442         cdev = kzalloc(sizeof(*cdev), GFP_KERNEL);
2443         if (!cdev)
2444                 goto out_unlock;
2445
2446         cdev->watched_lines = bitmap_zalloc(gdev->chip->ngpio, GFP_KERNEL);
2447         if (!cdev->watched_lines)
2448                 goto out_free_cdev;
2449
2450         init_waitqueue_head(&cdev->wait);
2451         INIT_KFIFO(cdev->events);
2452         cdev->gdev = gdev;
2453
2454         cdev->lineinfo_changed_nb.notifier_call = lineinfo_changed_notify;
2455         ret = blocking_notifier_chain_register(&gdev->notifier,
2456                                                &cdev->lineinfo_changed_nb);
2457         if (ret)
2458                 goto out_free_bitmap;
2459
2460         get_device(&gdev->dev);
2461         file->private_data = cdev;
2462
2463         ret = nonseekable_open(inode, file);
2464         if (ret)
2465                 goto out_unregister_notifier;
2466
2467         up_read(&gdev->sem);
2468
2469         return ret;
2470
2471 out_unregister_notifier:
2472         blocking_notifier_chain_unregister(&gdev->notifier,
2473                                            &cdev->lineinfo_changed_nb);
2474 out_free_bitmap:
2475         bitmap_free(cdev->watched_lines);
2476 out_free_cdev:
2477         kfree(cdev);
2478 out_unlock:
2479         up_read(&gdev->sem);
2480         return ret;
2481 }
2482
2483 /**
2484  * gpio_chrdev_release() - close chardev after ioctl operations
2485  * @inode: inode for this chardev
2486  * @file: file struct for storing private data
2487  * Returns 0 on success
2488  */
2489 static int gpio_chrdev_release(struct inode *inode, struct file *file)
2490 {
2491         struct gpio_chardev_data *cdev = file->private_data;
2492         struct gpio_device *gdev = cdev->gdev;
2493
2494         bitmap_free(cdev->watched_lines);
2495         blocking_notifier_chain_unregister(&gdev->notifier,
2496                                            &cdev->lineinfo_changed_nb);
2497         put_device(&gdev->dev);
2498         kfree(cdev);
2499
2500         return 0;
2501 }
2502
2503 static const struct file_operations gpio_fileops = {
2504         .release = gpio_chrdev_release,
2505         .open = gpio_chrdev_open,
2506         .poll = lineinfo_watch_poll,
2507         .read = lineinfo_watch_read,
2508         .owner = THIS_MODULE,
2509         .llseek = no_llseek,
2510         .unlocked_ioctl = gpio_ioctl,
2511 #ifdef CONFIG_COMPAT
2512         .compat_ioctl = gpio_ioctl_compat,
2513 #endif
2514 };
2515
2516 int gpiolib_cdev_register(struct gpio_device *gdev, dev_t devt)
2517 {
2518         int ret;
2519
2520         cdev_init(&gdev->chrdev, &gpio_fileops);
2521         gdev->chrdev.owner = THIS_MODULE;
2522         gdev->dev.devt = MKDEV(MAJOR(devt), gdev->id);
2523
2524         ret = cdev_device_add(&gdev->chrdev, &gdev->dev);
2525         if (ret)
2526                 return ret;
2527
2528         chip_dbg(gdev->chip, "added GPIO chardev (%d:%d)\n",
2529                  MAJOR(devt), gdev->id);
2530
2531         return 0;
2532 }
2533
2534 void gpiolib_cdev_unregister(struct gpio_device *gdev)
2535 {
2536         cdev_device_del(&gdev->chrdev, &gdev->dev);
2537 }