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