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