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