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