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