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