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