xref: /linux-6.15/drivers/input/evdev.c (revision b3d65108)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Event char devices, giving access to raw input device events.
4  *
5  * Copyright (c) 1999-2002 Vojtech Pavlik
6  */
7 
8 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
9 
10 #define EVDEV_MINOR_BASE	64
11 #define EVDEV_MINORS		32
12 #define EVDEV_MIN_BUFFER_SIZE	64U
13 #define EVDEV_BUF_PACKETS	8
14 
15 #include <linux/poll.h>
16 #include <linux/sched.h>
17 #include <linux/slab.h>
18 #include <linux/vmalloc.h>
19 #include <linux/mm.h>
20 #include <linux/module.h>
21 #include <linux/init.h>
22 #include <linux/input/mt.h>
23 #include <linux/major.h>
24 #include <linux/device.h>
25 #include <linux/cdev.h>
26 #include "input-compat.h"
27 
28 struct evdev {
29 	int open;
30 	struct input_handle handle;
31 	struct evdev_client __rcu *grab;
32 	struct list_head client_list;
33 	spinlock_t client_lock; /* protects client_list */
34 	struct mutex mutex;
35 	struct device dev;
36 	struct cdev cdev;
37 	bool exist;
38 };
39 
40 struct evdev_client {
41 	unsigned int head;
42 	unsigned int tail;
43 	unsigned int packet_head; /* [future] position of the first element of next packet */
44 	spinlock_t buffer_lock; /* protects access to buffer, head and tail */
45 	wait_queue_head_t wait;
46 	struct fasync_struct *fasync;
47 	struct evdev *evdev;
48 	struct list_head node;
49 	enum input_clock_type clk_type;
50 	bool revoked;
51 	unsigned long *evmasks[EV_CNT];
52 	unsigned int bufsize;
53 	struct input_event buffer[] __counted_by(bufsize);
54 };
55 
56 static size_t evdev_get_mask_cnt(unsigned int type)
57 {
58 	static const size_t counts[EV_CNT] = {
59 		/* EV_SYN==0 is EV_CNT, _not_ SYN_CNT, see EVIOCGBIT */
60 		[EV_SYN]	= EV_CNT,
61 		[EV_KEY]	= KEY_CNT,
62 		[EV_REL]	= REL_CNT,
63 		[EV_ABS]	= ABS_CNT,
64 		[EV_MSC]	= MSC_CNT,
65 		[EV_SW]		= SW_CNT,
66 		[EV_LED]	= LED_CNT,
67 		[EV_SND]	= SND_CNT,
68 		[EV_FF]		= FF_CNT,
69 	};
70 
71 	return (type < EV_CNT) ? counts[type] : 0;
72 }
73 
74 /* requires the buffer lock to be held */
75 static bool __evdev_is_filtered(struct evdev_client *client,
76 				unsigned int type,
77 				unsigned int code)
78 {
79 	unsigned long *mask;
80 	size_t cnt;
81 
82 	/* EV_SYN and unknown codes are never filtered */
83 	if (type == EV_SYN || type >= EV_CNT)
84 		return false;
85 
86 	/* first test whether the type is filtered */
87 	mask = client->evmasks[0];
88 	if (mask && !test_bit(type, mask))
89 		return true;
90 
91 	/* unknown values are never filtered */
92 	cnt = evdev_get_mask_cnt(type);
93 	if (!cnt || code >= cnt)
94 		return false;
95 
96 	mask = client->evmasks[type];
97 	return mask && !test_bit(code, mask);
98 }
99 
100 /* flush queued events of type @type, caller must hold client->buffer_lock */
101 static void __evdev_flush_queue(struct evdev_client *client, unsigned int type)
102 {
103 	unsigned int i, head, num;
104 	unsigned int mask = client->bufsize - 1;
105 	bool is_report;
106 	struct input_event *ev;
107 
108 	BUG_ON(type == EV_SYN);
109 
110 	head = client->tail;
111 	client->packet_head = client->tail;
112 
113 	/* init to 1 so a leading SYN_REPORT will not be dropped */
114 	num = 1;
115 
116 	for (i = client->tail; i != client->head; i = (i + 1) & mask) {
117 		ev = &client->buffer[i];
118 		is_report = ev->type == EV_SYN && ev->code == SYN_REPORT;
119 
120 		if (ev->type == type) {
121 			/* drop matched entry */
122 			continue;
123 		} else if (is_report && !num) {
124 			/* drop empty SYN_REPORT groups */
125 			continue;
126 		} else if (head != i) {
127 			/* move entry to fill the gap */
128 			client->buffer[head] = *ev;
129 		}
130 
131 		num++;
132 		head = (head + 1) & mask;
133 
134 		if (is_report) {
135 			num = 0;
136 			client->packet_head = head;
137 		}
138 	}
139 
140 	client->head = head;
141 }
142 
143 static void __evdev_queue_syn_dropped(struct evdev_client *client)
144 {
145 	ktime_t *ev_time = input_get_timestamp(client->evdev->handle.dev);
146 	struct timespec64 ts = ktime_to_timespec64(ev_time[client->clk_type]);
147 	struct input_event ev;
148 
149 	ev.input_event_sec = ts.tv_sec;
150 	ev.input_event_usec = ts.tv_nsec / NSEC_PER_USEC;
151 	ev.type = EV_SYN;
152 	ev.code = SYN_DROPPED;
153 	ev.value = 0;
154 
155 	client->buffer[client->head++] = ev;
156 	client->head &= client->bufsize - 1;
157 
158 	if (unlikely(client->head == client->tail)) {
159 		/* drop queue but keep our SYN_DROPPED event */
160 		client->tail = (client->head - 1) & (client->bufsize - 1);
161 		client->packet_head = client->tail;
162 	}
163 }
164 
165 static void evdev_queue_syn_dropped(struct evdev_client *client)
166 {
167 	unsigned long flags;
168 
169 	spin_lock_irqsave(&client->buffer_lock, flags);
170 	__evdev_queue_syn_dropped(client);
171 	spin_unlock_irqrestore(&client->buffer_lock, flags);
172 }
173 
174 static int evdev_set_clk_type(struct evdev_client *client, unsigned int clkid)
175 {
176 	unsigned long flags;
177 	enum input_clock_type clk_type;
178 
179 	switch (clkid) {
180 
181 	case CLOCK_REALTIME:
182 		clk_type = INPUT_CLK_REAL;
183 		break;
184 	case CLOCK_MONOTONIC:
185 		clk_type = INPUT_CLK_MONO;
186 		break;
187 	case CLOCK_BOOTTIME:
188 		clk_type = INPUT_CLK_BOOT;
189 		break;
190 	default:
191 		return -EINVAL;
192 	}
193 
194 	if (client->clk_type != clk_type) {
195 		client->clk_type = clk_type;
196 
197 		/*
198 		 * Flush pending events and queue SYN_DROPPED event,
199 		 * but only if the queue is not empty.
200 		 */
201 		spin_lock_irqsave(&client->buffer_lock, flags);
202 
203 		if (client->head != client->tail) {
204 			client->packet_head = client->head = client->tail;
205 			__evdev_queue_syn_dropped(client);
206 		}
207 
208 		spin_unlock_irqrestore(&client->buffer_lock, flags);
209 	}
210 
211 	return 0;
212 }
213 
214 static void __pass_event(struct evdev_client *client,
215 			 const struct input_event *event)
216 {
217 	client->buffer[client->head++] = *event;
218 	client->head &= client->bufsize - 1;
219 
220 	if (unlikely(client->head == client->tail)) {
221 		/*
222 		 * This effectively "drops" all unconsumed events, leaving
223 		 * EV_SYN/SYN_DROPPED plus the newest event in the queue.
224 		 */
225 		client->tail = (client->head - 2) & (client->bufsize - 1);
226 
227 		client->buffer[client->tail] = (struct input_event) {
228 			.input_event_sec = event->input_event_sec,
229 			.input_event_usec = event->input_event_usec,
230 			.type = EV_SYN,
231 			.code = SYN_DROPPED,
232 			.value = 0,
233 		};
234 
235 		client->packet_head = client->tail;
236 	}
237 
238 	if (event->type == EV_SYN && event->code == SYN_REPORT) {
239 		client->packet_head = client->head;
240 		kill_fasync(&client->fasync, SIGIO, POLL_IN);
241 	}
242 }
243 
244 static void evdev_pass_values(struct evdev_client *client,
245 			const struct input_value *vals, unsigned int count,
246 			ktime_t *ev_time)
247 {
248 	const struct input_value *v;
249 	struct input_event event;
250 	struct timespec64 ts;
251 	bool wakeup = false;
252 
253 	if (client->revoked)
254 		return;
255 
256 	ts = ktime_to_timespec64(ev_time[client->clk_type]);
257 	event.input_event_sec = ts.tv_sec;
258 	event.input_event_usec = ts.tv_nsec / NSEC_PER_USEC;
259 
260 	/* Interrupts are disabled, just acquire the lock. */
261 	spin_lock(&client->buffer_lock);
262 
263 	for (v = vals; v != vals + count; v++) {
264 		if (__evdev_is_filtered(client, v->type, v->code))
265 			continue;
266 
267 		if (v->type == EV_SYN && v->code == SYN_REPORT) {
268 			/* drop empty SYN_REPORT */
269 			if (client->packet_head == client->head)
270 				continue;
271 
272 			wakeup = true;
273 		}
274 
275 		event.type = v->type;
276 		event.code = v->code;
277 		event.value = v->value;
278 		__pass_event(client, &event);
279 	}
280 
281 	spin_unlock(&client->buffer_lock);
282 
283 	if (wakeup)
284 		wake_up_interruptible_poll(&client->wait,
285 			EPOLLIN | EPOLLOUT | EPOLLRDNORM | EPOLLWRNORM);
286 }
287 
288 /*
289  * Pass incoming events to all connected clients.
290  */
291 static void evdev_events(struct input_handle *handle,
292 			 const struct input_value *vals, unsigned int count)
293 {
294 	struct evdev *evdev = handle->private;
295 	struct evdev_client *client;
296 	ktime_t *ev_time = input_get_timestamp(handle->dev);
297 
298 	rcu_read_lock();
299 
300 	client = rcu_dereference(evdev->grab);
301 
302 	if (client)
303 		evdev_pass_values(client, vals, count, ev_time);
304 	else
305 		list_for_each_entry_rcu(client, &evdev->client_list, node)
306 			evdev_pass_values(client, vals, count, ev_time);
307 
308 	rcu_read_unlock();
309 }
310 
311 static int evdev_fasync(int fd, struct file *file, int on)
312 {
313 	struct evdev_client *client = file->private_data;
314 
315 	return fasync_helper(fd, file, on, &client->fasync);
316 }
317 
318 static void evdev_free(struct device *dev)
319 {
320 	struct evdev *evdev = container_of(dev, struct evdev, dev);
321 
322 	input_put_device(evdev->handle.dev);
323 	kfree(evdev);
324 }
325 
326 /*
327  * Grabs an event device (along with underlying input device).
328  * This function is called with evdev->mutex taken.
329  */
330 static int evdev_grab(struct evdev *evdev, struct evdev_client *client)
331 {
332 	int error;
333 
334 	if (evdev->grab)
335 		return -EBUSY;
336 
337 	error = input_grab_device(&evdev->handle);
338 	if (error)
339 		return error;
340 
341 	rcu_assign_pointer(evdev->grab, client);
342 
343 	return 0;
344 }
345 
346 static int evdev_ungrab(struct evdev *evdev, struct evdev_client *client)
347 {
348 	struct evdev_client *grab = rcu_dereference_protected(evdev->grab,
349 					lockdep_is_held(&evdev->mutex));
350 
351 	if (grab != client)
352 		return  -EINVAL;
353 
354 	rcu_assign_pointer(evdev->grab, NULL);
355 	synchronize_rcu();
356 	input_release_device(&evdev->handle);
357 
358 	return 0;
359 }
360 
361 static void evdev_attach_client(struct evdev *evdev,
362 				struct evdev_client *client)
363 {
364 	spin_lock(&evdev->client_lock);
365 	list_add_tail_rcu(&client->node, &evdev->client_list);
366 	spin_unlock(&evdev->client_lock);
367 }
368 
369 static void evdev_detach_client(struct evdev *evdev,
370 				struct evdev_client *client)
371 {
372 	spin_lock(&evdev->client_lock);
373 	list_del_rcu(&client->node);
374 	spin_unlock(&evdev->client_lock);
375 	synchronize_rcu();
376 }
377 
378 static int evdev_open_device(struct evdev *evdev)
379 {
380 	int retval;
381 
382 	retval = mutex_lock_interruptible(&evdev->mutex);
383 	if (retval)
384 		return retval;
385 
386 	if (!evdev->exist)
387 		retval = -ENODEV;
388 	else if (!evdev->open++) {
389 		retval = input_open_device(&evdev->handle);
390 		if (retval)
391 			evdev->open--;
392 	}
393 
394 	mutex_unlock(&evdev->mutex);
395 	return retval;
396 }
397 
398 static void evdev_close_device(struct evdev *evdev)
399 {
400 	mutex_lock(&evdev->mutex);
401 
402 	if (evdev->exist && !--evdev->open)
403 		input_close_device(&evdev->handle);
404 
405 	mutex_unlock(&evdev->mutex);
406 }
407 
408 /*
409  * Wake up users waiting for IO so they can disconnect from
410  * dead device.
411  */
412 static void evdev_hangup(struct evdev *evdev)
413 {
414 	struct evdev_client *client;
415 
416 	spin_lock(&evdev->client_lock);
417 	list_for_each_entry(client, &evdev->client_list, node) {
418 		kill_fasync(&client->fasync, SIGIO, POLL_HUP);
419 		wake_up_interruptible_poll(&client->wait, EPOLLHUP | EPOLLERR);
420 	}
421 	spin_unlock(&evdev->client_lock);
422 }
423 
424 static int evdev_release(struct inode *inode, struct file *file)
425 {
426 	struct evdev_client *client = file->private_data;
427 	struct evdev *evdev = client->evdev;
428 	unsigned int i;
429 
430 	mutex_lock(&evdev->mutex);
431 
432 	if (evdev->exist && !client->revoked)
433 		input_flush_device(&evdev->handle, file);
434 
435 	evdev_ungrab(evdev, client);
436 	mutex_unlock(&evdev->mutex);
437 
438 	evdev_detach_client(evdev, client);
439 
440 	for (i = 0; i < EV_CNT; ++i)
441 		bitmap_free(client->evmasks[i]);
442 
443 	kvfree(client);
444 
445 	evdev_close_device(evdev);
446 
447 	return 0;
448 }
449 
450 static unsigned int evdev_compute_buffer_size(struct input_dev *dev)
451 {
452 	unsigned int n_events =
453 		max(dev->hint_events_per_packet * EVDEV_BUF_PACKETS,
454 		    EVDEV_MIN_BUFFER_SIZE);
455 
456 	return roundup_pow_of_two(n_events);
457 }
458 
459 static int evdev_open(struct inode *inode, struct file *file)
460 {
461 	struct evdev *evdev = container_of(inode->i_cdev, struct evdev, cdev);
462 	unsigned int bufsize = evdev_compute_buffer_size(evdev->handle.dev);
463 	struct evdev_client *client;
464 	int error;
465 
466 	client = kvzalloc(struct_size(client, buffer, bufsize), GFP_KERNEL);
467 	if (!client)
468 		return -ENOMEM;
469 
470 	init_waitqueue_head(&client->wait);
471 	client->bufsize = bufsize;
472 	spin_lock_init(&client->buffer_lock);
473 	client->evdev = evdev;
474 	evdev_attach_client(evdev, client);
475 
476 	error = evdev_open_device(evdev);
477 	if (error)
478 		goto err_free_client;
479 
480 	file->private_data = client;
481 	stream_open(inode, file);
482 
483 	return 0;
484 
485  err_free_client:
486 	evdev_detach_client(evdev, client);
487 	kvfree(client);
488 	return error;
489 }
490 
491 static ssize_t evdev_write(struct file *file, const char __user *buffer,
492 			   size_t count, loff_t *ppos)
493 {
494 	struct evdev_client *client = file->private_data;
495 	struct evdev *evdev = client->evdev;
496 	struct input_event event;
497 	int retval = 0;
498 
499 	if (count != 0 && count < input_event_size())
500 		return -EINVAL;
501 
502 	retval = mutex_lock_interruptible(&evdev->mutex);
503 	if (retval)
504 		return retval;
505 
506 	if (!evdev->exist || client->revoked) {
507 		retval = -ENODEV;
508 		goto out;
509 	}
510 
511 	while (retval + input_event_size() <= count) {
512 
513 		if (input_event_from_user(buffer + retval, &event)) {
514 			retval = -EFAULT;
515 			goto out;
516 		}
517 		retval += input_event_size();
518 
519 		input_inject_event(&evdev->handle,
520 				   event.type, event.code, event.value);
521 		cond_resched();
522 	}
523 
524  out:
525 	mutex_unlock(&evdev->mutex);
526 	return retval;
527 }
528 
529 static int evdev_fetch_next_event(struct evdev_client *client,
530 				  struct input_event *event)
531 {
532 	int have_event;
533 
534 	spin_lock_irq(&client->buffer_lock);
535 
536 	have_event = client->packet_head != client->tail;
537 	if (have_event) {
538 		*event = client->buffer[client->tail++];
539 		client->tail &= client->bufsize - 1;
540 	}
541 
542 	spin_unlock_irq(&client->buffer_lock);
543 
544 	return have_event;
545 }
546 
547 static ssize_t evdev_read(struct file *file, char __user *buffer,
548 			  size_t count, loff_t *ppos)
549 {
550 	struct evdev_client *client = file->private_data;
551 	struct evdev *evdev = client->evdev;
552 	struct input_event event;
553 	size_t read = 0;
554 	int error;
555 
556 	if (count != 0 && count < input_event_size())
557 		return -EINVAL;
558 
559 	for (;;) {
560 		if (!evdev->exist || client->revoked)
561 			return -ENODEV;
562 
563 		if (client->packet_head == client->tail &&
564 		    (file->f_flags & O_NONBLOCK))
565 			return -EAGAIN;
566 
567 		/*
568 		 * count == 0 is special - no IO is done but we check
569 		 * for error conditions (see above).
570 		 */
571 		if (count == 0)
572 			break;
573 
574 		while (read + input_event_size() <= count &&
575 		       evdev_fetch_next_event(client, &event)) {
576 
577 			if (input_event_to_user(buffer + read, &event))
578 				return -EFAULT;
579 
580 			read += input_event_size();
581 		}
582 
583 		if (read)
584 			break;
585 
586 		if (!(file->f_flags & O_NONBLOCK)) {
587 			error = wait_event_interruptible(client->wait,
588 					client->packet_head != client->tail ||
589 					!evdev->exist || client->revoked);
590 			if (error)
591 				return error;
592 		}
593 	}
594 
595 	return read;
596 }
597 
598 /* No kernel lock - fine */
599 static __poll_t evdev_poll(struct file *file, poll_table *wait)
600 {
601 	struct evdev_client *client = file->private_data;
602 	struct evdev *evdev = client->evdev;
603 	__poll_t mask;
604 
605 	poll_wait(file, &client->wait, wait);
606 
607 	if (evdev->exist && !client->revoked)
608 		mask = EPOLLOUT | EPOLLWRNORM;
609 	else
610 		mask = EPOLLHUP | EPOLLERR;
611 
612 	if (client->packet_head != client->tail)
613 		mask |= EPOLLIN | EPOLLRDNORM;
614 
615 	return mask;
616 }
617 
618 #ifdef CONFIG_COMPAT
619 
620 #define BITS_PER_LONG_COMPAT (sizeof(compat_long_t) * 8)
621 #define BITS_TO_LONGS_COMPAT(x) ((((x) - 1) / BITS_PER_LONG_COMPAT) + 1)
622 
623 #ifdef __BIG_ENDIAN
624 static int bits_to_user(unsigned long *bits, unsigned int maxbit,
625 			unsigned int maxlen, void __user *p, int compat)
626 {
627 	int len, i;
628 
629 	if (compat) {
630 		len = BITS_TO_LONGS_COMPAT(maxbit) * sizeof(compat_long_t);
631 		if (len > maxlen)
632 			len = maxlen;
633 
634 		for (i = 0; i < len / sizeof(compat_long_t); i++)
635 			if (copy_to_user((compat_long_t __user *) p + i,
636 					 (compat_long_t *) bits +
637 						i + 1 - ((i % 2) << 1),
638 					 sizeof(compat_long_t)))
639 				return -EFAULT;
640 	} else {
641 		len = BITS_TO_LONGS(maxbit) * sizeof(long);
642 		if (len > maxlen)
643 			len = maxlen;
644 
645 		if (copy_to_user(p, bits, len))
646 			return -EFAULT;
647 	}
648 
649 	return len;
650 }
651 
652 static int bits_from_user(unsigned long *bits, unsigned int maxbit,
653 			  unsigned int maxlen, const void __user *p, int compat)
654 {
655 	int len, i;
656 
657 	if (compat) {
658 		if (maxlen % sizeof(compat_long_t))
659 			return -EINVAL;
660 
661 		len = BITS_TO_LONGS_COMPAT(maxbit) * sizeof(compat_long_t);
662 		if (len > maxlen)
663 			len = maxlen;
664 
665 		for (i = 0; i < len / sizeof(compat_long_t); i++)
666 			if (copy_from_user((compat_long_t *) bits +
667 						i + 1 - ((i % 2) << 1),
668 					   (compat_long_t __user *) p + i,
669 					   sizeof(compat_long_t)))
670 				return -EFAULT;
671 		if (i % 2)
672 			*((compat_long_t *) bits + i - 1) = 0;
673 
674 	} else {
675 		if (maxlen % sizeof(long))
676 			return -EINVAL;
677 
678 		len = BITS_TO_LONGS(maxbit) * sizeof(long);
679 		if (len > maxlen)
680 			len = maxlen;
681 
682 		if (copy_from_user(bits, p, len))
683 			return -EFAULT;
684 	}
685 
686 	return len;
687 }
688 
689 #else
690 
691 static int bits_to_user(unsigned long *bits, unsigned int maxbit,
692 			unsigned int maxlen, void __user *p, int compat)
693 {
694 	int len = compat ?
695 			BITS_TO_LONGS_COMPAT(maxbit) * sizeof(compat_long_t) :
696 			BITS_TO_LONGS(maxbit) * sizeof(long);
697 
698 	if (len > maxlen)
699 		len = maxlen;
700 
701 	return copy_to_user(p, bits, len) ? -EFAULT : len;
702 }
703 
704 static int bits_from_user(unsigned long *bits, unsigned int maxbit,
705 			  unsigned int maxlen, const void __user *p, int compat)
706 {
707 	size_t chunk_size = compat ? sizeof(compat_long_t) : sizeof(long);
708 	int len;
709 
710 	if (maxlen % chunk_size)
711 		return -EINVAL;
712 
713 	len = compat ? BITS_TO_LONGS_COMPAT(maxbit) : BITS_TO_LONGS(maxbit);
714 	len *= chunk_size;
715 	if (len > maxlen)
716 		len = maxlen;
717 
718 	return copy_from_user(bits, p, len) ? -EFAULT : len;
719 }
720 
721 #endif /* __BIG_ENDIAN */
722 
723 #else
724 
725 static int bits_to_user(unsigned long *bits, unsigned int maxbit,
726 			unsigned int maxlen, void __user *p, int compat)
727 {
728 	int len = BITS_TO_LONGS(maxbit) * sizeof(long);
729 
730 	if (len > maxlen)
731 		len = maxlen;
732 
733 	return copy_to_user(p, bits, len) ? -EFAULT : len;
734 }
735 
736 static int bits_from_user(unsigned long *bits, unsigned int maxbit,
737 			  unsigned int maxlen, const void __user *p, int compat)
738 {
739 	int len;
740 
741 	if (maxlen % sizeof(long))
742 		return -EINVAL;
743 
744 	len = BITS_TO_LONGS(maxbit) * sizeof(long);
745 	if (len > maxlen)
746 		len = maxlen;
747 
748 	return copy_from_user(bits, p, len) ? -EFAULT : len;
749 }
750 
751 #endif /* CONFIG_COMPAT */
752 
753 static int str_to_user(const char *str, unsigned int maxlen, void __user *p)
754 {
755 	int len;
756 
757 	if (!str)
758 		return -ENOENT;
759 
760 	len = strlen(str) + 1;
761 	if (len > maxlen)
762 		len = maxlen;
763 
764 	return copy_to_user(p, str, len) ? -EFAULT : len;
765 }
766 
767 static int handle_eviocgbit(struct input_dev *dev,
768 			    unsigned int type, unsigned int size,
769 			    void __user *p, int compat_mode)
770 {
771 	unsigned long *bits;
772 	int len;
773 
774 	switch (type) {
775 
776 	case      0: bits = dev->evbit;  len = EV_MAX;  break;
777 	case EV_KEY: bits = dev->keybit; len = KEY_MAX; break;
778 	case EV_REL: bits = dev->relbit; len = REL_MAX; break;
779 	case EV_ABS: bits = dev->absbit; len = ABS_MAX; break;
780 	case EV_MSC: bits = dev->mscbit; len = MSC_MAX; break;
781 	case EV_LED: bits = dev->ledbit; len = LED_MAX; break;
782 	case EV_SND: bits = dev->sndbit; len = SND_MAX; break;
783 	case EV_FF:  bits = dev->ffbit;  len = FF_MAX;  break;
784 	case EV_SW:  bits = dev->swbit;  len = SW_MAX;  break;
785 	default: return -EINVAL;
786 	}
787 
788 	return bits_to_user(bits, len, size, p, compat_mode);
789 }
790 
791 static int evdev_handle_get_keycode(struct input_dev *dev, void __user *p)
792 {
793 	struct input_keymap_entry ke = {
794 		.len	= sizeof(unsigned int),
795 		.flags	= 0,
796 	};
797 	int __user *ip = (int __user *)p;
798 	int error;
799 
800 	/* legacy case */
801 	if (copy_from_user(ke.scancode, p, sizeof(unsigned int)))
802 		return -EFAULT;
803 
804 	error = input_get_keycode(dev, &ke);
805 	if (error)
806 		return error;
807 
808 	if (put_user(ke.keycode, ip + 1))
809 		return -EFAULT;
810 
811 	return 0;
812 }
813 
814 static int evdev_handle_get_keycode_v2(struct input_dev *dev, void __user *p)
815 {
816 	struct input_keymap_entry ke;
817 	int error;
818 
819 	if (copy_from_user(&ke, p, sizeof(ke)))
820 		return -EFAULT;
821 
822 	error = input_get_keycode(dev, &ke);
823 	if (error)
824 		return error;
825 
826 	if (copy_to_user(p, &ke, sizeof(ke)))
827 		return -EFAULT;
828 
829 	return 0;
830 }
831 
832 static int evdev_handle_set_keycode(struct input_dev *dev, void __user *p)
833 {
834 	struct input_keymap_entry ke = {
835 		.len	= sizeof(unsigned int),
836 		.flags	= 0,
837 	};
838 	int __user *ip = (int __user *)p;
839 
840 	if (copy_from_user(ke.scancode, p, sizeof(unsigned int)))
841 		return -EFAULT;
842 
843 	if (get_user(ke.keycode, ip + 1))
844 		return -EFAULT;
845 
846 	return input_set_keycode(dev, &ke);
847 }
848 
849 static int evdev_handle_set_keycode_v2(struct input_dev *dev, void __user *p)
850 {
851 	struct input_keymap_entry ke;
852 
853 	if (copy_from_user(&ke, p, sizeof(ke)))
854 		return -EFAULT;
855 
856 	if (ke.len > sizeof(ke.scancode))
857 		return -EINVAL;
858 
859 	return input_set_keycode(dev, &ke);
860 }
861 
862 /*
863  * If we transfer state to the user, we should flush all pending events
864  * of the same type from the client's queue. Otherwise, they might end up
865  * with duplicate events, which can screw up client's state tracking.
866  * If bits_to_user fails after flushing the queue, we queue a SYN_DROPPED
867  * event so user-space will notice missing events.
868  *
869  * LOCKING:
870  * We need to take event_lock before buffer_lock to avoid dead-locks. But we
871  * need the even_lock only to guarantee consistent state. We can safely release
872  * it while flushing the queue. This allows input-core to handle filters while
873  * we flush the queue.
874  */
875 static int evdev_handle_get_val(struct evdev_client *client,
876 				struct input_dev *dev, unsigned int type,
877 				unsigned long *bits, unsigned int maxbit,
878 				unsigned int maxlen, void __user *p,
879 				int compat)
880 {
881 	int ret;
882 	unsigned long *mem;
883 
884 	mem = bitmap_alloc(maxbit, GFP_KERNEL);
885 	if (!mem)
886 		return -ENOMEM;
887 
888 	spin_lock_irq(&dev->event_lock);
889 	spin_lock(&client->buffer_lock);
890 
891 	bitmap_copy(mem, bits, maxbit);
892 
893 	spin_unlock(&dev->event_lock);
894 
895 	__evdev_flush_queue(client, type);
896 
897 	spin_unlock_irq(&client->buffer_lock);
898 
899 	ret = bits_to_user(mem, maxbit, maxlen, p, compat);
900 	if (ret < 0)
901 		evdev_queue_syn_dropped(client);
902 
903 	bitmap_free(mem);
904 
905 	return ret;
906 }
907 
908 static int evdev_handle_mt_request(struct input_dev *dev,
909 				   unsigned int size,
910 				   int __user *ip)
911 {
912 	const struct input_mt *mt = dev->mt;
913 	unsigned int code;
914 	int max_slots;
915 	int i;
916 
917 	if (get_user(code, &ip[0]))
918 		return -EFAULT;
919 	if (!mt || !input_is_mt_value(code))
920 		return -EINVAL;
921 
922 	max_slots = (size - sizeof(__u32)) / sizeof(__s32);
923 	for (i = 0; i < mt->num_slots && i < max_slots; i++) {
924 		int value = input_mt_get_value(&mt->slots[i], code);
925 		if (put_user(value, &ip[1 + i]))
926 			return -EFAULT;
927 	}
928 
929 	return 0;
930 }
931 
932 static int evdev_revoke(struct evdev *evdev, struct evdev_client *client,
933 			struct file *file)
934 {
935 	client->revoked = true;
936 	evdev_ungrab(evdev, client);
937 	input_flush_device(&evdev->handle, file);
938 	wake_up_interruptible_poll(&client->wait, EPOLLHUP | EPOLLERR);
939 
940 	return 0;
941 }
942 
943 /* must be called with evdev-mutex held */
944 static int evdev_set_mask(struct evdev_client *client,
945 			  unsigned int type,
946 			  const void __user *codes,
947 			  u32 codes_size,
948 			  int compat)
949 {
950 	unsigned long flags, *mask, *oldmask;
951 	size_t cnt;
952 	int error;
953 
954 	/* we allow unknown types and 'codes_size > size' for forward-compat */
955 	cnt = evdev_get_mask_cnt(type);
956 	if (!cnt)
957 		return 0;
958 
959 	mask = bitmap_zalloc(cnt, GFP_KERNEL);
960 	if (!mask)
961 		return -ENOMEM;
962 
963 	error = bits_from_user(mask, cnt - 1, codes_size, codes, compat);
964 	if (error < 0) {
965 		bitmap_free(mask);
966 		return error;
967 	}
968 
969 	spin_lock_irqsave(&client->buffer_lock, flags);
970 	oldmask = client->evmasks[type];
971 	client->evmasks[type] = mask;
972 	spin_unlock_irqrestore(&client->buffer_lock, flags);
973 
974 	bitmap_free(oldmask);
975 
976 	return 0;
977 }
978 
979 /* must be called with evdev-mutex held */
980 static int evdev_get_mask(struct evdev_client *client,
981 			  unsigned int type,
982 			  void __user *codes,
983 			  u32 codes_size,
984 			  int compat)
985 {
986 	unsigned long *mask;
987 	size_t cnt, size, xfer_size;
988 	int i;
989 	int error;
990 
991 	/* we allow unknown types and 'codes_size > size' for forward-compat */
992 	cnt = evdev_get_mask_cnt(type);
993 	size = sizeof(unsigned long) * BITS_TO_LONGS(cnt);
994 	xfer_size = min_t(size_t, codes_size, size);
995 
996 	if (cnt > 0) {
997 		mask = client->evmasks[type];
998 		if (mask) {
999 			error = bits_to_user(mask, cnt - 1,
1000 					     xfer_size, codes, compat);
1001 			if (error < 0)
1002 				return error;
1003 		} else {
1004 			/* fake mask with all bits set */
1005 			for (i = 0; i < xfer_size; i++)
1006 				if (put_user(0xffU, (u8 __user *)codes + i))
1007 					return -EFAULT;
1008 		}
1009 	}
1010 
1011 	if (xfer_size < codes_size)
1012 		if (clear_user(codes + xfer_size, codes_size - xfer_size))
1013 			return -EFAULT;
1014 
1015 	return 0;
1016 }
1017 
1018 static long evdev_do_ioctl(struct file *file, unsigned int cmd,
1019 			   void __user *p, int compat_mode)
1020 {
1021 	struct evdev_client *client = file->private_data;
1022 	struct evdev *evdev = client->evdev;
1023 	struct input_dev *dev = evdev->handle.dev;
1024 	struct input_absinfo abs;
1025 	struct input_mask mask;
1026 	struct ff_effect effect;
1027 	int __user *ip = (int __user *)p;
1028 	unsigned int i, t, u, v;
1029 	unsigned int size;
1030 	int error;
1031 
1032 	/* First we check for fixed-length commands */
1033 	switch (cmd) {
1034 
1035 	case EVIOCGVERSION:
1036 		return put_user(EV_VERSION, ip);
1037 
1038 	case EVIOCGID:
1039 		if (copy_to_user(p, &dev->id, sizeof(struct input_id)))
1040 			return -EFAULT;
1041 		return 0;
1042 
1043 	case EVIOCGREP:
1044 		if (!test_bit(EV_REP, dev->evbit))
1045 			return -ENOSYS;
1046 		if (put_user(dev->rep[REP_DELAY], ip))
1047 			return -EFAULT;
1048 		if (put_user(dev->rep[REP_PERIOD], ip + 1))
1049 			return -EFAULT;
1050 		return 0;
1051 
1052 	case EVIOCSREP:
1053 		if (!test_bit(EV_REP, dev->evbit))
1054 			return -ENOSYS;
1055 		if (get_user(u, ip))
1056 			return -EFAULT;
1057 		if (get_user(v, ip + 1))
1058 			return -EFAULT;
1059 
1060 		input_inject_event(&evdev->handle, EV_REP, REP_DELAY, u);
1061 		input_inject_event(&evdev->handle, EV_REP, REP_PERIOD, v);
1062 
1063 		return 0;
1064 
1065 	case EVIOCRMFF:
1066 		return input_ff_erase(dev, (int)(unsigned long) p, file);
1067 
1068 	case EVIOCGEFFECTS:
1069 		i = test_bit(EV_FF, dev->evbit) ?
1070 				dev->ff->max_effects : 0;
1071 		if (put_user(i, ip))
1072 			return -EFAULT;
1073 		return 0;
1074 
1075 	case EVIOCGRAB:
1076 		if (p)
1077 			return evdev_grab(evdev, client);
1078 		else
1079 			return evdev_ungrab(evdev, client);
1080 
1081 	case EVIOCREVOKE:
1082 		if (p)
1083 			return -EINVAL;
1084 		else
1085 			return evdev_revoke(evdev, client, file);
1086 
1087 	case EVIOCGMASK: {
1088 		void __user *codes_ptr;
1089 
1090 		if (copy_from_user(&mask, p, sizeof(mask)))
1091 			return -EFAULT;
1092 
1093 		codes_ptr = (void __user *)(unsigned long)mask.codes_ptr;
1094 		return evdev_get_mask(client,
1095 				      mask.type, codes_ptr, mask.codes_size,
1096 				      compat_mode);
1097 	}
1098 
1099 	case EVIOCSMASK: {
1100 		const void __user *codes_ptr;
1101 
1102 		if (copy_from_user(&mask, p, sizeof(mask)))
1103 			return -EFAULT;
1104 
1105 		codes_ptr = (const void __user *)(unsigned long)mask.codes_ptr;
1106 		return evdev_set_mask(client,
1107 				      mask.type, codes_ptr, mask.codes_size,
1108 				      compat_mode);
1109 	}
1110 
1111 	case EVIOCSCLOCKID:
1112 		if (copy_from_user(&i, p, sizeof(unsigned int)))
1113 			return -EFAULT;
1114 
1115 		return evdev_set_clk_type(client, i);
1116 
1117 	case EVIOCGKEYCODE:
1118 		return evdev_handle_get_keycode(dev, p);
1119 
1120 	case EVIOCSKEYCODE:
1121 		return evdev_handle_set_keycode(dev, p);
1122 
1123 	case EVIOCGKEYCODE_V2:
1124 		return evdev_handle_get_keycode_v2(dev, p);
1125 
1126 	case EVIOCSKEYCODE_V2:
1127 		return evdev_handle_set_keycode_v2(dev, p);
1128 	}
1129 
1130 	size = _IOC_SIZE(cmd);
1131 
1132 	/* Now check variable-length commands */
1133 #define EVIOC_MASK_SIZE(nr)	((nr) & ~(_IOC_SIZEMASK << _IOC_SIZESHIFT))
1134 	switch (EVIOC_MASK_SIZE(cmd)) {
1135 
1136 	case EVIOCGPROP(0):
1137 		return bits_to_user(dev->propbit, INPUT_PROP_MAX,
1138 				    size, p, compat_mode);
1139 
1140 	case EVIOCGMTSLOTS(0):
1141 		return evdev_handle_mt_request(dev, size, ip);
1142 
1143 	case EVIOCGKEY(0):
1144 		return evdev_handle_get_val(client, dev, EV_KEY, dev->key,
1145 					    KEY_MAX, size, p, compat_mode);
1146 
1147 	case EVIOCGLED(0):
1148 		return evdev_handle_get_val(client, dev, EV_LED, dev->led,
1149 					    LED_MAX, size, p, compat_mode);
1150 
1151 	case EVIOCGSND(0):
1152 		return evdev_handle_get_val(client, dev, EV_SND, dev->snd,
1153 					    SND_MAX, size, p, compat_mode);
1154 
1155 	case EVIOCGSW(0):
1156 		return evdev_handle_get_val(client, dev, EV_SW, dev->sw,
1157 					    SW_MAX, size, p, compat_mode);
1158 
1159 	case EVIOCGNAME(0):
1160 		return str_to_user(dev->name, size, p);
1161 
1162 	case EVIOCGPHYS(0):
1163 		return str_to_user(dev->phys, size, p);
1164 
1165 	case EVIOCGUNIQ(0):
1166 		return str_to_user(dev->uniq, size, p);
1167 
1168 	case EVIOC_MASK_SIZE(EVIOCSFF):
1169 		if (input_ff_effect_from_user(p, size, &effect))
1170 			return -EFAULT;
1171 
1172 		error = input_ff_upload(dev, &effect, file);
1173 		if (error)
1174 			return error;
1175 
1176 		if (put_user(effect.id, &(((struct ff_effect __user *)p)->id)))
1177 			return -EFAULT;
1178 
1179 		return 0;
1180 	}
1181 
1182 	/* Multi-number variable-length handlers */
1183 	if (_IOC_TYPE(cmd) != 'E')
1184 		return -EINVAL;
1185 
1186 	if (_IOC_DIR(cmd) == _IOC_READ) {
1187 
1188 		if ((_IOC_NR(cmd) & ~EV_MAX) == _IOC_NR(EVIOCGBIT(0, 0)))
1189 			return handle_eviocgbit(dev,
1190 						_IOC_NR(cmd) & EV_MAX, size,
1191 						p, compat_mode);
1192 
1193 		if ((_IOC_NR(cmd) & ~ABS_MAX) == _IOC_NR(EVIOCGABS(0))) {
1194 
1195 			if (!dev->absinfo)
1196 				return -EINVAL;
1197 
1198 			t = _IOC_NR(cmd) & ABS_MAX;
1199 			abs = dev->absinfo[t];
1200 
1201 			if (copy_to_user(p, &abs, min_t(size_t,
1202 					size, sizeof(struct input_absinfo))))
1203 				return -EFAULT;
1204 
1205 			return 0;
1206 		}
1207 	}
1208 
1209 	if (_IOC_DIR(cmd) == _IOC_WRITE) {
1210 
1211 		if ((_IOC_NR(cmd) & ~ABS_MAX) == _IOC_NR(EVIOCSABS(0))) {
1212 
1213 			if (!dev->absinfo)
1214 				return -EINVAL;
1215 
1216 			t = _IOC_NR(cmd) & ABS_MAX;
1217 
1218 			if (copy_from_user(&abs, p, min_t(size_t,
1219 					size, sizeof(struct input_absinfo))))
1220 				return -EFAULT;
1221 
1222 			if (size < sizeof(struct input_absinfo))
1223 				abs.resolution = 0;
1224 
1225 			/* We can't change number of reserved MT slots */
1226 			if (t == ABS_MT_SLOT)
1227 				return -EINVAL;
1228 
1229 			/*
1230 			 * Take event lock to ensure that we are not
1231 			 * changing device parameters in the middle
1232 			 * of event.
1233 			 */
1234 			spin_lock_irq(&dev->event_lock);
1235 			dev->absinfo[t] = abs;
1236 			spin_unlock_irq(&dev->event_lock);
1237 
1238 			return 0;
1239 		}
1240 	}
1241 
1242 	return -EINVAL;
1243 }
1244 
1245 static long evdev_ioctl_handler(struct file *file, unsigned int cmd,
1246 				void __user *p, int compat_mode)
1247 {
1248 	struct evdev_client *client = file->private_data;
1249 	struct evdev *evdev = client->evdev;
1250 	int retval;
1251 
1252 	retval = mutex_lock_interruptible(&evdev->mutex);
1253 	if (retval)
1254 		return retval;
1255 
1256 	if (!evdev->exist || client->revoked) {
1257 		retval = -ENODEV;
1258 		goto out;
1259 	}
1260 
1261 	retval = evdev_do_ioctl(file, cmd, p, compat_mode);
1262 
1263  out:
1264 	mutex_unlock(&evdev->mutex);
1265 	return retval;
1266 }
1267 
1268 static long evdev_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
1269 {
1270 	return evdev_ioctl_handler(file, cmd, (void __user *)arg, 0);
1271 }
1272 
1273 #ifdef CONFIG_COMPAT
1274 static long evdev_ioctl_compat(struct file *file,
1275 				unsigned int cmd, unsigned long arg)
1276 {
1277 	return evdev_ioctl_handler(file, cmd, compat_ptr(arg), 1);
1278 }
1279 #endif
1280 
1281 static const struct file_operations evdev_fops = {
1282 	.owner		= THIS_MODULE,
1283 	.read		= evdev_read,
1284 	.write		= evdev_write,
1285 	.poll		= evdev_poll,
1286 	.open		= evdev_open,
1287 	.release	= evdev_release,
1288 	.unlocked_ioctl	= evdev_ioctl,
1289 #ifdef CONFIG_COMPAT
1290 	.compat_ioctl	= evdev_ioctl_compat,
1291 #endif
1292 	.fasync		= evdev_fasync,
1293 	.llseek		= no_llseek,
1294 };
1295 
1296 /*
1297  * Mark device non-existent. This disables writes, ioctls and
1298  * prevents new users from opening the device. Already posted
1299  * blocking reads will stay, however new ones will fail.
1300  */
1301 static void evdev_mark_dead(struct evdev *evdev)
1302 {
1303 	mutex_lock(&evdev->mutex);
1304 	evdev->exist = false;
1305 	mutex_unlock(&evdev->mutex);
1306 }
1307 
1308 static void evdev_cleanup(struct evdev *evdev)
1309 {
1310 	struct input_handle *handle = &evdev->handle;
1311 
1312 	evdev_mark_dead(evdev);
1313 	evdev_hangup(evdev);
1314 
1315 	/* evdev is marked dead so no one else accesses evdev->open */
1316 	if (evdev->open) {
1317 		input_flush_device(handle, NULL);
1318 		input_close_device(handle);
1319 	}
1320 }
1321 
1322 /*
1323  * Create new evdev device. Note that input core serializes calls
1324  * to connect and disconnect.
1325  */
1326 static int evdev_connect(struct input_handler *handler, struct input_dev *dev,
1327 			 const struct input_device_id *id)
1328 {
1329 	struct evdev *evdev;
1330 	int minor;
1331 	int dev_no;
1332 	int error;
1333 
1334 	minor = input_get_new_minor(EVDEV_MINOR_BASE, EVDEV_MINORS, true);
1335 	if (minor < 0) {
1336 		error = minor;
1337 		pr_err("failed to reserve new minor: %d\n", error);
1338 		return error;
1339 	}
1340 
1341 	evdev = kzalloc(sizeof(struct evdev), GFP_KERNEL);
1342 	if (!evdev) {
1343 		error = -ENOMEM;
1344 		goto err_free_minor;
1345 	}
1346 
1347 	INIT_LIST_HEAD(&evdev->client_list);
1348 	spin_lock_init(&evdev->client_lock);
1349 	mutex_init(&evdev->mutex);
1350 	evdev->exist = true;
1351 
1352 	dev_no = minor;
1353 	/* Normalize device number if it falls into legacy range */
1354 	if (dev_no < EVDEV_MINOR_BASE + EVDEV_MINORS)
1355 		dev_no -= EVDEV_MINOR_BASE;
1356 	dev_set_name(&evdev->dev, "event%d", dev_no);
1357 
1358 	evdev->handle.dev = input_get_device(dev);
1359 	evdev->handle.name = dev_name(&evdev->dev);
1360 	evdev->handle.handler = handler;
1361 	evdev->handle.private = evdev;
1362 
1363 	evdev->dev.devt = MKDEV(INPUT_MAJOR, minor);
1364 	evdev->dev.class = &input_class;
1365 	evdev->dev.parent = &dev->dev;
1366 	evdev->dev.release = evdev_free;
1367 	device_initialize(&evdev->dev);
1368 
1369 	error = input_register_handle(&evdev->handle);
1370 	if (error)
1371 		goto err_free_evdev;
1372 
1373 	cdev_init(&evdev->cdev, &evdev_fops);
1374 
1375 	error = cdev_device_add(&evdev->cdev, &evdev->dev);
1376 	if (error)
1377 		goto err_cleanup_evdev;
1378 
1379 	return 0;
1380 
1381  err_cleanup_evdev:
1382 	evdev_cleanup(evdev);
1383 	input_unregister_handle(&evdev->handle);
1384  err_free_evdev:
1385 	put_device(&evdev->dev);
1386  err_free_minor:
1387 	input_free_minor(minor);
1388 	return error;
1389 }
1390 
1391 static void evdev_disconnect(struct input_handle *handle)
1392 {
1393 	struct evdev *evdev = handle->private;
1394 
1395 	cdev_device_del(&evdev->cdev, &evdev->dev);
1396 	evdev_cleanup(evdev);
1397 	input_free_minor(MINOR(evdev->dev.devt));
1398 	input_unregister_handle(handle);
1399 	put_device(&evdev->dev);
1400 }
1401 
1402 static const struct input_device_id evdev_ids[] = {
1403 	{ .driver_info = 1 },	/* Matches all devices */
1404 	{ },			/* Terminating zero entry */
1405 };
1406 
1407 MODULE_DEVICE_TABLE(input, evdev_ids);
1408 
1409 static struct input_handler evdev_handler = {
1410 	.events		= evdev_events,
1411 	.connect	= evdev_connect,
1412 	.disconnect	= evdev_disconnect,
1413 	.legacy_minors	= true,
1414 	.minor		= EVDEV_MINOR_BASE,
1415 	.name		= "evdev",
1416 	.id_table	= evdev_ids,
1417 };
1418 
1419 static int __init evdev_init(void)
1420 {
1421 	return input_register_handler(&evdev_handler);
1422 }
1423 
1424 static void __exit evdev_exit(void)
1425 {
1426 	input_unregister_handler(&evdev_handler);
1427 }
1428 
1429 module_init(evdev_init);
1430 module_exit(evdev_exit);
1431 
1432 MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
1433 MODULE_DESCRIPTION("Input driver event char devices");
1434 MODULE_LICENSE("GPL");
1435