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