xref: /openbmc/linux/drivers/gpio/gpiolib-cdev.c (revision 309364bc3205b36c2dd6a13ac04d1ea8b681e193)
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 active_edflags = READ_ONCE(line->edflags);
1247 	unsigned int debounce_period_us =
1248 			gpio_v2_line_config_debounce_period(lc, line_idx);
1249 
1250 	if ((active_edflags == edflags) &&
1251 	    (READ_ONCE(line->debounce_period_us) == debounce_period_us))
1252 		return 0;
1253 
1254 	/* sw debounced and still will be...*/
1255 	if (debounce_period_us && READ_ONCE(line->sw_debounced)) {
1256 		line_set_debounce_period(line, debounce_period_us);
1257 		return 0;
1258 	}
1259 
1260 	/* reconfiguring edge detection or sw debounce being disabled */
1261 	if ((line->irq && !READ_ONCE(line->sw_debounced)) ||
1262 	    (active_edflags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE) ||
1263 	    (!debounce_period_us && READ_ONCE(line->sw_debounced)))
1264 		edge_detector_stop(line);
1265 
1266 	return edge_detector_setup(line, lc, line_idx, edflags);
1267 }
1268 
1269 static u64 gpio_v2_line_config_flags(struct gpio_v2_line_config *lc,
1270 				     unsigned int line_idx)
1271 {
1272 	unsigned int i;
1273 	u64 mask = BIT_ULL(line_idx);
1274 
1275 	for (i = 0; i < lc->num_attrs; i++) {
1276 		if ((lc->attrs[i].attr.id == GPIO_V2_LINE_ATTR_ID_FLAGS) &&
1277 		    (lc->attrs[i].mask & mask))
1278 			return lc->attrs[i].attr.flags;
1279 	}
1280 	return lc->flags;
1281 }
1282 
1283 static int gpio_v2_line_config_output_value(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_OUTPUT_VALUES) &&
1291 		    (lc->attrs[i].mask & mask))
1292 			return !!(lc->attrs[i].attr.values & mask);
1293 	}
1294 	return 0;
1295 }
1296 
1297 static int gpio_v2_line_flags_validate(u64 flags)
1298 {
1299 	/* Return an error if an unknown flag is set */
1300 	if (flags & ~GPIO_V2_LINE_VALID_FLAGS)
1301 		return -EINVAL;
1302 
1303 	if (!IS_ENABLED(CONFIG_HTE) &&
1304 	    (flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE))
1305 		return -EOPNOTSUPP;
1306 
1307 	/*
1308 	 * Do not allow both INPUT and OUTPUT flags to be set as they are
1309 	 * contradictory.
1310 	 */
1311 	if ((flags & GPIO_V2_LINE_FLAG_INPUT) &&
1312 	    (flags & GPIO_V2_LINE_FLAG_OUTPUT))
1313 		return -EINVAL;
1314 
1315 	/* Only allow one event clock source */
1316 	if (IS_ENABLED(CONFIG_HTE) &&
1317 	    (flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME) &&
1318 	    (flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE))
1319 		return -EINVAL;
1320 
1321 	/* Edge detection requires explicit input. */
1322 	if ((flags & GPIO_V2_LINE_EDGE_FLAGS) &&
1323 	    !(flags & GPIO_V2_LINE_FLAG_INPUT))
1324 		return -EINVAL;
1325 
1326 	/*
1327 	 * Do not allow OPEN_SOURCE and OPEN_DRAIN flags in a single
1328 	 * request. If the hardware actually supports enabling both at the
1329 	 * same time the electrical result would be disastrous.
1330 	 */
1331 	if ((flags & GPIO_V2_LINE_FLAG_OPEN_DRAIN) &&
1332 	    (flags & GPIO_V2_LINE_FLAG_OPEN_SOURCE))
1333 		return -EINVAL;
1334 
1335 	/* Drive requires explicit output direction. */
1336 	if ((flags & GPIO_V2_LINE_DRIVE_FLAGS) &&
1337 	    !(flags & GPIO_V2_LINE_FLAG_OUTPUT))
1338 		return -EINVAL;
1339 
1340 	/* Bias requires explicit direction. */
1341 	if ((flags & GPIO_V2_LINE_BIAS_FLAGS) &&
1342 	    !(flags & GPIO_V2_LINE_DIRECTION_FLAGS))
1343 		return -EINVAL;
1344 
1345 	/* Only one bias flag can be set. */
1346 	if (((flags & GPIO_V2_LINE_FLAG_BIAS_DISABLED) &&
1347 	     (flags & (GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN |
1348 		       GPIO_V2_LINE_FLAG_BIAS_PULL_UP))) ||
1349 	    ((flags & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN) &&
1350 	     (flags & GPIO_V2_LINE_FLAG_BIAS_PULL_UP)))
1351 		return -EINVAL;
1352 
1353 	return 0;
1354 }
1355 
1356 static int gpio_v2_line_config_validate(struct gpio_v2_line_config *lc,
1357 					unsigned int num_lines)
1358 {
1359 	unsigned int i;
1360 	u64 flags;
1361 	int ret;
1362 
1363 	if (lc->num_attrs > GPIO_V2_LINE_NUM_ATTRS_MAX)
1364 		return -EINVAL;
1365 
1366 	if (memchr_inv(lc->padding, 0, sizeof(lc->padding)))
1367 		return -EINVAL;
1368 
1369 	for (i = 0; i < num_lines; i++) {
1370 		flags = gpio_v2_line_config_flags(lc, i);
1371 		ret = gpio_v2_line_flags_validate(flags);
1372 		if (ret)
1373 			return ret;
1374 
1375 		/* debounce requires explicit input */
1376 		if (gpio_v2_line_config_debounced(lc, i) &&
1377 		    !(flags & GPIO_V2_LINE_FLAG_INPUT))
1378 			return -EINVAL;
1379 	}
1380 	return 0;
1381 }
1382 
1383 static void gpio_v2_line_config_flags_to_desc_flags(u64 flags,
1384 						    unsigned long *flagsp)
1385 {
1386 	assign_bit(FLAG_ACTIVE_LOW, flagsp,
1387 		   flags & GPIO_V2_LINE_FLAG_ACTIVE_LOW);
1388 
1389 	if (flags & GPIO_V2_LINE_FLAG_OUTPUT)
1390 		set_bit(FLAG_IS_OUT, flagsp);
1391 	else if (flags & GPIO_V2_LINE_FLAG_INPUT)
1392 		clear_bit(FLAG_IS_OUT, flagsp);
1393 
1394 	assign_bit(FLAG_EDGE_RISING, flagsp,
1395 		   flags & GPIO_V2_LINE_FLAG_EDGE_RISING);
1396 	assign_bit(FLAG_EDGE_FALLING, flagsp,
1397 		   flags & GPIO_V2_LINE_FLAG_EDGE_FALLING);
1398 
1399 	assign_bit(FLAG_OPEN_DRAIN, flagsp,
1400 		   flags & GPIO_V2_LINE_FLAG_OPEN_DRAIN);
1401 	assign_bit(FLAG_OPEN_SOURCE, flagsp,
1402 		   flags & GPIO_V2_LINE_FLAG_OPEN_SOURCE);
1403 
1404 	assign_bit(FLAG_PULL_UP, flagsp,
1405 		   flags & GPIO_V2_LINE_FLAG_BIAS_PULL_UP);
1406 	assign_bit(FLAG_PULL_DOWN, flagsp,
1407 		   flags & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN);
1408 	assign_bit(FLAG_BIAS_DISABLE, flagsp,
1409 		   flags & GPIO_V2_LINE_FLAG_BIAS_DISABLED);
1410 
1411 	assign_bit(FLAG_EVENT_CLOCK_REALTIME, flagsp,
1412 		   flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME);
1413 	assign_bit(FLAG_EVENT_CLOCK_HTE, flagsp,
1414 		   flags & GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE);
1415 }
1416 
1417 static long linereq_get_values(struct linereq *lr, void __user *ip)
1418 {
1419 	struct gpio_v2_line_values lv;
1420 	DECLARE_BITMAP(vals, GPIO_V2_LINES_MAX);
1421 	struct gpio_desc **descs;
1422 	unsigned int i, didx, num_get;
1423 	bool val;
1424 	int ret;
1425 
1426 	/* NOTE: It's ok to read values of output lines. */
1427 	if (copy_from_user(&lv, ip, sizeof(lv)))
1428 		return -EFAULT;
1429 
1430 	for (num_get = 0, i = 0; i < lr->num_lines; i++) {
1431 		if (lv.mask & BIT_ULL(i)) {
1432 			num_get++;
1433 			descs = &lr->lines[i].desc;
1434 		}
1435 	}
1436 
1437 	if (num_get == 0)
1438 		return -EINVAL;
1439 
1440 	if (num_get != 1) {
1441 		descs = kmalloc_array(num_get, sizeof(*descs), GFP_KERNEL);
1442 		if (!descs)
1443 			return -ENOMEM;
1444 		for (didx = 0, i = 0; i < lr->num_lines; i++) {
1445 			if (lv.mask & BIT_ULL(i)) {
1446 				descs[didx] = lr->lines[i].desc;
1447 				didx++;
1448 			}
1449 		}
1450 	}
1451 	ret = gpiod_get_array_value_complex(false, true, num_get,
1452 					    descs, NULL, vals);
1453 
1454 	if (num_get != 1)
1455 		kfree(descs);
1456 	if (ret)
1457 		return ret;
1458 
1459 	lv.bits = 0;
1460 	for (didx = 0, i = 0; i < lr->num_lines; i++) {
1461 		if (lv.mask & BIT_ULL(i)) {
1462 			if (lr->lines[i].sw_debounced)
1463 				val = debounced_value(&lr->lines[i]);
1464 			else
1465 				val = test_bit(didx, vals);
1466 			if (val)
1467 				lv.bits |= BIT_ULL(i);
1468 			didx++;
1469 		}
1470 	}
1471 
1472 	if (copy_to_user(ip, &lv, sizeof(lv)))
1473 		return -EFAULT;
1474 
1475 	return 0;
1476 }
1477 
1478 static long linereq_set_values_unlocked(struct linereq *lr,
1479 					struct gpio_v2_line_values *lv)
1480 {
1481 	DECLARE_BITMAP(vals, GPIO_V2_LINES_MAX);
1482 	struct gpio_desc **descs;
1483 	unsigned int i, didx, num_set;
1484 	int ret;
1485 
1486 	bitmap_zero(vals, GPIO_V2_LINES_MAX);
1487 	for (num_set = 0, i = 0; i < lr->num_lines; i++) {
1488 		if (lv->mask & BIT_ULL(i)) {
1489 			if (!test_bit(FLAG_IS_OUT, &lr->lines[i].desc->flags))
1490 				return -EPERM;
1491 			if (lv->bits & BIT_ULL(i))
1492 				__set_bit(num_set, vals);
1493 			num_set++;
1494 			descs = &lr->lines[i].desc;
1495 		}
1496 	}
1497 	if (num_set == 0)
1498 		return -EINVAL;
1499 
1500 	if (num_set != 1) {
1501 		/* build compacted desc array and values */
1502 		descs = kmalloc_array(num_set, sizeof(*descs), GFP_KERNEL);
1503 		if (!descs)
1504 			return -ENOMEM;
1505 		for (didx = 0, i = 0; i < lr->num_lines; i++) {
1506 			if (lv->mask & BIT_ULL(i)) {
1507 				descs[didx] = lr->lines[i].desc;
1508 				didx++;
1509 			}
1510 		}
1511 	}
1512 	ret = gpiod_set_array_value_complex(false, true, num_set,
1513 					    descs, NULL, vals);
1514 
1515 	if (num_set != 1)
1516 		kfree(descs);
1517 	return ret;
1518 }
1519 
1520 static long linereq_set_values(struct linereq *lr, void __user *ip)
1521 {
1522 	struct gpio_v2_line_values lv;
1523 	int ret;
1524 
1525 	if (copy_from_user(&lv, ip, sizeof(lv)))
1526 		return -EFAULT;
1527 
1528 	mutex_lock(&lr->config_mutex);
1529 
1530 	ret = linereq_set_values_unlocked(lr, &lv);
1531 
1532 	mutex_unlock(&lr->config_mutex);
1533 
1534 	return ret;
1535 }
1536 
1537 static long linereq_set_config_unlocked(struct linereq *lr,
1538 					struct gpio_v2_line_config *lc)
1539 {
1540 	struct gpio_desc *desc;
1541 	struct line *line;
1542 	unsigned int i;
1543 	u64 flags, edflags;
1544 	int ret;
1545 
1546 	for (i = 0; i < lr->num_lines; i++) {
1547 		line = &lr->lines[i];
1548 		desc = lr->lines[i].desc;
1549 		flags = gpio_v2_line_config_flags(lc, i);
1550 		gpio_v2_line_config_flags_to_desc_flags(flags, &desc->flags);
1551 		edflags = flags & GPIO_V2_LINE_EDGE_DETECTOR_FLAGS;
1552 		/*
1553 		 * Lines have to be requested explicitly for input
1554 		 * or output, else the line will be treated "as is".
1555 		 */
1556 		if (flags & GPIO_V2_LINE_FLAG_OUTPUT) {
1557 			int val = gpio_v2_line_config_output_value(lc, i);
1558 
1559 			edge_detector_stop(line);
1560 			ret = gpiod_direction_output(desc, val);
1561 			if (ret)
1562 				return ret;
1563 		} else if (flags & GPIO_V2_LINE_FLAG_INPUT) {
1564 			ret = gpiod_direction_input(desc);
1565 			if (ret)
1566 				return ret;
1567 
1568 			ret = edge_detector_update(line, lc, i, edflags);
1569 			if (ret)
1570 				return ret;
1571 		}
1572 
1573 		WRITE_ONCE(line->edflags, edflags);
1574 
1575 		gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_CONFIG);
1576 	}
1577 	return 0;
1578 }
1579 
1580 static long linereq_set_config(struct linereq *lr, void __user *ip)
1581 {
1582 	struct gpio_v2_line_config lc;
1583 	int ret;
1584 
1585 	if (copy_from_user(&lc, ip, sizeof(lc)))
1586 		return -EFAULT;
1587 
1588 	ret = gpio_v2_line_config_validate(&lc, lr->num_lines);
1589 	if (ret)
1590 		return ret;
1591 
1592 	mutex_lock(&lr->config_mutex);
1593 
1594 	ret = linereq_set_config_unlocked(lr, &lc);
1595 
1596 	mutex_unlock(&lr->config_mutex);
1597 
1598 	return ret;
1599 }
1600 
1601 static long linereq_ioctl_unlocked(struct file *file, unsigned int cmd,
1602 				   unsigned long arg)
1603 {
1604 	struct linereq *lr = file->private_data;
1605 	void __user *ip = (void __user *)arg;
1606 
1607 	if (!lr->gdev->chip)
1608 		return -ENODEV;
1609 
1610 	switch (cmd) {
1611 	case GPIO_V2_LINE_GET_VALUES_IOCTL:
1612 		return linereq_get_values(lr, ip);
1613 	case GPIO_V2_LINE_SET_VALUES_IOCTL:
1614 		return linereq_set_values(lr, ip);
1615 	case GPIO_V2_LINE_SET_CONFIG_IOCTL:
1616 		return linereq_set_config(lr, ip);
1617 	default:
1618 		return -EINVAL;
1619 	}
1620 }
1621 
1622 static long linereq_ioctl(struct file *file, unsigned int cmd,
1623 			  unsigned long arg)
1624 {
1625 	struct linereq *lr = file->private_data;
1626 
1627 	return call_ioctl_locked(file, cmd, arg, lr->gdev,
1628 				 linereq_ioctl_unlocked);
1629 }
1630 
1631 #ifdef CONFIG_COMPAT
1632 static long linereq_ioctl_compat(struct file *file, unsigned int cmd,
1633 				 unsigned long arg)
1634 {
1635 	return linereq_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
1636 }
1637 #endif
1638 
1639 static __poll_t linereq_poll_unlocked(struct file *file,
1640 				      struct poll_table_struct *wait)
1641 {
1642 	struct linereq *lr = file->private_data;
1643 	__poll_t events = 0;
1644 
1645 	if (!lr->gdev->chip)
1646 		return EPOLLHUP | EPOLLERR;
1647 
1648 	poll_wait(file, &lr->wait, wait);
1649 
1650 	if (!kfifo_is_empty_spinlocked_noirqsave(&lr->events,
1651 						 &lr->wait.lock))
1652 		events = EPOLLIN | EPOLLRDNORM;
1653 
1654 	return events;
1655 }
1656 
1657 static __poll_t linereq_poll(struct file *file,
1658 			     struct poll_table_struct *wait)
1659 {
1660 	struct linereq *lr = file->private_data;
1661 
1662 	return call_poll_locked(file, wait, lr->gdev, linereq_poll_unlocked);
1663 }
1664 
1665 static ssize_t linereq_read_unlocked(struct file *file, char __user *buf,
1666 				     size_t count, loff_t *f_ps)
1667 {
1668 	struct linereq *lr = file->private_data;
1669 	struct gpio_v2_line_event le;
1670 	ssize_t bytes_read = 0;
1671 	int ret;
1672 
1673 	if (!lr->gdev->chip)
1674 		return -ENODEV;
1675 
1676 	if (count < sizeof(le))
1677 		return -EINVAL;
1678 
1679 	do {
1680 		spin_lock(&lr->wait.lock);
1681 		if (kfifo_is_empty(&lr->events)) {
1682 			if (bytes_read) {
1683 				spin_unlock(&lr->wait.lock);
1684 				return bytes_read;
1685 			}
1686 
1687 			if (file->f_flags & O_NONBLOCK) {
1688 				spin_unlock(&lr->wait.lock);
1689 				return -EAGAIN;
1690 			}
1691 
1692 			ret = wait_event_interruptible_locked(lr->wait,
1693 					!kfifo_is_empty(&lr->events));
1694 			if (ret) {
1695 				spin_unlock(&lr->wait.lock);
1696 				return ret;
1697 			}
1698 		}
1699 
1700 		ret = kfifo_out(&lr->events, &le, 1);
1701 		spin_unlock(&lr->wait.lock);
1702 		if (ret != 1) {
1703 			/*
1704 			 * This should never happen - we were holding the
1705 			 * lock from the moment we learned the fifo is no
1706 			 * longer empty until now.
1707 			 */
1708 			ret = -EIO;
1709 			break;
1710 		}
1711 
1712 		if (copy_to_user(buf + bytes_read, &le, sizeof(le)))
1713 			return -EFAULT;
1714 		bytes_read += sizeof(le);
1715 	} while (count >= bytes_read + sizeof(le));
1716 
1717 	return bytes_read;
1718 }
1719 
1720 static ssize_t linereq_read(struct file *file, char __user *buf,
1721 			    size_t count, loff_t *f_ps)
1722 {
1723 	struct linereq *lr = file->private_data;
1724 
1725 	return call_read_locked(file, buf, count, f_ps, lr->gdev,
1726 				linereq_read_unlocked);
1727 }
1728 
1729 static void linereq_free(struct linereq *lr)
1730 {
1731 	struct line *line;
1732 	unsigned int i;
1733 
1734 	if (lr->device_unregistered_nb.notifier_call)
1735 		blocking_notifier_chain_unregister(&lr->gdev->device_notifier,
1736 						   &lr->device_unregistered_nb);
1737 
1738 	for (i = 0; i < lr->num_lines; i++) {
1739 		line = &lr->lines[i];
1740 		if (!line->desc)
1741 			continue;
1742 
1743 		edge_detector_stop(line);
1744 		if (line_has_supinfo(line))
1745 			supinfo_erase(line);
1746 		gpiod_free(line->desc);
1747 	}
1748 	kfifo_free(&lr->events);
1749 	kfree(lr->label);
1750 	gpio_device_put(lr->gdev);
1751 	kfree(lr);
1752 }
1753 
1754 static int linereq_release(struct inode *inode, struct file *file)
1755 {
1756 	struct linereq *lr = file->private_data;
1757 
1758 	linereq_free(lr);
1759 	return 0;
1760 }
1761 
1762 #ifdef CONFIG_PROC_FS
1763 static void linereq_show_fdinfo(struct seq_file *out, struct file *file)
1764 {
1765 	struct linereq *lr = file->private_data;
1766 	struct device *dev = &lr->gdev->dev;
1767 	u16 i;
1768 
1769 	seq_printf(out, "gpio-chip:\t%s\n", dev_name(dev));
1770 
1771 	for (i = 0; i < lr->num_lines; i++)
1772 		seq_printf(out, "gpio-line:\t%d\n",
1773 			   gpio_chip_hwgpio(lr->lines[i].desc));
1774 }
1775 #endif
1776 
1777 static const struct file_operations line_fileops = {
1778 	.release = linereq_release,
1779 	.read = linereq_read,
1780 	.poll = linereq_poll,
1781 	.owner = THIS_MODULE,
1782 	.llseek = noop_llseek,
1783 	.unlocked_ioctl = linereq_ioctl,
1784 #ifdef CONFIG_COMPAT
1785 	.compat_ioctl = linereq_ioctl_compat,
1786 #endif
1787 #ifdef CONFIG_PROC_FS
1788 	.show_fdinfo = linereq_show_fdinfo,
1789 #endif
1790 };
1791 
1792 static int linereq_create(struct gpio_device *gdev, void __user *ip)
1793 {
1794 	struct gpio_v2_line_request ulr;
1795 	struct gpio_v2_line_config *lc;
1796 	struct linereq *lr;
1797 	struct file *file;
1798 	u64 flags, edflags;
1799 	unsigned int i;
1800 	int fd, ret;
1801 
1802 	if (copy_from_user(&ulr, ip, sizeof(ulr)))
1803 		return -EFAULT;
1804 
1805 	if ((ulr.num_lines == 0) || (ulr.num_lines > GPIO_V2_LINES_MAX))
1806 		return -EINVAL;
1807 
1808 	if (memchr_inv(ulr.padding, 0, sizeof(ulr.padding)))
1809 		return -EINVAL;
1810 
1811 	lc = &ulr.config;
1812 	ret = gpio_v2_line_config_validate(lc, ulr.num_lines);
1813 	if (ret)
1814 		return ret;
1815 
1816 	lr = kzalloc(struct_size(lr, lines, ulr.num_lines), GFP_KERNEL);
1817 	if (!lr)
1818 		return -ENOMEM;
1819 
1820 	lr->gdev = gpio_device_get(gdev);
1821 
1822 	for (i = 0; i < ulr.num_lines; i++) {
1823 		lr->lines[i].req = lr;
1824 		WRITE_ONCE(lr->lines[i].sw_debounced, 0);
1825 		INIT_DELAYED_WORK(&lr->lines[i].work, debounce_work_func);
1826 	}
1827 
1828 	if (ulr.consumer[0] != '\0') {
1829 		/* label is only initialized if consumer is set */
1830 		lr->label = kstrndup(ulr.consumer, sizeof(ulr.consumer) - 1,
1831 				     GFP_KERNEL);
1832 		if (!lr->label) {
1833 			ret = -ENOMEM;
1834 			goto out_free_linereq;
1835 		}
1836 	}
1837 
1838 	mutex_init(&lr->config_mutex);
1839 	init_waitqueue_head(&lr->wait);
1840 	lr->event_buffer_size = ulr.event_buffer_size;
1841 	if (lr->event_buffer_size == 0)
1842 		lr->event_buffer_size = ulr.num_lines * 16;
1843 	else if (lr->event_buffer_size > GPIO_V2_LINES_MAX * 16)
1844 		lr->event_buffer_size = GPIO_V2_LINES_MAX * 16;
1845 
1846 	atomic_set(&lr->seqno, 0);
1847 	lr->num_lines = ulr.num_lines;
1848 
1849 	/* Request each GPIO */
1850 	for (i = 0; i < ulr.num_lines; i++) {
1851 		u32 offset = ulr.offsets[i];
1852 		struct gpio_desc *desc = gpiochip_get_desc(gdev->chip, offset);
1853 
1854 		if (IS_ERR(desc)) {
1855 			ret = PTR_ERR(desc);
1856 			goto out_free_linereq;
1857 		}
1858 
1859 		ret = gpiod_request_user(desc, lr->label);
1860 		if (ret)
1861 			goto out_free_linereq;
1862 
1863 		lr->lines[i].desc = desc;
1864 		flags = gpio_v2_line_config_flags(lc, i);
1865 		gpio_v2_line_config_flags_to_desc_flags(flags, &desc->flags);
1866 
1867 		ret = gpiod_set_transitory(desc, false);
1868 		if (ret < 0)
1869 			goto out_free_linereq;
1870 
1871 		edflags = flags & GPIO_V2_LINE_EDGE_DETECTOR_FLAGS;
1872 		/*
1873 		 * Lines have to be requested explicitly for input
1874 		 * or output, else the line will be treated "as is".
1875 		 */
1876 		if (flags & GPIO_V2_LINE_FLAG_OUTPUT) {
1877 			int val = gpio_v2_line_config_output_value(lc, i);
1878 
1879 			ret = gpiod_direction_output(desc, val);
1880 			if (ret)
1881 				goto out_free_linereq;
1882 		} else if (flags & GPIO_V2_LINE_FLAG_INPUT) {
1883 			ret = gpiod_direction_input(desc);
1884 			if (ret)
1885 				goto out_free_linereq;
1886 
1887 			ret = edge_detector_setup(&lr->lines[i], lc, i,
1888 						  edflags);
1889 			if (ret)
1890 				goto out_free_linereq;
1891 		}
1892 
1893 		lr->lines[i].edflags = edflags;
1894 
1895 		gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_REQUESTED);
1896 
1897 		dev_dbg(&gdev->dev, "registered chardev handle for line %d\n",
1898 			offset);
1899 	}
1900 
1901 	lr->device_unregistered_nb.notifier_call = linereq_unregistered_notify;
1902 	ret = blocking_notifier_chain_register(&gdev->device_notifier,
1903 					       &lr->device_unregistered_nb);
1904 	if (ret)
1905 		goto out_free_linereq;
1906 
1907 	fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
1908 	if (fd < 0) {
1909 		ret = fd;
1910 		goto out_free_linereq;
1911 	}
1912 
1913 	file = anon_inode_getfile("gpio-line", &line_fileops, lr,
1914 				  O_RDONLY | O_CLOEXEC);
1915 	if (IS_ERR(file)) {
1916 		ret = PTR_ERR(file);
1917 		goto out_put_unused_fd;
1918 	}
1919 
1920 	ulr.fd = fd;
1921 	if (copy_to_user(ip, &ulr, sizeof(ulr))) {
1922 		/*
1923 		 * fput() will trigger the release() callback, so do not go onto
1924 		 * the regular error cleanup path here.
1925 		 */
1926 		fput(file);
1927 		put_unused_fd(fd);
1928 		return -EFAULT;
1929 	}
1930 
1931 	fd_install(fd, file);
1932 
1933 	dev_dbg(&gdev->dev, "registered chardev handle for %d lines\n",
1934 		lr->num_lines);
1935 
1936 	return 0;
1937 
1938 out_put_unused_fd:
1939 	put_unused_fd(fd);
1940 out_free_linereq:
1941 	linereq_free(lr);
1942 	return ret;
1943 }
1944 
1945 #ifdef CONFIG_GPIO_CDEV_V1
1946 
1947 /*
1948  * GPIO line event management
1949  */
1950 
1951 /**
1952  * struct lineevent_state - contains the state of a userspace event
1953  * @gdev: the GPIO device the event pertains to
1954  * @label: consumer label used to tag descriptors
1955  * @desc: the GPIO descriptor held by this event
1956  * @eflags: the event flags this line was requested with
1957  * @irq: the interrupt that trigger in response to events on this GPIO
1958  * @wait: wait queue that handles blocking reads of events
1959  * @device_unregistered_nb: notifier block for receiving gdev unregister events
1960  * @events: KFIFO for the GPIO events
1961  * @timestamp: cache for the timestamp storing it between hardirq
1962  * and IRQ thread, used to bring the timestamp close to the actual
1963  * event
1964  */
1965 struct lineevent_state {
1966 	struct gpio_device *gdev;
1967 	const char *label;
1968 	struct gpio_desc *desc;
1969 	u32 eflags;
1970 	int irq;
1971 	wait_queue_head_t wait;
1972 	struct notifier_block device_unregistered_nb;
1973 	DECLARE_KFIFO(events, struct gpioevent_data, 16);
1974 	u64 timestamp;
1975 };
1976 
1977 #define GPIOEVENT_REQUEST_VALID_FLAGS \
1978 	(GPIOEVENT_REQUEST_RISING_EDGE | \
1979 	GPIOEVENT_REQUEST_FALLING_EDGE)
1980 
1981 static __poll_t lineevent_poll_unlocked(struct file *file,
1982 					struct poll_table_struct *wait)
1983 {
1984 	struct lineevent_state *le = file->private_data;
1985 	__poll_t events = 0;
1986 
1987 	if (!le->gdev->chip)
1988 		return EPOLLHUP | EPOLLERR;
1989 
1990 	poll_wait(file, &le->wait, wait);
1991 
1992 	if (!kfifo_is_empty_spinlocked_noirqsave(&le->events, &le->wait.lock))
1993 		events = EPOLLIN | EPOLLRDNORM;
1994 
1995 	return events;
1996 }
1997 
1998 static __poll_t lineevent_poll(struct file *file,
1999 			       struct poll_table_struct *wait)
2000 {
2001 	struct lineevent_state *le = file->private_data;
2002 
2003 	return call_poll_locked(file, wait, le->gdev, lineevent_poll_unlocked);
2004 }
2005 
2006 static int lineevent_unregistered_notify(struct notifier_block *nb,
2007 					 unsigned long action, void *data)
2008 {
2009 	struct lineevent_state *le = container_of(nb, struct lineevent_state,
2010 						  device_unregistered_nb);
2011 
2012 	wake_up_poll(&le->wait, EPOLLIN | EPOLLERR);
2013 
2014 	return NOTIFY_OK;
2015 }
2016 
2017 struct compat_gpioeevent_data {
2018 	compat_u64	timestamp;
2019 	u32		id;
2020 };
2021 
2022 static ssize_t lineevent_read_unlocked(struct file *file, char __user *buf,
2023 				       size_t count, loff_t *f_ps)
2024 {
2025 	struct lineevent_state *le = file->private_data;
2026 	struct gpioevent_data ge;
2027 	ssize_t bytes_read = 0;
2028 	ssize_t ge_size;
2029 	int ret;
2030 
2031 	if (!le->gdev->chip)
2032 		return -ENODEV;
2033 
2034 	/*
2035 	 * When compatible system call is being used the struct gpioevent_data,
2036 	 * in case of at least ia32, has different size due to the alignment
2037 	 * differences. Because we have first member 64 bits followed by one of
2038 	 * 32 bits there is no gap between them. The only difference is the
2039 	 * padding at the end of the data structure. Hence, we calculate the
2040 	 * actual sizeof() and pass this as an argument to copy_to_user() to
2041 	 * drop unneeded bytes from the output.
2042 	 */
2043 	if (compat_need_64bit_alignment_fixup())
2044 		ge_size = sizeof(struct compat_gpioeevent_data);
2045 	else
2046 		ge_size = sizeof(struct gpioevent_data);
2047 	if (count < ge_size)
2048 		return -EINVAL;
2049 
2050 	do {
2051 		spin_lock(&le->wait.lock);
2052 		if (kfifo_is_empty(&le->events)) {
2053 			if (bytes_read) {
2054 				spin_unlock(&le->wait.lock);
2055 				return bytes_read;
2056 			}
2057 
2058 			if (file->f_flags & O_NONBLOCK) {
2059 				spin_unlock(&le->wait.lock);
2060 				return -EAGAIN;
2061 			}
2062 
2063 			ret = wait_event_interruptible_locked(le->wait,
2064 					!kfifo_is_empty(&le->events));
2065 			if (ret) {
2066 				spin_unlock(&le->wait.lock);
2067 				return ret;
2068 			}
2069 		}
2070 
2071 		ret = kfifo_out(&le->events, &ge, 1);
2072 		spin_unlock(&le->wait.lock);
2073 		if (ret != 1) {
2074 			/*
2075 			 * This should never happen - we were holding the lock
2076 			 * from the moment we learned the fifo is no longer
2077 			 * empty until now.
2078 			 */
2079 			ret = -EIO;
2080 			break;
2081 		}
2082 
2083 		if (copy_to_user(buf + bytes_read, &ge, ge_size))
2084 			return -EFAULT;
2085 		bytes_read += ge_size;
2086 	} while (count >= bytes_read + ge_size);
2087 
2088 	return bytes_read;
2089 }
2090 
2091 static ssize_t lineevent_read(struct file *file, char __user *buf,
2092 			      size_t count, loff_t *f_ps)
2093 {
2094 	struct lineevent_state *le = file->private_data;
2095 
2096 	return call_read_locked(file, buf, count, f_ps, le->gdev,
2097 				lineevent_read_unlocked);
2098 }
2099 
2100 static void lineevent_free(struct lineevent_state *le)
2101 {
2102 	if (le->device_unregistered_nb.notifier_call)
2103 		blocking_notifier_chain_unregister(&le->gdev->device_notifier,
2104 						   &le->device_unregistered_nb);
2105 	if (le->irq)
2106 		free_irq_label(free_irq(le->irq, le));
2107 	if (le->desc)
2108 		gpiod_free(le->desc);
2109 	kfree(le->label);
2110 	gpio_device_put(le->gdev);
2111 	kfree(le);
2112 }
2113 
2114 static int lineevent_release(struct inode *inode, struct file *file)
2115 {
2116 	lineevent_free(file->private_data);
2117 	return 0;
2118 }
2119 
2120 static long lineevent_ioctl_unlocked(struct file *file, unsigned int cmd,
2121 				     unsigned long arg)
2122 {
2123 	struct lineevent_state *le = file->private_data;
2124 	void __user *ip = (void __user *)arg;
2125 	struct gpiohandle_data ghd;
2126 
2127 	if (!le->gdev->chip)
2128 		return -ENODEV;
2129 
2130 	/*
2131 	 * We can get the value for an event line but not set it,
2132 	 * because it is input by definition.
2133 	 */
2134 	if (cmd == GPIOHANDLE_GET_LINE_VALUES_IOCTL) {
2135 		int val;
2136 
2137 		memset(&ghd, 0, sizeof(ghd));
2138 
2139 		val = gpiod_get_value_cansleep(le->desc);
2140 		if (val < 0)
2141 			return val;
2142 		ghd.values[0] = val;
2143 
2144 		if (copy_to_user(ip, &ghd, sizeof(ghd)))
2145 			return -EFAULT;
2146 
2147 		return 0;
2148 	}
2149 	return -EINVAL;
2150 }
2151 
2152 static long lineevent_ioctl(struct file *file, unsigned int cmd,
2153 			    unsigned long arg)
2154 {
2155 	struct lineevent_state *le = file->private_data;
2156 
2157 	return call_ioctl_locked(file, cmd, arg, le->gdev,
2158 				 lineevent_ioctl_unlocked);
2159 }
2160 
2161 #ifdef CONFIG_COMPAT
2162 static long lineevent_ioctl_compat(struct file *file, unsigned int cmd,
2163 				   unsigned long arg)
2164 {
2165 	return lineevent_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
2166 }
2167 #endif
2168 
2169 static const struct file_operations lineevent_fileops = {
2170 	.release = lineevent_release,
2171 	.read = lineevent_read,
2172 	.poll = lineevent_poll,
2173 	.owner = THIS_MODULE,
2174 	.llseek = noop_llseek,
2175 	.unlocked_ioctl = lineevent_ioctl,
2176 #ifdef CONFIG_COMPAT
2177 	.compat_ioctl = lineevent_ioctl_compat,
2178 #endif
2179 };
2180 
2181 static irqreturn_t lineevent_irq_thread(int irq, void *p)
2182 {
2183 	struct lineevent_state *le = p;
2184 	struct gpioevent_data ge;
2185 	int ret;
2186 
2187 	/* Do not leak kernel stack to userspace */
2188 	memset(&ge, 0, sizeof(ge));
2189 
2190 	/*
2191 	 * We may be running from a nested threaded interrupt in which case
2192 	 * we didn't get the timestamp from lineevent_irq_handler().
2193 	 */
2194 	if (!le->timestamp)
2195 		ge.timestamp = ktime_get_ns();
2196 	else
2197 		ge.timestamp = le->timestamp;
2198 
2199 	if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE
2200 	    && le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
2201 		int level = gpiod_get_value_cansleep(le->desc);
2202 
2203 		if (level)
2204 			/* Emit low-to-high event */
2205 			ge.id = GPIOEVENT_EVENT_RISING_EDGE;
2206 		else
2207 			/* Emit high-to-low event */
2208 			ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
2209 	} else if (le->eflags & GPIOEVENT_REQUEST_RISING_EDGE) {
2210 		/* Emit low-to-high event */
2211 		ge.id = GPIOEVENT_EVENT_RISING_EDGE;
2212 	} else if (le->eflags & GPIOEVENT_REQUEST_FALLING_EDGE) {
2213 		/* Emit high-to-low event */
2214 		ge.id = GPIOEVENT_EVENT_FALLING_EDGE;
2215 	} else {
2216 		return IRQ_NONE;
2217 	}
2218 
2219 	ret = kfifo_in_spinlocked_noirqsave(&le->events, &ge,
2220 					    1, &le->wait.lock);
2221 	if (ret)
2222 		wake_up_poll(&le->wait, EPOLLIN);
2223 	else
2224 		pr_debug_ratelimited("event FIFO is full - event dropped\n");
2225 
2226 	return IRQ_HANDLED;
2227 }
2228 
2229 static irqreturn_t lineevent_irq_handler(int irq, void *p)
2230 {
2231 	struct lineevent_state *le = p;
2232 
2233 	/*
2234 	 * Just store the timestamp in hardirq context so we get it as
2235 	 * close in time as possible to the actual event.
2236 	 */
2237 	le->timestamp = ktime_get_ns();
2238 
2239 	return IRQ_WAKE_THREAD;
2240 }
2241 
2242 static int lineevent_create(struct gpio_device *gdev, void __user *ip)
2243 {
2244 	struct gpioevent_request eventreq;
2245 	struct lineevent_state *le;
2246 	struct gpio_desc *desc;
2247 	struct file *file;
2248 	u32 offset;
2249 	u32 lflags;
2250 	u32 eflags;
2251 	int fd;
2252 	int ret;
2253 	int irq, irqflags = 0;
2254 	char *label;
2255 
2256 	if (copy_from_user(&eventreq, ip, sizeof(eventreq)))
2257 		return -EFAULT;
2258 
2259 	offset = eventreq.lineoffset;
2260 	lflags = eventreq.handleflags;
2261 	eflags = eventreq.eventflags;
2262 
2263 	desc = gpiochip_get_desc(gdev->chip, offset);
2264 	if (IS_ERR(desc))
2265 		return PTR_ERR(desc);
2266 
2267 	/* Return an error if a unknown flag is set */
2268 	if ((lflags & ~GPIOHANDLE_REQUEST_VALID_FLAGS) ||
2269 	    (eflags & ~GPIOEVENT_REQUEST_VALID_FLAGS))
2270 		return -EINVAL;
2271 
2272 	/* This is just wrong: we don't look for events on output lines */
2273 	if ((lflags & GPIOHANDLE_REQUEST_OUTPUT) ||
2274 	    (lflags & GPIOHANDLE_REQUEST_OPEN_DRAIN) ||
2275 	    (lflags & GPIOHANDLE_REQUEST_OPEN_SOURCE))
2276 		return -EINVAL;
2277 
2278 	/* Only one bias flag can be set. */
2279 	if (((lflags & GPIOHANDLE_REQUEST_BIAS_DISABLE) &&
2280 	     (lflags & (GPIOHANDLE_REQUEST_BIAS_PULL_DOWN |
2281 			GPIOHANDLE_REQUEST_BIAS_PULL_UP))) ||
2282 	    ((lflags & GPIOHANDLE_REQUEST_BIAS_PULL_DOWN) &&
2283 	     (lflags & GPIOHANDLE_REQUEST_BIAS_PULL_UP)))
2284 		return -EINVAL;
2285 
2286 	le = kzalloc(sizeof(*le), GFP_KERNEL);
2287 	if (!le)
2288 		return -ENOMEM;
2289 	le->gdev = gpio_device_get(gdev);
2290 
2291 	if (eventreq.consumer_label[0] != '\0') {
2292 		/* label is only initialized if consumer_label is set */
2293 		le->label = kstrndup(eventreq.consumer_label,
2294 				     sizeof(eventreq.consumer_label) - 1,
2295 				     GFP_KERNEL);
2296 		if (!le->label) {
2297 			ret = -ENOMEM;
2298 			goto out_free_le;
2299 		}
2300 	}
2301 
2302 	ret = gpiod_request_user(desc, le->label);
2303 	if (ret)
2304 		goto out_free_le;
2305 	le->desc = desc;
2306 	le->eflags = eflags;
2307 
2308 	linehandle_flags_to_desc_flags(lflags, &desc->flags);
2309 
2310 	ret = gpiod_direction_input(desc);
2311 	if (ret)
2312 		goto out_free_le;
2313 
2314 	gpiod_line_state_notify(desc, GPIO_V2_LINE_CHANGED_REQUESTED);
2315 
2316 	irq = gpiod_to_irq(desc);
2317 	if (irq <= 0) {
2318 		ret = -ENODEV;
2319 		goto out_free_le;
2320 	}
2321 
2322 	if (eflags & GPIOEVENT_REQUEST_RISING_EDGE)
2323 		irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
2324 			IRQF_TRIGGER_FALLING : IRQF_TRIGGER_RISING;
2325 	if (eflags & GPIOEVENT_REQUEST_FALLING_EDGE)
2326 		irqflags |= test_bit(FLAG_ACTIVE_LOW, &desc->flags) ?
2327 			IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING;
2328 	irqflags |= IRQF_ONESHOT;
2329 
2330 	INIT_KFIFO(le->events);
2331 	init_waitqueue_head(&le->wait);
2332 
2333 	le->device_unregistered_nb.notifier_call = lineevent_unregistered_notify;
2334 	ret = blocking_notifier_chain_register(&gdev->device_notifier,
2335 					       &le->device_unregistered_nb);
2336 	if (ret)
2337 		goto out_free_le;
2338 
2339 	label = make_irq_label(le->label);
2340 	if (IS_ERR(label)) {
2341 		ret = PTR_ERR(label);
2342 		goto out_free_le;
2343 	}
2344 
2345 	/* Request a thread to read the events */
2346 	ret = request_threaded_irq(irq,
2347 				   lineevent_irq_handler,
2348 				   lineevent_irq_thread,
2349 				   irqflags,
2350 				   label,
2351 				   le);
2352 	if (ret) {
2353 		free_irq_label(label);
2354 		goto out_free_le;
2355 	}
2356 
2357 	le->irq = irq;
2358 
2359 	fd = get_unused_fd_flags(O_RDONLY | O_CLOEXEC);
2360 	if (fd < 0) {
2361 		ret = fd;
2362 		goto out_free_le;
2363 	}
2364 
2365 	file = anon_inode_getfile("gpio-event",
2366 				  &lineevent_fileops,
2367 				  le,
2368 				  O_RDONLY | O_CLOEXEC);
2369 	if (IS_ERR(file)) {
2370 		ret = PTR_ERR(file);
2371 		goto out_put_unused_fd;
2372 	}
2373 
2374 	eventreq.fd = fd;
2375 	if (copy_to_user(ip, &eventreq, sizeof(eventreq))) {
2376 		/*
2377 		 * fput() will trigger the release() callback, so do not go onto
2378 		 * the regular error cleanup path here.
2379 		 */
2380 		fput(file);
2381 		put_unused_fd(fd);
2382 		return -EFAULT;
2383 	}
2384 
2385 	fd_install(fd, file);
2386 
2387 	return 0;
2388 
2389 out_put_unused_fd:
2390 	put_unused_fd(fd);
2391 out_free_le:
2392 	lineevent_free(le);
2393 	return ret;
2394 }
2395 
2396 static void gpio_v2_line_info_to_v1(struct gpio_v2_line_info *info_v2,
2397 				    struct gpioline_info *info_v1)
2398 {
2399 	u64 flagsv2 = info_v2->flags;
2400 
2401 	memcpy(info_v1->name, info_v2->name, sizeof(info_v1->name));
2402 	memcpy(info_v1->consumer, info_v2->consumer, sizeof(info_v1->consumer));
2403 	info_v1->line_offset = info_v2->offset;
2404 	info_v1->flags = 0;
2405 
2406 	if (flagsv2 & GPIO_V2_LINE_FLAG_USED)
2407 		info_v1->flags |= GPIOLINE_FLAG_KERNEL;
2408 
2409 	if (flagsv2 & GPIO_V2_LINE_FLAG_OUTPUT)
2410 		info_v1->flags |= GPIOLINE_FLAG_IS_OUT;
2411 
2412 	if (flagsv2 & GPIO_V2_LINE_FLAG_ACTIVE_LOW)
2413 		info_v1->flags |= GPIOLINE_FLAG_ACTIVE_LOW;
2414 
2415 	if (flagsv2 & GPIO_V2_LINE_FLAG_OPEN_DRAIN)
2416 		info_v1->flags |= GPIOLINE_FLAG_OPEN_DRAIN;
2417 	if (flagsv2 & GPIO_V2_LINE_FLAG_OPEN_SOURCE)
2418 		info_v1->flags |= GPIOLINE_FLAG_OPEN_SOURCE;
2419 
2420 	if (flagsv2 & GPIO_V2_LINE_FLAG_BIAS_PULL_UP)
2421 		info_v1->flags |= GPIOLINE_FLAG_BIAS_PULL_UP;
2422 	if (flagsv2 & GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN)
2423 		info_v1->flags |= GPIOLINE_FLAG_BIAS_PULL_DOWN;
2424 	if (flagsv2 & GPIO_V2_LINE_FLAG_BIAS_DISABLED)
2425 		info_v1->flags |= GPIOLINE_FLAG_BIAS_DISABLE;
2426 }
2427 
2428 static void gpio_v2_line_info_changed_to_v1(
2429 		struct gpio_v2_line_info_changed *lic_v2,
2430 		struct gpioline_info_changed *lic_v1)
2431 {
2432 	memset(lic_v1, 0, sizeof(*lic_v1));
2433 	gpio_v2_line_info_to_v1(&lic_v2->info, &lic_v1->info);
2434 	lic_v1->timestamp = lic_v2->timestamp_ns;
2435 	lic_v1->event_type = lic_v2->event_type;
2436 }
2437 
2438 #endif /* CONFIG_GPIO_CDEV_V1 */
2439 
2440 static void gpio_desc_to_lineinfo(struct gpio_desc *desc,
2441 				  struct gpio_v2_line_info *info)
2442 {
2443 	struct gpio_chip *gc = desc->gdev->chip;
2444 	bool ok_for_pinctrl;
2445 	unsigned long flags;
2446 
2447 	memset(info, 0, sizeof(*info));
2448 	info->offset = gpio_chip_hwgpio(desc);
2449 
2450 	/*
2451 	 * This function takes a mutex so we must check this before taking
2452 	 * the spinlock.
2453 	 *
2454 	 * FIXME: find a non-racy way to retrieve this information. Maybe a
2455 	 * lock common to both frameworks?
2456 	 */
2457 	ok_for_pinctrl =
2458 		pinctrl_gpio_can_use_line(gc->base + info->offset);
2459 
2460 	spin_lock_irqsave(&gpio_lock, flags);
2461 
2462 	if (desc->name)
2463 		strscpy(info->name, desc->name, sizeof(info->name));
2464 
2465 	if (desc->label)
2466 		strscpy(info->consumer, desc->label, sizeof(info->consumer));
2467 
2468 	/*
2469 	 * Userspace only need to know that the kernel is using this GPIO so
2470 	 * it can't use it.
2471 	 */
2472 	info->flags = 0;
2473 	if (test_bit(FLAG_REQUESTED, &desc->flags) ||
2474 	    test_bit(FLAG_IS_HOGGED, &desc->flags) ||
2475 	    test_bit(FLAG_USED_AS_IRQ, &desc->flags) ||
2476 	    test_bit(FLAG_EXPORT, &desc->flags) ||
2477 	    test_bit(FLAG_SYSFS, &desc->flags) ||
2478 	    !gpiochip_line_is_valid(gc, info->offset) ||
2479 	    !ok_for_pinctrl)
2480 		info->flags |= GPIO_V2_LINE_FLAG_USED;
2481 
2482 	if (test_bit(FLAG_IS_OUT, &desc->flags))
2483 		info->flags |= GPIO_V2_LINE_FLAG_OUTPUT;
2484 	else
2485 		info->flags |= GPIO_V2_LINE_FLAG_INPUT;
2486 
2487 	if (test_bit(FLAG_ACTIVE_LOW, &desc->flags))
2488 		info->flags |= GPIO_V2_LINE_FLAG_ACTIVE_LOW;
2489 
2490 	if (test_bit(FLAG_OPEN_DRAIN, &desc->flags))
2491 		info->flags |= GPIO_V2_LINE_FLAG_OPEN_DRAIN;
2492 	if (test_bit(FLAG_OPEN_SOURCE, &desc->flags))
2493 		info->flags |= GPIO_V2_LINE_FLAG_OPEN_SOURCE;
2494 
2495 	if (test_bit(FLAG_BIAS_DISABLE, &desc->flags))
2496 		info->flags |= GPIO_V2_LINE_FLAG_BIAS_DISABLED;
2497 	if (test_bit(FLAG_PULL_DOWN, &desc->flags))
2498 		info->flags |= GPIO_V2_LINE_FLAG_BIAS_PULL_DOWN;
2499 	if (test_bit(FLAG_PULL_UP, &desc->flags))
2500 		info->flags |= GPIO_V2_LINE_FLAG_BIAS_PULL_UP;
2501 
2502 	if (test_bit(FLAG_EDGE_RISING, &desc->flags))
2503 		info->flags |= GPIO_V2_LINE_FLAG_EDGE_RISING;
2504 	if (test_bit(FLAG_EDGE_FALLING, &desc->flags))
2505 		info->flags |= GPIO_V2_LINE_FLAG_EDGE_FALLING;
2506 
2507 	if (test_bit(FLAG_EVENT_CLOCK_REALTIME, &desc->flags))
2508 		info->flags |= GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME;
2509 	else if (test_bit(FLAG_EVENT_CLOCK_HTE, &desc->flags))
2510 		info->flags |= GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE;
2511 
2512 	spin_unlock_irqrestore(&gpio_lock, flags);
2513 }
2514 
2515 struct gpio_chardev_data {
2516 	struct gpio_device *gdev;
2517 	wait_queue_head_t wait;
2518 	DECLARE_KFIFO(events, struct gpio_v2_line_info_changed, 32);
2519 	struct notifier_block lineinfo_changed_nb;
2520 	struct notifier_block device_unregistered_nb;
2521 	unsigned long *watched_lines;
2522 #ifdef CONFIG_GPIO_CDEV_V1
2523 	atomic_t watch_abi_version;
2524 #endif
2525 };
2526 
2527 static int chipinfo_get(struct gpio_chardev_data *cdev, void __user *ip)
2528 {
2529 	struct gpio_device *gdev = cdev->gdev;
2530 	struct gpiochip_info chipinfo;
2531 
2532 	memset(&chipinfo, 0, sizeof(chipinfo));
2533 
2534 	strscpy(chipinfo.name, dev_name(&gdev->dev), sizeof(chipinfo.name));
2535 	strscpy(chipinfo.label, gdev->label, sizeof(chipinfo.label));
2536 	chipinfo.lines = gdev->ngpio;
2537 	if (copy_to_user(ip, &chipinfo, sizeof(chipinfo)))
2538 		return -EFAULT;
2539 	return 0;
2540 }
2541 
2542 #ifdef CONFIG_GPIO_CDEV_V1
2543 /*
2544  * returns 0 if the versions match, else the previously selected ABI version
2545  */
2546 static int lineinfo_ensure_abi_version(struct gpio_chardev_data *cdata,
2547 				       unsigned int version)
2548 {
2549 	int abiv = atomic_cmpxchg(&cdata->watch_abi_version, 0, version);
2550 
2551 	if (abiv == version)
2552 		return 0;
2553 
2554 	return abiv;
2555 }
2556 
2557 static int lineinfo_get_v1(struct gpio_chardev_data *cdev, void __user *ip,
2558 			   bool watch)
2559 {
2560 	struct gpio_desc *desc;
2561 	struct gpioline_info lineinfo;
2562 	struct gpio_v2_line_info lineinfo_v2;
2563 
2564 	if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
2565 		return -EFAULT;
2566 
2567 	/* this doubles as a range check on line_offset */
2568 	desc = gpiochip_get_desc(cdev->gdev->chip, lineinfo.line_offset);
2569 	if (IS_ERR(desc))
2570 		return PTR_ERR(desc);
2571 
2572 	if (watch) {
2573 		if (lineinfo_ensure_abi_version(cdev, 1))
2574 			return -EPERM;
2575 
2576 		if (test_and_set_bit(lineinfo.line_offset, cdev->watched_lines))
2577 			return -EBUSY;
2578 	}
2579 
2580 	gpio_desc_to_lineinfo(desc, &lineinfo_v2);
2581 	gpio_v2_line_info_to_v1(&lineinfo_v2, &lineinfo);
2582 
2583 	if (copy_to_user(ip, &lineinfo, sizeof(lineinfo))) {
2584 		if (watch)
2585 			clear_bit(lineinfo.line_offset, cdev->watched_lines);
2586 		return -EFAULT;
2587 	}
2588 
2589 	return 0;
2590 }
2591 #endif
2592 
2593 static int lineinfo_get(struct gpio_chardev_data *cdev, void __user *ip,
2594 			bool watch)
2595 {
2596 	struct gpio_desc *desc;
2597 	struct gpio_v2_line_info lineinfo;
2598 
2599 	if (copy_from_user(&lineinfo, ip, sizeof(lineinfo)))
2600 		return -EFAULT;
2601 
2602 	if (memchr_inv(lineinfo.padding, 0, sizeof(lineinfo.padding)))
2603 		return -EINVAL;
2604 
2605 	desc = gpiochip_get_desc(cdev->gdev->chip, lineinfo.offset);
2606 	if (IS_ERR(desc))
2607 		return PTR_ERR(desc);
2608 
2609 	if (watch) {
2610 #ifdef CONFIG_GPIO_CDEV_V1
2611 		if (lineinfo_ensure_abi_version(cdev, 2))
2612 			return -EPERM;
2613 #endif
2614 		if (test_and_set_bit(lineinfo.offset, cdev->watched_lines))
2615 			return -EBUSY;
2616 	}
2617 	gpio_desc_to_lineinfo(desc, &lineinfo);
2618 	supinfo_to_lineinfo(desc, &lineinfo);
2619 
2620 	if (copy_to_user(ip, &lineinfo, sizeof(lineinfo))) {
2621 		if (watch)
2622 			clear_bit(lineinfo.offset, cdev->watched_lines);
2623 		return -EFAULT;
2624 	}
2625 
2626 	return 0;
2627 }
2628 
2629 static int lineinfo_unwatch(struct gpio_chardev_data *cdev, void __user *ip)
2630 {
2631 	__u32 offset;
2632 
2633 	if (copy_from_user(&offset, ip, sizeof(offset)))
2634 		return -EFAULT;
2635 
2636 	if (offset >= cdev->gdev->ngpio)
2637 		return -EINVAL;
2638 
2639 	if (!test_and_clear_bit(offset, cdev->watched_lines))
2640 		return -EBUSY;
2641 
2642 	return 0;
2643 }
2644 
2645 static long gpio_ioctl_unlocked(struct file *file, unsigned int cmd, unsigned long arg)
2646 {
2647 	struct gpio_chardev_data *cdev = file->private_data;
2648 	struct gpio_device *gdev = cdev->gdev;
2649 	void __user *ip = (void __user *)arg;
2650 
2651 	/* We fail any subsequent ioctl():s when the chip is gone */
2652 	if (!gdev->chip)
2653 		return -ENODEV;
2654 
2655 	/* Fill in the struct and pass to userspace */
2656 	switch (cmd) {
2657 	case GPIO_GET_CHIPINFO_IOCTL:
2658 		return chipinfo_get(cdev, ip);
2659 #ifdef CONFIG_GPIO_CDEV_V1
2660 	case GPIO_GET_LINEHANDLE_IOCTL:
2661 		return linehandle_create(gdev, ip);
2662 	case GPIO_GET_LINEEVENT_IOCTL:
2663 		return lineevent_create(gdev, ip);
2664 	case GPIO_GET_LINEINFO_IOCTL:
2665 		return lineinfo_get_v1(cdev, ip, false);
2666 	case GPIO_GET_LINEINFO_WATCH_IOCTL:
2667 		return lineinfo_get_v1(cdev, ip, true);
2668 #endif /* CONFIG_GPIO_CDEV_V1 */
2669 	case GPIO_V2_GET_LINEINFO_IOCTL:
2670 		return lineinfo_get(cdev, ip, false);
2671 	case GPIO_V2_GET_LINEINFO_WATCH_IOCTL:
2672 		return lineinfo_get(cdev, ip, true);
2673 	case GPIO_V2_GET_LINE_IOCTL:
2674 		return linereq_create(gdev, ip);
2675 	case GPIO_GET_LINEINFO_UNWATCH_IOCTL:
2676 		return lineinfo_unwatch(cdev, ip);
2677 	default:
2678 		return -EINVAL;
2679 	}
2680 }
2681 
2682 /*
2683  * gpio_ioctl() - ioctl handler for the GPIO chardev
2684  */
2685 static long gpio_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
2686 {
2687 	struct gpio_chardev_data *cdev = file->private_data;
2688 
2689 	return call_ioctl_locked(file, cmd, arg, cdev->gdev,
2690 				 gpio_ioctl_unlocked);
2691 }
2692 
2693 #ifdef CONFIG_COMPAT
2694 static long gpio_ioctl_compat(struct file *file, unsigned int cmd,
2695 			      unsigned long arg)
2696 {
2697 	return gpio_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
2698 }
2699 #endif
2700 
2701 static int lineinfo_changed_notify(struct notifier_block *nb,
2702 				   unsigned long action, void *data)
2703 {
2704 	struct gpio_chardev_data *cdev =
2705 		container_of(nb, struct gpio_chardev_data, lineinfo_changed_nb);
2706 	struct gpio_v2_line_info_changed chg;
2707 	struct gpio_desc *desc = data;
2708 	int ret;
2709 
2710 	if (!test_bit(gpio_chip_hwgpio(desc), cdev->watched_lines))
2711 		return NOTIFY_DONE;
2712 
2713 	memset(&chg, 0, sizeof(chg));
2714 	chg.event_type = action;
2715 	chg.timestamp_ns = ktime_get_ns();
2716 	gpio_desc_to_lineinfo(desc, &chg.info);
2717 	supinfo_to_lineinfo(desc, &chg.info);
2718 
2719 	ret = kfifo_in_spinlocked(&cdev->events, &chg, 1, &cdev->wait.lock);
2720 	if (ret)
2721 		wake_up_poll(&cdev->wait, EPOLLIN);
2722 	else
2723 		pr_debug_ratelimited("lineinfo event FIFO is full - event dropped\n");
2724 
2725 	return NOTIFY_OK;
2726 }
2727 
2728 static int gpio_device_unregistered_notify(struct notifier_block *nb,
2729 					   unsigned long action, void *data)
2730 {
2731 	struct gpio_chardev_data *cdev = container_of(nb,
2732 						      struct gpio_chardev_data,
2733 						      device_unregistered_nb);
2734 
2735 	wake_up_poll(&cdev->wait, EPOLLIN | EPOLLERR);
2736 
2737 	return NOTIFY_OK;
2738 }
2739 
2740 static __poll_t lineinfo_watch_poll_unlocked(struct file *file,
2741 					     struct poll_table_struct *pollt)
2742 {
2743 	struct gpio_chardev_data *cdev = file->private_data;
2744 	__poll_t events = 0;
2745 
2746 	if (!cdev->gdev->chip)
2747 		return EPOLLHUP | EPOLLERR;
2748 
2749 	poll_wait(file, &cdev->wait, pollt);
2750 
2751 	if (!kfifo_is_empty_spinlocked_noirqsave(&cdev->events,
2752 						 &cdev->wait.lock))
2753 		events = EPOLLIN | EPOLLRDNORM;
2754 
2755 	return events;
2756 }
2757 
2758 static __poll_t lineinfo_watch_poll(struct file *file,
2759 				    struct poll_table_struct *pollt)
2760 {
2761 	struct gpio_chardev_data *cdev = file->private_data;
2762 
2763 	return call_poll_locked(file, pollt, cdev->gdev,
2764 				lineinfo_watch_poll_unlocked);
2765 }
2766 
2767 static ssize_t lineinfo_watch_read_unlocked(struct file *file, char __user *buf,
2768 					    size_t count, loff_t *off)
2769 {
2770 	struct gpio_chardev_data *cdev = file->private_data;
2771 	struct gpio_v2_line_info_changed event;
2772 	ssize_t bytes_read = 0;
2773 	int ret;
2774 	size_t event_size;
2775 
2776 	if (!cdev->gdev->chip)
2777 		return -ENODEV;
2778 
2779 #ifndef CONFIG_GPIO_CDEV_V1
2780 	event_size = sizeof(struct gpio_v2_line_info_changed);
2781 	if (count < event_size)
2782 		return -EINVAL;
2783 #endif
2784 
2785 	do {
2786 		spin_lock(&cdev->wait.lock);
2787 		if (kfifo_is_empty(&cdev->events)) {
2788 			if (bytes_read) {
2789 				spin_unlock(&cdev->wait.lock);
2790 				return bytes_read;
2791 			}
2792 
2793 			if (file->f_flags & O_NONBLOCK) {
2794 				spin_unlock(&cdev->wait.lock);
2795 				return -EAGAIN;
2796 			}
2797 
2798 			ret = wait_event_interruptible_locked(cdev->wait,
2799 					!kfifo_is_empty(&cdev->events));
2800 			if (ret) {
2801 				spin_unlock(&cdev->wait.lock);
2802 				return ret;
2803 			}
2804 		}
2805 #ifdef CONFIG_GPIO_CDEV_V1
2806 		/* must be after kfifo check so watch_abi_version is set */
2807 		if (atomic_read(&cdev->watch_abi_version) == 2)
2808 			event_size = sizeof(struct gpio_v2_line_info_changed);
2809 		else
2810 			event_size = sizeof(struct gpioline_info_changed);
2811 		if (count < event_size) {
2812 			spin_unlock(&cdev->wait.lock);
2813 			return -EINVAL;
2814 		}
2815 #endif
2816 		ret = kfifo_out(&cdev->events, &event, 1);
2817 		spin_unlock(&cdev->wait.lock);
2818 		if (ret != 1) {
2819 			ret = -EIO;
2820 			break;
2821 			/* We should never get here. See lineevent_read(). */
2822 		}
2823 
2824 #ifdef CONFIG_GPIO_CDEV_V1
2825 		if (event_size == sizeof(struct gpio_v2_line_info_changed)) {
2826 			if (copy_to_user(buf + bytes_read, &event, event_size))
2827 				return -EFAULT;
2828 		} else {
2829 			struct gpioline_info_changed event_v1;
2830 
2831 			gpio_v2_line_info_changed_to_v1(&event, &event_v1);
2832 			if (copy_to_user(buf + bytes_read, &event_v1,
2833 					 event_size))
2834 				return -EFAULT;
2835 		}
2836 #else
2837 		if (copy_to_user(buf + bytes_read, &event, event_size))
2838 			return -EFAULT;
2839 #endif
2840 		bytes_read += event_size;
2841 	} while (count >= bytes_read + sizeof(event));
2842 
2843 	return bytes_read;
2844 }
2845 
2846 static ssize_t lineinfo_watch_read(struct file *file, char __user *buf,
2847 				   size_t count, loff_t *off)
2848 {
2849 	struct gpio_chardev_data *cdev = file->private_data;
2850 
2851 	return call_read_locked(file, buf, count, off, cdev->gdev,
2852 				lineinfo_watch_read_unlocked);
2853 }
2854 
2855 /**
2856  * gpio_chrdev_open() - open the chardev for ioctl operations
2857  * @inode: inode for this chardev
2858  * @file: file struct for storing private data
2859  * Returns 0 on success
2860  */
2861 static int gpio_chrdev_open(struct inode *inode, struct file *file)
2862 {
2863 	struct gpio_device *gdev = container_of(inode->i_cdev,
2864 						struct gpio_device, chrdev);
2865 	struct gpio_chardev_data *cdev;
2866 	int ret = -ENOMEM;
2867 
2868 	down_read(&gdev->sem);
2869 
2870 	/* Fail on open if the backing gpiochip is gone */
2871 	if (!gdev->chip) {
2872 		ret = -ENODEV;
2873 		goto out_unlock;
2874 	}
2875 
2876 	cdev = kzalloc(sizeof(*cdev), GFP_KERNEL);
2877 	if (!cdev)
2878 		goto out_unlock;
2879 
2880 	cdev->watched_lines = bitmap_zalloc(gdev->chip->ngpio, GFP_KERNEL);
2881 	if (!cdev->watched_lines)
2882 		goto out_free_cdev;
2883 
2884 	init_waitqueue_head(&cdev->wait);
2885 	INIT_KFIFO(cdev->events);
2886 	cdev->gdev = gpio_device_get(gdev);
2887 
2888 	cdev->lineinfo_changed_nb.notifier_call = lineinfo_changed_notify;
2889 	ret = blocking_notifier_chain_register(&gdev->line_state_notifier,
2890 					       &cdev->lineinfo_changed_nb);
2891 	if (ret)
2892 		goto out_free_bitmap;
2893 
2894 	cdev->device_unregistered_nb.notifier_call =
2895 					gpio_device_unregistered_notify;
2896 	ret = blocking_notifier_chain_register(&gdev->device_notifier,
2897 					       &cdev->device_unregistered_nb);
2898 	if (ret)
2899 		goto out_unregister_line_notifier;
2900 
2901 	file->private_data = cdev;
2902 
2903 	ret = nonseekable_open(inode, file);
2904 	if (ret)
2905 		goto out_unregister_device_notifier;
2906 
2907 	up_read(&gdev->sem);
2908 
2909 	return ret;
2910 
2911 out_unregister_device_notifier:
2912 	blocking_notifier_chain_unregister(&gdev->device_notifier,
2913 					   &cdev->device_unregistered_nb);
2914 out_unregister_line_notifier:
2915 	blocking_notifier_chain_unregister(&gdev->line_state_notifier,
2916 					   &cdev->lineinfo_changed_nb);
2917 out_free_bitmap:
2918 	gpio_device_put(gdev);
2919 	bitmap_free(cdev->watched_lines);
2920 out_free_cdev:
2921 	kfree(cdev);
2922 out_unlock:
2923 	up_read(&gdev->sem);
2924 	return ret;
2925 }
2926 
2927 /**
2928  * gpio_chrdev_release() - close chardev after ioctl operations
2929  * @inode: inode for this chardev
2930  * @file: file struct for storing private data
2931  * Returns 0 on success
2932  */
2933 static int gpio_chrdev_release(struct inode *inode, struct file *file)
2934 {
2935 	struct gpio_chardev_data *cdev = file->private_data;
2936 	struct gpio_device *gdev = cdev->gdev;
2937 
2938 	blocking_notifier_chain_unregister(&gdev->device_notifier,
2939 					   &cdev->device_unregistered_nb);
2940 	blocking_notifier_chain_unregister(&gdev->line_state_notifier,
2941 					   &cdev->lineinfo_changed_nb);
2942 	bitmap_free(cdev->watched_lines);
2943 	gpio_device_put(gdev);
2944 	kfree(cdev);
2945 
2946 	return 0;
2947 }
2948 
2949 static const struct file_operations gpio_fileops = {
2950 	.release = gpio_chrdev_release,
2951 	.open = gpio_chrdev_open,
2952 	.poll = lineinfo_watch_poll,
2953 	.read = lineinfo_watch_read,
2954 	.owner = THIS_MODULE,
2955 	.llseek = no_llseek,
2956 	.unlocked_ioctl = gpio_ioctl,
2957 #ifdef CONFIG_COMPAT
2958 	.compat_ioctl = gpio_ioctl_compat,
2959 #endif
2960 };
2961 
2962 int gpiolib_cdev_register(struct gpio_device *gdev, dev_t devt)
2963 {
2964 	int ret;
2965 
2966 	cdev_init(&gdev->chrdev, &gpio_fileops);
2967 	gdev->chrdev.owner = THIS_MODULE;
2968 	gdev->dev.devt = MKDEV(MAJOR(devt), gdev->id);
2969 
2970 	ret = cdev_device_add(&gdev->chrdev, &gdev->dev);
2971 	if (ret)
2972 		return ret;
2973 
2974 	chip_dbg(gdev->chip, "added GPIO chardev (%d:%d)\n",
2975 		 MAJOR(devt), gdev->id);
2976 
2977 	return 0;
2978 }
2979 
2980 void gpiolib_cdev_unregister(struct gpio_device *gdev)
2981 {
2982 	cdev_device_del(&gdev->chrdev, &gdev->dev);
2983 	blocking_notifier_call_chain(&gdev->device_notifier, 0, NULL);
2984 }
2985