• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * The input core
4  *
5  * Copyright (c) 1999-2002 Vojtech Pavlik
6  */
7 
8 
9 #define pr_fmt(fmt) KBUILD_BASENAME ": " fmt
10 
11 #include <linux/init.h>
12 #include <linux/types.h>
13 #include <linux/idr.h>
14 #include <linux/input/mt.h>
15 #include <linux/module.h>
16 #include <linux/slab.h>
17 #include <linux/random.h>
18 #include <linux/major.h>
19 #include <linux/proc_fs.h>
20 #include <linux/sched.h>
21 #include <linux/seq_file.h>
22 #include <linux/poll.h>
23 #include <linux/device.h>
24 #include <linux/mutex.h>
25 #include <linux/rcupdate.h>
26 #include "input-compat.h"
27 #include "input-poller.h"
28 
29 MODULE_AUTHOR("Vojtech Pavlik <vojtech@suse.cz>");
30 MODULE_DESCRIPTION("Input core");
31 MODULE_LICENSE("GPL");
32 
33 #define INPUT_MAX_CHAR_DEVICES		1024
34 #define INPUT_FIRST_DYNAMIC_DEV		256
35 static DEFINE_IDA(input_ida);
36 
37 static LIST_HEAD(input_dev_list);
38 static LIST_HEAD(input_handler_list);
39 
40 /*
41  * input_mutex protects access to both input_dev_list and input_handler_list.
42  * This also causes input_[un]register_device and input_[un]register_handler
43  * be mutually exclusive which simplifies locking in drivers implementing
44  * input handlers.
45  */
46 static DEFINE_MUTEX(input_mutex);
47 
48 static const struct input_value input_value_sync = { EV_SYN, SYN_REPORT, 1 };
49 
is_event_supported(unsigned int code,unsigned long * bm,unsigned int max)50 static inline int is_event_supported(unsigned int code,
51 				     unsigned long *bm, unsigned int max)
52 {
53 	return code <= max && test_bit(code, bm);
54 }
55 
input_defuzz_abs_event(int value,int old_val,int fuzz)56 static int input_defuzz_abs_event(int value, int old_val, int fuzz)
57 {
58 	if (fuzz) {
59 		if (value > (long)old_val - fuzz / 2 &&
60 				value < (long)old_val + fuzz / 2)
61 			return old_val;
62 
63 		if (value > (long)old_val - fuzz &&
64 				value < (long)old_val + fuzz)
65 			return ((long)old_val * 3 + value) / 4;
66 
67 		if (value > (long)old_val - fuzz * 2 &&
68 				value < (long)old_val + fuzz * 2)
69 			return ((long)old_val + value) / 2;
70 	}
71 
72 	return value;
73 }
74 
input_start_autorepeat(struct input_dev * dev,int code)75 static void input_start_autorepeat(struct input_dev *dev, int code)
76 {
77 	if (test_bit(EV_REP, dev->evbit) &&
78 	    dev->rep[REP_PERIOD] && dev->rep[REP_DELAY] &&
79 	    dev->timer.function) {
80 		dev->repeat_key = code;
81 		mod_timer(&dev->timer,
82 			  jiffies + msecs_to_jiffies(dev->rep[REP_DELAY]));
83 	}
84 }
85 
input_stop_autorepeat(struct input_dev * dev)86 static void input_stop_autorepeat(struct input_dev *dev)
87 {
88 	del_timer(&dev->timer);
89 }
90 
91 /*
92  * Pass event first through all filters and then, if event has not been
93  * filtered out, through all open handles. This function is called with
94  * dev->event_lock held and interrupts disabled.
95  */
input_to_handler(struct input_handle * handle,struct input_value * vals,unsigned int count)96 static unsigned int input_to_handler(struct input_handle *handle,
97 			struct input_value *vals, unsigned int count)
98 {
99 	struct input_handler *handler = handle->handler;
100 	struct input_value *end = vals;
101 	struct input_value *v;
102 
103 	if (handler->filter) {
104 		for (v = vals; v != vals + count; v++) {
105 			if (handler->filter(handle, v->type, v->code, v->value))
106 				continue;
107 			if (end != v)
108 				*end = *v;
109 			end++;
110 		}
111 		count = end - vals;
112 	}
113 
114 	if (!count)
115 		return 0;
116 
117 	if (handler->events)
118 		handler->events(handle, vals, count);
119 	else if (handler->event)
120 		for (v = vals; v != vals + count; v++)
121 			handler->event(handle, v->type, v->code, v->value);
122 
123 	return count;
124 }
125 
126 /*
127  * Pass values first through all filters and then, if event has not been
128  * filtered out, through all open handles. This function is called with
129  * dev->event_lock held and interrupts disabled.
130  */
input_pass_values(struct input_dev * dev,struct input_value * vals,unsigned int count)131 static void input_pass_values(struct input_dev *dev,
132 			      struct input_value *vals, unsigned int count)
133 {
134 	struct input_handle *handle;
135 	struct input_value *v;
136 
137 	if (!count)
138 		return;
139 
140 	rcu_read_lock();
141 
142 	handle = rcu_dereference(dev->grab);
143 	if (handle) {
144 		count = input_to_handler(handle, vals, count);
145 	} else {
146 		list_for_each_entry_rcu(handle, &dev->h_list, d_node)
147 			if (handle->open) {
148 				count = input_to_handler(handle, vals, count);
149 				if (!count)
150 					break;
151 			}
152 	}
153 
154 	rcu_read_unlock();
155 
156 	/* trigger auto repeat for key events */
157 	if (test_bit(EV_REP, dev->evbit) && test_bit(EV_KEY, dev->evbit)) {
158 		for (v = vals; v != vals + count; v++) {
159 			if (v->type == EV_KEY && v->value != 2) {
160 				if (v->value)
161 					input_start_autorepeat(dev, v->code);
162 				else
163 					input_stop_autorepeat(dev);
164 			}
165 		}
166 	}
167 }
168 
input_pass_event(struct input_dev * dev,unsigned int type,unsigned int code,int value)169 static void input_pass_event(struct input_dev *dev,
170 			     unsigned int type, unsigned int code, int value)
171 {
172 	struct input_value vals[] = { { type, code, value } };
173 
174 	input_pass_values(dev, vals, ARRAY_SIZE(vals));
175 }
176 
177 /*
178  * Generate software autorepeat event. Note that we take
179  * dev->event_lock here to avoid racing with input_event
180  * which may cause keys get "stuck".
181  */
input_repeat_key(struct timer_list * t)182 static void input_repeat_key(struct timer_list *t)
183 {
184 	struct input_dev *dev = from_timer(dev, t, timer);
185 	unsigned long flags;
186 
187 	spin_lock_irqsave(&dev->event_lock, flags);
188 
189 	if (test_bit(dev->repeat_key, dev->key) &&
190 	    is_event_supported(dev->repeat_key, dev->keybit, KEY_MAX)) {
191 		struct input_value vals[] =  {
192 			{ EV_KEY, dev->repeat_key, 2 },
193 			input_value_sync
194 		};
195 
196 		input_set_timestamp(dev, ktime_get());
197 		input_pass_values(dev, vals, ARRAY_SIZE(vals));
198 
199 		if (dev->rep[REP_PERIOD])
200 			mod_timer(&dev->timer, jiffies +
201 					msecs_to_jiffies(dev->rep[REP_PERIOD]));
202 	}
203 
204 	spin_unlock_irqrestore(&dev->event_lock, flags);
205 }
206 
207 #define INPUT_IGNORE_EVENT	0
208 #define INPUT_PASS_TO_HANDLERS	1
209 #define INPUT_PASS_TO_DEVICE	2
210 #define INPUT_SLOT		4
211 #define INPUT_FLUSH		8
212 #define INPUT_PASS_TO_ALL	(INPUT_PASS_TO_HANDLERS | INPUT_PASS_TO_DEVICE)
213 
input_handle_abs_event(struct input_dev * dev,unsigned int code,int * pval)214 static int input_handle_abs_event(struct input_dev *dev,
215 				  unsigned int code, int *pval)
216 {
217 	struct input_mt *mt = dev->mt;
218 	bool is_mt_event;
219 	int *pold;
220 
221 	if (code == ABS_MT_SLOT) {
222 		/*
223 		 * "Stage" the event; we'll flush it later, when we
224 		 * get actual touch data.
225 		 */
226 		if (mt && *pval >= 0 && *pval < mt->num_slots)
227 			mt->slot = *pval;
228 
229 		return INPUT_IGNORE_EVENT;
230 	}
231 
232 	is_mt_event = input_is_mt_value(code);
233 
234 	if (!is_mt_event) {
235 		pold = &dev->absinfo[code].value;
236 	} else if (mt) {
237 		pold = &mt->slots[mt->slot].abs[code - ABS_MT_FIRST];
238 	} else {
239 		/*
240 		 * Bypass filtering for multi-touch events when
241 		 * not employing slots.
242 		 */
243 		pold = NULL;
244 	}
245 
246 	if (pold) {
247 		*pval = input_defuzz_abs_event(*pval, *pold,
248 						dev->absinfo[code].fuzz);
249 		if (*pold == *pval)
250 			return INPUT_IGNORE_EVENT;
251 
252 		*pold = *pval;
253 	}
254 
255 	/* Flush pending "slot" event */
256 	if (is_mt_event && mt && mt->slot != input_abs_get_val(dev, ABS_MT_SLOT)) {
257 		input_abs_set_val(dev, ABS_MT_SLOT, mt->slot);
258 		return INPUT_PASS_TO_HANDLERS | INPUT_SLOT;
259 	}
260 
261 	return INPUT_PASS_TO_HANDLERS;
262 }
263 
input_get_disposition(struct input_dev * dev,unsigned int type,unsigned int code,int * pval)264 static int input_get_disposition(struct input_dev *dev,
265 			  unsigned int type, unsigned int code, int *pval)
266 {
267 	int disposition = INPUT_IGNORE_EVENT;
268 	int value = *pval;
269 
270 	switch (type) {
271 
272 	case EV_SYN:
273 		switch (code) {
274 		case SYN_CONFIG:
275 			disposition = INPUT_PASS_TO_ALL;
276 			break;
277 
278 		case SYN_REPORT:
279 			disposition = INPUT_PASS_TO_HANDLERS | INPUT_FLUSH;
280 			break;
281 		case SYN_MT_REPORT:
282 			disposition = INPUT_PASS_TO_HANDLERS;
283 			break;
284 		}
285 		break;
286 
287 	case EV_KEY:
288 		if (is_event_supported(code, dev->keybit, KEY_MAX)) {
289 
290 			/* auto-repeat bypasses state updates */
291 			if (value == 2) {
292 				disposition = INPUT_PASS_TO_HANDLERS;
293 				break;
294 			}
295 
296 			if (!!test_bit(code, dev->key) != !!value) {
297 
298 				__change_bit(code, dev->key);
299 				disposition = INPUT_PASS_TO_HANDLERS;
300 			}
301 		}
302 		break;
303 
304 	case EV_SW:
305 		if (is_event_supported(code, dev->swbit, SW_MAX) &&
306 		    !!test_bit(code, dev->sw) != !!value) {
307 
308 			__change_bit(code, dev->sw);
309 			disposition = INPUT_PASS_TO_HANDLERS;
310 		}
311 		break;
312 
313 	case EV_ABS:
314 		if (is_event_supported(code, dev->absbit, ABS_MAX))
315 			disposition = input_handle_abs_event(dev, code, &value);
316 
317 		break;
318 
319 	case EV_REL:
320 		if (is_event_supported(code, dev->relbit, REL_MAX) && value)
321 			disposition = INPUT_PASS_TO_HANDLERS;
322 
323 		break;
324 
325 	case EV_MSC:
326 		if (is_event_supported(code, dev->mscbit, MSC_MAX))
327 			disposition = INPUT_PASS_TO_ALL;
328 
329 		break;
330 
331 	case EV_LED:
332 		if (is_event_supported(code, dev->ledbit, LED_MAX) &&
333 		    !!test_bit(code, dev->led) != !!value) {
334 
335 			__change_bit(code, dev->led);
336 			disposition = INPUT_PASS_TO_ALL;
337 		}
338 		break;
339 
340 	case EV_SND:
341 		if (is_event_supported(code, dev->sndbit, SND_MAX)) {
342 
343 			if (!!test_bit(code, dev->snd) != !!value)
344 				__change_bit(code, dev->snd);
345 			disposition = INPUT_PASS_TO_ALL;
346 		}
347 		break;
348 
349 	case EV_REP:
350 		if (code <= REP_MAX && value >= 0 && dev->rep[code] != value) {
351 			dev->rep[code] = value;
352 			disposition = INPUT_PASS_TO_ALL;
353 		}
354 		break;
355 
356 	case EV_FF:
357 		if (value >= 0)
358 			disposition = INPUT_PASS_TO_ALL;
359 		break;
360 
361 	case EV_PWR:
362 		disposition = INPUT_PASS_TO_ALL;
363 		break;
364 	}
365 
366 	*pval = value;
367 	return disposition;
368 }
369 
input_handle_event(struct input_dev * dev,unsigned int type,unsigned int code,int value)370 static void input_handle_event(struct input_dev *dev,
371 			       unsigned int type, unsigned int code, int value)
372 {
373 	int disposition = input_get_disposition(dev, type, code, &value);
374 
375 	if (disposition != INPUT_IGNORE_EVENT && type != EV_SYN)
376 		add_input_randomness(type, code, value);
377 
378 	if ((disposition & INPUT_PASS_TO_DEVICE) && dev->event)
379 		dev->event(dev, type, code, value);
380 
381 	if (!dev->vals)
382 		return;
383 
384 	if (disposition & INPUT_PASS_TO_HANDLERS) {
385 		struct input_value *v;
386 
387 		if (disposition & INPUT_SLOT) {
388 			v = &dev->vals[dev->num_vals++];
389 			v->type = EV_ABS;
390 			v->code = ABS_MT_SLOT;
391 			v->value = dev->mt->slot;
392 		}
393 
394 		v = &dev->vals[dev->num_vals++];
395 		v->type = type;
396 		v->code = code;
397 		v->value = value;
398 	}
399 
400 	if (disposition & INPUT_FLUSH) {
401 		if (dev->num_vals >= 2)
402 			input_pass_values(dev, dev->vals, dev->num_vals);
403 		dev->num_vals = 0;
404 		/*
405 		 * Reset the timestamp on flush so we won't end up
406 		 * with a stale one. Note we only need to reset the
407 		 * monolithic one as we use its presence when deciding
408 		 * whether to generate a synthetic timestamp.
409 		 */
410 		dev->timestamp[INPUT_CLK_MONO] = ktime_set(0, 0);
411 	} else if (dev->num_vals >= dev->max_vals - 2) {
412 		dev->vals[dev->num_vals++] = input_value_sync;
413 		input_pass_values(dev, dev->vals, dev->num_vals);
414 		dev->num_vals = 0;
415 	}
416 
417 }
418 
419 /**
420  * input_event() - report new input event
421  * @dev: device that generated the event
422  * @type: type of the event
423  * @code: event code
424  * @value: value of the event
425  *
426  * This function should be used by drivers implementing various input
427  * devices to report input events. See also input_inject_event().
428  *
429  * NOTE: input_event() may be safely used right after input device was
430  * allocated with input_allocate_device(), even before it is registered
431  * with input_register_device(), but the event will not reach any of the
432  * input handlers. Such early invocation of input_event() may be used
433  * to 'seed' initial state of a switch or initial position of absolute
434  * axis, etc.
435  */
input_event(struct input_dev * dev,unsigned int type,unsigned int code,int value)436 void input_event(struct input_dev *dev,
437 		 unsigned int type, unsigned int code, int value)
438 {
439 	unsigned long flags;
440 
441 	if (is_event_supported(type, dev->evbit, EV_MAX)) {
442 
443 		spin_lock_irqsave(&dev->event_lock, flags);
444 		input_handle_event(dev, type, code, value);
445 		spin_unlock_irqrestore(&dev->event_lock, flags);
446 	}
447 }
448 EXPORT_SYMBOL(input_event);
449 
450 /**
451  * input_inject_event() - send input event from input handler
452  * @handle: input handle to send event through
453  * @type: type of the event
454  * @code: event code
455  * @value: value of the event
456  *
457  * Similar to input_event() but will ignore event if device is
458  * "grabbed" and handle injecting event is not the one that owns
459  * the device.
460  */
input_inject_event(struct input_handle * handle,unsigned int type,unsigned int code,int value)461 void input_inject_event(struct input_handle *handle,
462 			unsigned int type, unsigned int code, int value)
463 {
464 	struct input_dev *dev = handle->dev;
465 	struct input_handle *grab;
466 	unsigned long flags;
467 
468 	if (is_event_supported(type, dev->evbit, EV_MAX)) {
469 		spin_lock_irqsave(&dev->event_lock, flags);
470 
471 		rcu_read_lock();
472 		grab = rcu_dereference(dev->grab);
473 		if (!grab || grab == handle)
474 			input_handle_event(dev, type, code, value);
475 		rcu_read_unlock();
476 
477 		spin_unlock_irqrestore(&dev->event_lock, flags);
478 	}
479 }
480 EXPORT_SYMBOL(input_inject_event);
481 
482 /**
483  * input_alloc_absinfo - allocates array of input_absinfo structs
484  * @dev: the input device emitting absolute events
485  *
486  * If the absinfo struct the caller asked for is already allocated, this
487  * functions will not do anything.
488  */
input_alloc_absinfo(struct input_dev * dev)489 void input_alloc_absinfo(struct input_dev *dev)
490 {
491 	if (dev->absinfo)
492 		return;
493 
494 	dev->absinfo = kcalloc(ABS_CNT, sizeof(*dev->absinfo), GFP_KERNEL);
495 	if (!dev->absinfo) {
496 		dev_err(dev->dev.parent ?: &dev->dev,
497 			"%s: unable to allocate memory\n", __func__);
498 		/*
499 		 * We will handle this allocation failure in
500 		 * input_register_device() when we refuse to register input
501 		 * device with ABS bits but without absinfo.
502 		 */
503 	}
504 }
505 EXPORT_SYMBOL(input_alloc_absinfo);
506 
input_set_abs_params(struct input_dev * dev,unsigned int axis,int min,int max,int fuzz,int flat)507 void input_set_abs_params(struct input_dev *dev, unsigned int axis,
508 			  int min, int max, int fuzz, int flat)
509 {
510 	struct input_absinfo *absinfo;
511 
512 	input_alloc_absinfo(dev);
513 	if (!dev->absinfo)
514 		return;
515 
516 	absinfo = &dev->absinfo[axis];
517 	absinfo->minimum = min;
518 	absinfo->maximum = max;
519 	absinfo->fuzz = fuzz;
520 	absinfo->flat = flat;
521 
522 	__set_bit(EV_ABS, dev->evbit);
523 	__set_bit(axis, dev->absbit);
524 }
525 EXPORT_SYMBOL(input_set_abs_params);
526 
527 
528 /**
529  * input_grab_device - grabs device for exclusive use
530  * @handle: input handle that wants to own the device
531  *
532  * When a device is grabbed by an input handle all events generated by
533  * the device are delivered only to this handle. Also events injected
534  * by other input handles are ignored while device is grabbed.
535  */
input_grab_device(struct input_handle * handle)536 int input_grab_device(struct input_handle *handle)
537 {
538 	struct input_dev *dev = handle->dev;
539 	int retval;
540 
541 	retval = mutex_lock_interruptible(&dev->mutex);
542 	if (retval)
543 		return retval;
544 
545 	if (dev->grab) {
546 		retval = -EBUSY;
547 		goto out;
548 	}
549 
550 	rcu_assign_pointer(dev->grab, handle);
551 
552  out:
553 	mutex_unlock(&dev->mutex);
554 	return retval;
555 }
556 EXPORT_SYMBOL(input_grab_device);
557 
__input_release_device(struct input_handle * handle)558 static void __input_release_device(struct input_handle *handle)
559 {
560 	struct input_dev *dev = handle->dev;
561 	struct input_handle *grabber;
562 
563 	grabber = rcu_dereference_protected(dev->grab,
564 					    lockdep_is_held(&dev->mutex));
565 	if (grabber == handle) {
566 		rcu_assign_pointer(dev->grab, NULL);
567 		/* Make sure input_pass_event() notices that grab is gone */
568 		synchronize_rcu();
569 
570 		list_for_each_entry(handle, &dev->h_list, d_node)
571 			if (handle->open && handle->handler->start)
572 				handle->handler->start(handle);
573 	}
574 }
575 
576 /**
577  * input_release_device - release previously grabbed device
578  * @handle: input handle that owns the device
579  *
580  * Releases previously grabbed device so that other input handles can
581  * start receiving input events. Upon release all handlers attached
582  * to the device have their start() method called so they have a change
583  * to synchronize device state with the rest of the system.
584  */
input_release_device(struct input_handle * handle)585 void input_release_device(struct input_handle *handle)
586 {
587 	struct input_dev *dev = handle->dev;
588 
589 	mutex_lock(&dev->mutex);
590 	__input_release_device(handle);
591 	mutex_unlock(&dev->mutex);
592 }
593 EXPORT_SYMBOL(input_release_device);
594 
595 /**
596  * input_open_device - open input device
597  * @handle: handle through which device is being accessed
598  *
599  * This function should be called by input handlers when they
600  * want to start receive events from given input device.
601  */
input_open_device(struct input_handle * handle)602 int input_open_device(struct input_handle *handle)
603 {
604 	struct input_dev *dev = handle->dev;
605 	int retval;
606 
607 	retval = mutex_lock_interruptible(&dev->mutex);
608 	if (retval)
609 		return retval;
610 
611 	if (dev->going_away) {
612 		retval = -ENODEV;
613 		goto out;
614 	}
615 
616 	handle->open++;
617 
618 	if (dev->users++) {
619 		/*
620 		 * Device is already opened, so we can exit immediately and
621 		 * report success.
622 		 */
623 		goto out;
624 	}
625 
626 	if (dev->open) {
627 		retval = dev->open(dev);
628 		if (retval) {
629 			dev->users--;
630 			handle->open--;
631 			/*
632 			 * Make sure we are not delivering any more events
633 			 * through this handle
634 			 */
635 			synchronize_rcu();
636 			goto out;
637 		}
638 	}
639 
640 	if (dev->poller)
641 		input_dev_poller_start(dev->poller);
642 
643  out:
644 	mutex_unlock(&dev->mutex);
645 	return retval;
646 }
647 EXPORT_SYMBOL(input_open_device);
648 
input_flush_device(struct input_handle * handle,struct file * file)649 int input_flush_device(struct input_handle *handle, struct file *file)
650 {
651 	struct input_dev *dev = handle->dev;
652 	int retval;
653 
654 	retval = mutex_lock_interruptible(&dev->mutex);
655 	if (retval)
656 		return retval;
657 
658 	if (dev->flush)
659 		retval = dev->flush(dev, file);
660 
661 	mutex_unlock(&dev->mutex);
662 	return retval;
663 }
664 EXPORT_SYMBOL(input_flush_device);
665 
666 /**
667  * input_close_device - close input device
668  * @handle: handle through which device is being accessed
669  *
670  * This function should be called by input handlers when they
671  * want to stop receive events from given input device.
672  */
input_close_device(struct input_handle * handle)673 void input_close_device(struct input_handle *handle)
674 {
675 	struct input_dev *dev = handle->dev;
676 
677 	mutex_lock(&dev->mutex);
678 
679 	__input_release_device(handle);
680 
681 	if (!--dev->users) {
682 		if (dev->poller)
683 			input_dev_poller_stop(dev->poller);
684 
685 		if (dev->close)
686 			dev->close(dev);
687 	}
688 
689 	if (!--handle->open) {
690 		/*
691 		 * synchronize_rcu() makes sure that input_pass_event()
692 		 * completed and that no more input events are delivered
693 		 * through this handle
694 		 */
695 		synchronize_rcu();
696 	}
697 
698 	mutex_unlock(&dev->mutex);
699 }
700 EXPORT_SYMBOL(input_close_device);
701 
702 /*
703  * Simulate keyup events for all keys that are marked as pressed.
704  * The function must be called with dev->event_lock held.
705  */
input_dev_release_keys(struct input_dev * dev)706 static void input_dev_release_keys(struct input_dev *dev)
707 {
708 	bool need_sync = false;
709 	int code;
710 
711 	if (is_event_supported(EV_KEY, dev->evbit, EV_MAX)) {
712 		for_each_set_bit(code, dev->key, KEY_CNT) {
713 			input_pass_event(dev, EV_KEY, code, 0);
714 			need_sync = true;
715 		}
716 
717 		if (need_sync)
718 			input_pass_event(dev, EV_SYN, SYN_REPORT, 1);
719 
720 		memset(dev->key, 0, sizeof(dev->key));
721 	}
722 }
723 
724 /*
725  * Prepare device for unregistering
726  */
input_disconnect_device(struct input_dev * dev)727 static void input_disconnect_device(struct input_dev *dev)
728 {
729 	struct input_handle *handle;
730 
731 	/*
732 	 * Mark device as going away. Note that we take dev->mutex here
733 	 * not to protect access to dev->going_away but rather to ensure
734 	 * that there are no threads in the middle of input_open_device()
735 	 */
736 	mutex_lock(&dev->mutex);
737 	dev->going_away = true;
738 	mutex_unlock(&dev->mutex);
739 
740 	spin_lock_irq(&dev->event_lock);
741 
742 	/*
743 	 * Simulate keyup events for all pressed keys so that handlers
744 	 * are not left with "stuck" keys. The driver may continue
745 	 * generate events even after we done here but they will not
746 	 * reach any handlers.
747 	 */
748 	input_dev_release_keys(dev);
749 
750 	list_for_each_entry(handle, &dev->h_list, d_node)
751 		handle->open = 0;
752 
753 	spin_unlock_irq(&dev->event_lock);
754 }
755 
756 /**
757  * input_scancode_to_scalar() - converts scancode in &struct input_keymap_entry
758  * @ke: keymap entry containing scancode to be converted.
759  * @scancode: pointer to the location where converted scancode should
760  *	be stored.
761  *
762  * This function is used to convert scancode stored in &struct keymap_entry
763  * into scalar form understood by legacy keymap handling methods. These
764  * methods expect scancodes to be represented as 'unsigned int'.
765  */
input_scancode_to_scalar(const struct input_keymap_entry * ke,unsigned int * scancode)766 int input_scancode_to_scalar(const struct input_keymap_entry *ke,
767 			     unsigned int *scancode)
768 {
769 	switch (ke->len) {
770 	case 1:
771 		*scancode = *((u8 *)ke->scancode);
772 		break;
773 
774 	case 2:
775 		*scancode = *((u16 *)ke->scancode);
776 		break;
777 
778 	case 4:
779 		*scancode = *((u32 *)ke->scancode);
780 		break;
781 
782 	default:
783 		return -EINVAL;
784 	}
785 
786 	return 0;
787 }
788 EXPORT_SYMBOL(input_scancode_to_scalar);
789 
790 /*
791  * Those routines handle the default case where no [gs]etkeycode() is
792  * defined. In this case, an array indexed by the scancode is used.
793  */
794 
input_fetch_keycode(struct input_dev * dev,unsigned int index)795 static unsigned int input_fetch_keycode(struct input_dev *dev,
796 					unsigned int index)
797 {
798 	switch (dev->keycodesize) {
799 	case 1:
800 		return ((u8 *)dev->keycode)[index];
801 
802 	case 2:
803 		return ((u16 *)dev->keycode)[index];
804 
805 	default:
806 		return ((u32 *)dev->keycode)[index];
807 	}
808 }
809 
input_default_getkeycode(struct input_dev * dev,struct input_keymap_entry * ke)810 static int input_default_getkeycode(struct input_dev *dev,
811 				    struct input_keymap_entry *ke)
812 {
813 	unsigned int index;
814 	int error;
815 
816 	if (!dev->keycodesize)
817 		return -EINVAL;
818 
819 	if (ke->flags & INPUT_KEYMAP_BY_INDEX)
820 		index = ke->index;
821 	else {
822 		error = input_scancode_to_scalar(ke, &index);
823 		if (error)
824 			return error;
825 	}
826 
827 	if (index >= dev->keycodemax)
828 		return -EINVAL;
829 
830 	ke->keycode = input_fetch_keycode(dev, index);
831 	ke->index = index;
832 	ke->len = sizeof(index);
833 	memcpy(ke->scancode, &index, sizeof(index));
834 
835 	return 0;
836 }
837 
input_default_setkeycode(struct input_dev * dev,const struct input_keymap_entry * ke,unsigned int * old_keycode)838 static int input_default_setkeycode(struct input_dev *dev,
839 				    const struct input_keymap_entry *ke,
840 				    unsigned int *old_keycode)
841 {
842 	unsigned int index;
843 	int error;
844 	int i;
845 
846 	if (!dev->keycodesize)
847 		return -EINVAL;
848 
849 	if (ke->flags & INPUT_KEYMAP_BY_INDEX) {
850 		index = ke->index;
851 	} else {
852 		error = input_scancode_to_scalar(ke, &index);
853 		if (error)
854 			return error;
855 	}
856 
857 	if (index >= dev->keycodemax)
858 		return -EINVAL;
859 
860 	if (dev->keycodesize < sizeof(ke->keycode) &&
861 			(ke->keycode >> (dev->keycodesize * 8)))
862 		return -EINVAL;
863 
864 	switch (dev->keycodesize) {
865 		case 1: {
866 			u8 *k = (u8 *)dev->keycode;
867 			*old_keycode = k[index];
868 			k[index] = ke->keycode;
869 			break;
870 		}
871 		case 2: {
872 			u16 *k = (u16 *)dev->keycode;
873 			*old_keycode = k[index];
874 			k[index] = ke->keycode;
875 			break;
876 		}
877 		default: {
878 			u32 *k = (u32 *)dev->keycode;
879 			*old_keycode = k[index];
880 			k[index] = ke->keycode;
881 			break;
882 		}
883 	}
884 
885 	if (*old_keycode <= KEY_MAX) {
886 		__clear_bit(*old_keycode, dev->keybit);
887 		for (i = 0; i < dev->keycodemax; i++) {
888 			if (input_fetch_keycode(dev, i) == *old_keycode) {
889 				__set_bit(*old_keycode, dev->keybit);
890 				/* Setting the bit twice is useless, so break */
891 				break;
892 			}
893 		}
894 	}
895 
896 	__set_bit(ke->keycode, dev->keybit);
897 	return 0;
898 }
899 
900 /**
901  * input_get_keycode - retrieve keycode currently mapped to a given scancode
902  * @dev: input device which keymap is being queried
903  * @ke: keymap entry
904  *
905  * This function should be called by anyone interested in retrieving current
906  * keymap. Presently evdev handlers use it.
907  */
input_get_keycode(struct input_dev * dev,struct input_keymap_entry * ke)908 int input_get_keycode(struct input_dev *dev, struct input_keymap_entry *ke)
909 {
910 	unsigned long flags;
911 	int retval;
912 
913 	spin_lock_irqsave(&dev->event_lock, flags);
914 	retval = dev->getkeycode(dev, ke);
915 	spin_unlock_irqrestore(&dev->event_lock, flags);
916 
917 	return retval;
918 }
919 EXPORT_SYMBOL(input_get_keycode);
920 
921 /**
922  * input_set_keycode - attribute a keycode to a given scancode
923  * @dev: input device which keymap is being updated
924  * @ke: new keymap entry
925  *
926  * This function should be called by anyone needing to update current
927  * keymap. Presently keyboard and evdev handlers use it.
928  */
input_set_keycode(struct input_dev * dev,const struct input_keymap_entry * ke)929 int input_set_keycode(struct input_dev *dev,
930 		      const struct input_keymap_entry *ke)
931 {
932 	unsigned long flags;
933 	unsigned int old_keycode;
934 	int retval;
935 
936 	if (ke->keycode > KEY_MAX)
937 		return -EINVAL;
938 
939 	spin_lock_irqsave(&dev->event_lock, flags);
940 
941 	retval = dev->setkeycode(dev, ke, &old_keycode);
942 	if (retval)
943 		goto out;
944 
945 	/* Make sure KEY_RESERVED did not get enabled. */
946 	__clear_bit(KEY_RESERVED, dev->keybit);
947 
948 	/*
949 	 * Simulate keyup event if keycode is not present
950 	 * in the keymap anymore
951 	 */
952 	if (old_keycode > KEY_MAX) {
953 		dev_warn(dev->dev.parent ?: &dev->dev,
954 			 "%s: got too big old keycode %#x\n",
955 			 __func__, old_keycode);
956 	} else if (test_bit(EV_KEY, dev->evbit) &&
957 		   !is_event_supported(old_keycode, dev->keybit, KEY_MAX) &&
958 		   __test_and_clear_bit(old_keycode, dev->key)) {
959 		struct input_value vals[] =  {
960 			{ EV_KEY, old_keycode, 0 },
961 			input_value_sync
962 		};
963 
964 		input_pass_values(dev, vals, ARRAY_SIZE(vals));
965 	}
966 
967  out:
968 	spin_unlock_irqrestore(&dev->event_lock, flags);
969 
970 	return retval;
971 }
972 EXPORT_SYMBOL(input_set_keycode);
973 
input_match_device_id(const struct input_dev * dev,const struct input_device_id * id)974 bool input_match_device_id(const struct input_dev *dev,
975 			   const struct input_device_id *id)
976 {
977 	if (id->flags & INPUT_DEVICE_ID_MATCH_BUS)
978 		if (id->bustype != dev->id.bustype)
979 			return false;
980 
981 	if (id->flags & INPUT_DEVICE_ID_MATCH_VENDOR)
982 		if (id->vendor != dev->id.vendor)
983 			return false;
984 
985 	if (id->flags & INPUT_DEVICE_ID_MATCH_PRODUCT)
986 		if (id->product != dev->id.product)
987 			return false;
988 
989 	if (id->flags & INPUT_DEVICE_ID_MATCH_VERSION)
990 		if (id->version != dev->id.version)
991 			return false;
992 
993 	if (!bitmap_subset(id->evbit, dev->evbit, EV_MAX) ||
994 	    !bitmap_subset(id->keybit, dev->keybit, KEY_MAX) ||
995 	    !bitmap_subset(id->relbit, dev->relbit, REL_MAX) ||
996 	    !bitmap_subset(id->absbit, dev->absbit, ABS_MAX) ||
997 	    !bitmap_subset(id->mscbit, dev->mscbit, MSC_MAX) ||
998 	    !bitmap_subset(id->ledbit, dev->ledbit, LED_MAX) ||
999 	    !bitmap_subset(id->sndbit, dev->sndbit, SND_MAX) ||
1000 	    !bitmap_subset(id->ffbit, dev->ffbit, FF_MAX) ||
1001 	    !bitmap_subset(id->swbit, dev->swbit, SW_MAX) ||
1002 	    !bitmap_subset(id->propbit, dev->propbit, INPUT_PROP_MAX)) {
1003 		return false;
1004 	}
1005 
1006 	return true;
1007 }
1008 EXPORT_SYMBOL(input_match_device_id);
1009 
input_match_device(struct input_handler * handler,struct input_dev * dev)1010 static const struct input_device_id *input_match_device(struct input_handler *handler,
1011 							struct input_dev *dev)
1012 {
1013 	const struct input_device_id *id;
1014 
1015 	for (id = handler->id_table; id->flags || id->driver_info; id++) {
1016 		if (input_match_device_id(dev, id) &&
1017 		    (!handler->match || handler->match(handler, dev))) {
1018 			return id;
1019 		}
1020 	}
1021 
1022 	return NULL;
1023 }
1024 
input_attach_handler(struct input_dev * dev,struct input_handler * handler)1025 static int input_attach_handler(struct input_dev *dev, struct input_handler *handler)
1026 {
1027 	const struct input_device_id *id;
1028 	int error;
1029 
1030 	id = input_match_device(handler, dev);
1031 	if (!id)
1032 		return -ENODEV;
1033 
1034 	error = handler->connect(handler, dev, id);
1035 	if (error && error != -ENODEV)
1036 		pr_err("failed to attach handler %s to device %s, error: %d\n",
1037 		       handler->name, kobject_name(&dev->dev.kobj), error);
1038 
1039 	return error;
1040 }
1041 
1042 #ifdef CONFIG_COMPAT
1043 
input_bits_to_string(char * buf,int buf_size,unsigned long bits,bool skip_empty)1044 static int input_bits_to_string(char *buf, int buf_size,
1045 				unsigned long bits, bool skip_empty)
1046 {
1047 	int len = 0;
1048 
1049 	if (in_compat_syscall()) {
1050 		u32 dword = bits >> 32;
1051 		if (dword || !skip_empty)
1052 			len += snprintf(buf, buf_size, "%x ", dword);
1053 
1054 		dword = bits & 0xffffffffUL;
1055 		if (dword || !skip_empty || len)
1056 			len += snprintf(buf + len, max(buf_size - len, 0),
1057 					"%x", dword);
1058 	} else {
1059 		if (bits || !skip_empty)
1060 			len += snprintf(buf, buf_size, "%lx", bits);
1061 	}
1062 
1063 	return len;
1064 }
1065 
1066 #else /* !CONFIG_COMPAT */
1067 
input_bits_to_string(char * buf,int buf_size,unsigned long bits,bool skip_empty)1068 static int input_bits_to_string(char *buf, int buf_size,
1069 				unsigned long bits, bool skip_empty)
1070 {
1071 	return bits || !skip_empty ?
1072 		snprintf(buf, buf_size, "%lx", bits) : 0;
1073 }
1074 
1075 #endif
1076 
1077 #ifdef CONFIG_PROC_FS
1078 
1079 static struct proc_dir_entry *proc_bus_input_dir;
1080 static DECLARE_WAIT_QUEUE_HEAD(input_devices_poll_wait);
1081 static int input_devices_state;
1082 
input_wakeup_procfs_readers(void)1083 static inline void input_wakeup_procfs_readers(void)
1084 {
1085 	input_devices_state++;
1086 	wake_up(&input_devices_poll_wait);
1087 }
1088 
input_proc_devices_poll(struct file * file,poll_table * wait)1089 static __poll_t input_proc_devices_poll(struct file *file, poll_table *wait)
1090 {
1091 	poll_wait(file, &input_devices_poll_wait, wait);
1092 	if (file->f_version != input_devices_state) {
1093 		file->f_version = input_devices_state;
1094 		return EPOLLIN | EPOLLRDNORM;
1095 	}
1096 
1097 	return 0;
1098 }
1099 
1100 union input_seq_state {
1101 	struct {
1102 		unsigned short pos;
1103 		bool mutex_acquired;
1104 	};
1105 	void *p;
1106 };
1107 
input_devices_seq_start(struct seq_file * seq,loff_t * pos)1108 static void *input_devices_seq_start(struct seq_file *seq, loff_t *pos)
1109 {
1110 	union input_seq_state *state = (union input_seq_state *)&seq->private;
1111 	int error;
1112 
1113 	/* We need to fit into seq->private pointer */
1114 	BUILD_BUG_ON(sizeof(union input_seq_state) != sizeof(seq->private));
1115 
1116 	error = mutex_lock_interruptible(&input_mutex);
1117 	if (error) {
1118 		state->mutex_acquired = false;
1119 		return ERR_PTR(error);
1120 	}
1121 
1122 	state->mutex_acquired = true;
1123 
1124 	return seq_list_start(&input_dev_list, *pos);
1125 }
1126 
input_devices_seq_next(struct seq_file * seq,void * v,loff_t * pos)1127 static void *input_devices_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1128 {
1129 	return seq_list_next(v, &input_dev_list, pos);
1130 }
1131 
input_seq_stop(struct seq_file * seq,void * v)1132 static void input_seq_stop(struct seq_file *seq, void *v)
1133 {
1134 	union input_seq_state *state = (union input_seq_state *)&seq->private;
1135 
1136 	if (state->mutex_acquired)
1137 		mutex_unlock(&input_mutex);
1138 }
1139 
input_seq_print_bitmap(struct seq_file * seq,const char * name,unsigned long * bitmap,int max)1140 static void input_seq_print_bitmap(struct seq_file *seq, const char *name,
1141 				   unsigned long *bitmap, int max)
1142 {
1143 	int i;
1144 	bool skip_empty = true;
1145 	char buf[18];
1146 
1147 	seq_printf(seq, "B: %s=", name);
1148 
1149 	for (i = BITS_TO_LONGS(max) - 1; i >= 0; i--) {
1150 		if (input_bits_to_string(buf, sizeof(buf),
1151 					 bitmap[i], skip_empty)) {
1152 			skip_empty = false;
1153 			seq_printf(seq, "%s%s", buf, i > 0 ? " " : "");
1154 		}
1155 	}
1156 
1157 	/*
1158 	 * If no output was produced print a single 0.
1159 	 */
1160 	if (skip_empty)
1161 		seq_putc(seq, '0');
1162 
1163 	seq_putc(seq, '\n');
1164 }
1165 
input_devices_seq_show(struct seq_file * seq,void * v)1166 static int input_devices_seq_show(struct seq_file *seq, void *v)
1167 {
1168 	struct input_dev *dev = container_of(v, struct input_dev, node);
1169 	const char *path = kobject_get_path(&dev->dev.kobj, GFP_KERNEL);
1170 	struct input_handle *handle;
1171 
1172 	seq_printf(seq, "I: Bus=%04x Vendor=%04x Product=%04x Version=%04x\n",
1173 		   dev->id.bustype, dev->id.vendor, dev->id.product, dev->id.version);
1174 
1175 	seq_printf(seq, "N: Name=\"%s\"\n", dev->name ? dev->name : "");
1176 	seq_printf(seq, "P: Phys=%s\n", dev->phys ? dev->phys : "");
1177 	seq_printf(seq, "S: Sysfs=%s\n", path ? path : "");
1178 	seq_printf(seq, "U: Uniq=%s\n", dev->uniq ? dev->uniq : "");
1179 	seq_puts(seq, "H: Handlers=");
1180 
1181 	list_for_each_entry(handle, &dev->h_list, d_node)
1182 		seq_printf(seq, "%s ", handle->name);
1183 	seq_putc(seq, '\n');
1184 
1185 	input_seq_print_bitmap(seq, "PROP", dev->propbit, INPUT_PROP_MAX);
1186 
1187 	input_seq_print_bitmap(seq, "EV", dev->evbit, EV_MAX);
1188 	if (test_bit(EV_KEY, dev->evbit))
1189 		input_seq_print_bitmap(seq, "KEY", dev->keybit, KEY_MAX);
1190 	if (test_bit(EV_REL, dev->evbit))
1191 		input_seq_print_bitmap(seq, "REL", dev->relbit, REL_MAX);
1192 	if (test_bit(EV_ABS, dev->evbit))
1193 		input_seq_print_bitmap(seq, "ABS", dev->absbit, ABS_MAX);
1194 	if (test_bit(EV_MSC, dev->evbit))
1195 		input_seq_print_bitmap(seq, "MSC", dev->mscbit, MSC_MAX);
1196 	if (test_bit(EV_LED, dev->evbit))
1197 		input_seq_print_bitmap(seq, "LED", dev->ledbit, LED_MAX);
1198 	if (test_bit(EV_SND, dev->evbit))
1199 		input_seq_print_bitmap(seq, "SND", dev->sndbit, SND_MAX);
1200 	if (test_bit(EV_FF, dev->evbit))
1201 		input_seq_print_bitmap(seq, "FF", dev->ffbit, FF_MAX);
1202 	if (test_bit(EV_SW, dev->evbit))
1203 		input_seq_print_bitmap(seq, "SW", dev->swbit, SW_MAX);
1204 
1205 	seq_putc(seq, '\n');
1206 
1207 	kfree(path);
1208 	return 0;
1209 }
1210 
1211 static const struct seq_operations input_devices_seq_ops = {
1212 	.start	= input_devices_seq_start,
1213 	.next	= input_devices_seq_next,
1214 	.stop	= input_seq_stop,
1215 	.show	= input_devices_seq_show,
1216 };
1217 
input_proc_devices_open(struct inode * inode,struct file * file)1218 static int input_proc_devices_open(struct inode *inode, struct file *file)
1219 {
1220 	return seq_open(file, &input_devices_seq_ops);
1221 }
1222 
1223 static const struct proc_ops input_devices_proc_ops = {
1224 	.proc_open	= input_proc_devices_open,
1225 	.proc_poll	= input_proc_devices_poll,
1226 	.proc_read	= seq_read,
1227 	.proc_lseek	= seq_lseek,
1228 	.proc_release	= seq_release,
1229 };
1230 
input_handlers_seq_start(struct seq_file * seq,loff_t * pos)1231 static void *input_handlers_seq_start(struct seq_file *seq, loff_t *pos)
1232 {
1233 	union input_seq_state *state = (union input_seq_state *)&seq->private;
1234 	int error;
1235 
1236 	/* We need to fit into seq->private pointer */
1237 	BUILD_BUG_ON(sizeof(union input_seq_state) != sizeof(seq->private));
1238 
1239 	error = mutex_lock_interruptible(&input_mutex);
1240 	if (error) {
1241 		state->mutex_acquired = false;
1242 		return ERR_PTR(error);
1243 	}
1244 
1245 	state->mutex_acquired = true;
1246 	state->pos = *pos;
1247 
1248 	return seq_list_start(&input_handler_list, *pos);
1249 }
1250 
input_handlers_seq_next(struct seq_file * seq,void * v,loff_t * pos)1251 static void *input_handlers_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1252 {
1253 	union input_seq_state *state = (union input_seq_state *)&seq->private;
1254 
1255 	state->pos = *pos + 1;
1256 	return seq_list_next(v, &input_handler_list, pos);
1257 }
1258 
input_handlers_seq_show(struct seq_file * seq,void * v)1259 static int input_handlers_seq_show(struct seq_file *seq, void *v)
1260 {
1261 	struct input_handler *handler = container_of(v, struct input_handler, node);
1262 	union input_seq_state *state = (union input_seq_state *)&seq->private;
1263 
1264 	seq_printf(seq, "N: Number=%u Name=%s", state->pos, handler->name);
1265 	if (handler->filter)
1266 		seq_puts(seq, " (filter)");
1267 	if (handler->legacy_minors)
1268 		seq_printf(seq, " Minor=%d", handler->minor);
1269 	seq_putc(seq, '\n');
1270 
1271 	return 0;
1272 }
1273 
1274 static const struct seq_operations input_handlers_seq_ops = {
1275 	.start	= input_handlers_seq_start,
1276 	.next	= input_handlers_seq_next,
1277 	.stop	= input_seq_stop,
1278 	.show	= input_handlers_seq_show,
1279 };
1280 
input_proc_handlers_open(struct inode * inode,struct file * file)1281 static int input_proc_handlers_open(struct inode *inode, struct file *file)
1282 {
1283 	return seq_open(file, &input_handlers_seq_ops);
1284 }
1285 
1286 static const struct proc_ops input_handlers_proc_ops = {
1287 	.proc_open	= input_proc_handlers_open,
1288 	.proc_read	= seq_read,
1289 	.proc_lseek	= seq_lseek,
1290 	.proc_release	= seq_release,
1291 };
1292 
input_proc_init(void)1293 static int __init input_proc_init(void)
1294 {
1295 	struct proc_dir_entry *entry;
1296 
1297 	proc_bus_input_dir = proc_mkdir("bus/input", NULL);
1298 	if (!proc_bus_input_dir)
1299 		return -ENOMEM;
1300 
1301 	entry = proc_create("devices", 0, proc_bus_input_dir,
1302 			    &input_devices_proc_ops);
1303 	if (!entry)
1304 		goto fail1;
1305 
1306 	entry = proc_create("handlers", 0, proc_bus_input_dir,
1307 			    &input_handlers_proc_ops);
1308 	if (!entry)
1309 		goto fail2;
1310 
1311 	return 0;
1312 
1313  fail2:	remove_proc_entry("devices", proc_bus_input_dir);
1314  fail1: remove_proc_entry("bus/input", NULL);
1315 	return -ENOMEM;
1316 }
1317 
input_proc_exit(void)1318 static void input_proc_exit(void)
1319 {
1320 	remove_proc_entry("devices", proc_bus_input_dir);
1321 	remove_proc_entry("handlers", proc_bus_input_dir);
1322 	remove_proc_entry("bus/input", NULL);
1323 }
1324 
1325 #else /* !CONFIG_PROC_FS */
input_wakeup_procfs_readers(void)1326 static inline void input_wakeup_procfs_readers(void) { }
input_proc_init(void)1327 static inline int input_proc_init(void) { return 0; }
input_proc_exit(void)1328 static inline void input_proc_exit(void) { }
1329 #endif
1330 
1331 #define INPUT_DEV_STRING_ATTR_SHOW(name)				\
1332 static ssize_t input_dev_show_##name(struct device *dev,		\
1333 				     struct device_attribute *attr,	\
1334 				     char *buf)				\
1335 {									\
1336 	struct input_dev *input_dev = to_input_dev(dev);		\
1337 									\
1338 	return scnprintf(buf, PAGE_SIZE, "%s\n",			\
1339 			 input_dev->name ? input_dev->name : "");	\
1340 }									\
1341 static DEVICE_ATTR(name, S_IRUGO, input_dev_show_##name, NULL)
1342 
1343 INPUT_DEV_STRING_ATTR_SHOW(name);
1344 INPUT_DEV_STRING_ATTR_SHOW(phys);
1345 INPUT_DEV_STRING_ATTR_SHOW(uniq);
1346 
input_print_modalias_bits(char * buf,int size,char name,unsigned long * bm,unsigned int min_bit,unsigned int max_bit)1347 static int input_print_modalias_bits(char *buf, int size,
1348 				     char name, unsigned long *bm,
1349 				     unsigned int min_bit, unsigned int max_bit)
1350 {
1351 	int len = 0, i;
1352 
1353 	len += snprintf(buf, max(size, 0), "%c", name);
1354 	for (i = min_bit; i < max_bit; i++)
1355 		if (bm[BIT_WORD(i)] & BIT_MASK(i))
1356 			len += snprintf(buf + len, max(size - len, 0), "%X,", i);
1357 	return len;
1358 }
1359 
input_print_modalias(char * buf,int size,struct input_dev * id,int add_cr)1360 static int input_print_modalias(char *buf, int size, struct input_dev *id,
1361 				int add_cr)
1362 {
1363 	int len;
1364 
1365 	len = snprintf(buf, max(size, 0),
1366 		       "input:b%04Xv%04Xp%04Xe%04X-",
1367 		       id->id.bustype, id->id.vendor,
1368 		       id->id.product, id->id.version);
1369 
1370 	len += input_print_modalias_bits(buf + len, size - len,
1371 				'e', id->evbit, 0, EV_MAX);
1372 	len += input_print_modalias_bits(buf + len, size - len,
1373 				'k', id->keybit, KEY_MIN_INTERESTING, KEY_MAX);
1374 	len += input_print_modalias_bits(buf + len, size - len,
1375 				'r', id->relbit, 0, REL_MAX);
1376 	len += input_print_modalias_bits(buf + len, size - len,
1377 				'a', id->absbit, 0, ABS_MAX);
1378 	len += input_print_modalias_bits(buf + len, size - len,
1379 				'm', id->mscbit, 0, MSC_MAX);
1380 	len += input_print_modalias_bits(buf + len, size - len,
1381 				'l', id->ledbit, 0, LED_MAX);
1382 	len += input_print_modalias_bits(buf + len, size - len,
1383 				's', id->sndbit, 0, SND_MAX);
1384 	len += input_print_modalias_bits(buf + len, size - len,
1385 				'f', id->ffbit, 0, FF_MAX);
1386 	len += input_print_modalias_bits(buf + len, size - len,
1387 				'w', id->swbit, 0, SW_MAX);
1388 
1389 	if (add_cr)
1390 		len += snprintf(buf + len, max(size - len, 0), "\n");
1391 
1392 	return len;
1393 }
1394 
input_dev_show_modalias(struct device * dev,struct device_attribute * attr,char * buf)1395 static ssize_t input_dev_show_modalias(struct device *dev,
1396 				       struct device_attribute *attr,
1397 				       char *buf)
1398 {
1399 	struct input_dev *id = to_input_dev(dev);
1400 	ssize_t len;
1401 
1402 	len = input_print_modalias(buf, PAGE_SIZE, id, 1);
1403 
1404 	return min_t(int, len, PAGE_SIZE);
1405 }
1406 static DEVICE_ATTR(modalias, S_IRUGO, input_dev_show_modalias, NULL);
1407 
1408 static int input_print_bitmap(char *buf, int buf_size, unsigned long *bitmap,
1409 			      int max, int add_cr);
1410 
input_dev_show_properties(struct device * dev,struct device_attribute * attr,char * buf)1411 static ssize_t input_dev_show_properties(struct device *dev,
1412 					 struct device_attribute *attr,
1413 					 char *buf)
1414 {
1415 	struct input_dev *input_dev = to_input_dev(dev);
1416 	int len = input_print_bitmap(buf, PAGE_SIZE, input_dev->propbit,
1417 				     INPUT_PROP_MAX, true);
1418 	return min_t(int, len, PAGE_SIZE);
1419 }
1420 static DEVICE_ATTR(properties, S_IRUGO, input_dev_show_properties, NULL);
1421 
1422 static struct attribute *input_dev_attrs[] = {
1423 	&dev_attr_name.attr,
1424 	&dev_attr_phys.attr,
1425 	&dev_attr_uniq.attr,
1426 	&dev_attr_modalias.attr,
1427 	&dev_attr_properties.attr,
1428 	NULL
1429 };
1430 
1431 static const struct attribute_group input_dev_attr_group = {
1432 	.attrs	= input_dev_attrs,
1433 };
1434 
1435 #define INPUT_DEV_ID_ATTR(name)						\
1436 static ssize_t input_dev_show_id_##name(struct device *dev,		\
1437 					struct device_attribute *attr,	\
1438 					char *buf)			\
1439 {									\
1440 	struct input_dev *input_dev = to_input_dev(dev);		\
1441 	return scnprintf(buf, PAGE_SIZE, "%04x\n", input_dev->id.name);	\
1442 }									\
1443 static DEVICE_ATTR(name, S_IRUGO, input_dev_show_id_##name, NULL)
1444 
1445 INPUT_DEV_ID_ATTR(bustype);
1446 INPUT_DEV_ID_ATTR(vendor);
1447 INPUT_DEV_ID_ATTR(product);
1448 INPUT_DEV_ID_ATTR(version);
1449 
1450 static struct attribute *input_dev_id_attrs[] = {
1451 	&dev_attr_bustype.attr,
1452 	&dev_attr_vendor.attr,
1453 	&dev_attr_product.attr,
1454 	&dev_attr_version.attr,
1455 	NULL
1456 };
1457 
1458 static const struct attribute_group input_dev_id_attr_group = {
1459 	.name	= "id",
1460 	.attrs	= input_dev_id_attrs,
1461 };
1462 
input_print_bitmap(char * buf,int buf_size,unsigned long * bitmap,int max,int add_cr)1463 static int input_print_bitmap(char *buf, int buf_size, unsigned long *bitmap,
1464 			      int max, int add_cr)
1465 {
1466 	int i;
1467 	int len = 0;
1468 	bool skip_empty = true;
1469 
1470 	for (i = BITS_TO_LONGS(max) - 1; i >= 0; i--) {
1471 		len += input_bits_to_string(buf + len, max(buf_size - len, 0),
1472 					    bitmap[i], skip_empty);
1473 		if (len) {
1474 			skip_empty = false;
1475 			if (i > 0)
1476 				len += snprintf(buf + len, max(buf_size - len, 0), " ");
1477 		}
1478 	}
1479 
1480 	/*
1481 	 * If no output was produced print a single 0.
1482 	 */
1483 	if (len == 0)
1484 		len = snprintf(buf, buf_size, "%d", 0);
1485 
1486 	if (add_cr)
1487 		len += snprintf(buf + len, max(buf_size - len, 0), "\n");
1488 
1489 	return len;
1490 }
1491 
1492 #define INPUT_DEV_CAP_ATTR(ev, bm)					\
1493 static ssize_t input_dev_show_cap_##bm(struct device *dev,		\
1494 				       struct device_attribute *attr,	\
1495 				       char *buf)			\
1496 {									\
1497 	struct input_dev *input_dev = to_input_dev(dev);		\
1498 	int len = input_print_bitmap(buf, PAGE_SIZE,			\
1499 				     input_dev->bm##bit, ev##_MAX,	\
1500 				     true);				\
1501 	return min_t(int, len, PAGE_SIZE);				\
1502 }									\
1503 static DEVICE_ATTR(bm, S_IRUGO, input_dev_show_cap_##bm, NULL)
1504 
1505 INPUT_DEV_CAP_ATTR(EV, ev);
1506 INPUT_DEV_CAP_ATTR(KEY, key);
1507 INPUT_DEV_CAP_ATTR(REL, rel);
1508 INPUT_DEV_CAP_ATTR(ABS, abs);
1509 INPUT_DEV_CAP_ATTR(MSC, msc);
1510 INPUT_DEV_CAP_ATTR(LED, led);
1511 INPUT_DEV_CAP_ATTR(SND, snd);
1512 INPUT_DEV_CAP_ATTR(FF, ff);
1513 INPUT_DEV_CAP_ATTR(SW, sw);
1514 
1515 static struct attribute *input_dev_caps_attrs[] = {
1516 	&dev_attr_ev.attr,
1517 	&dev_attr_key.attr,
1518 	&dev_attr_rel.attr,
1519 	&dev_attr_abs.attr,
1520 	&dev_attr_msc.attr,
1521 	&dev_attr_led.attr,
1522 	&dev_attr_snd.attr,
1523 	&dev_attr_ff.attr,
1524 	&dev_attr_sw.attr,
1525 	NULL
1526 };
1527 
1528 static const struct attribute_group input_dev_caps_attr_group = {
1529 	.name	= "capabilities",
1530 	.attrs	= input_dev_caps_attrs,
1531 };
1532 
1533 static const struct attribute_group *input_dev_attr_groups[] = {
1534 	&input_dev_attr_group,
1535 	&input_dev_id_attr_group,
1536 	&input_dev_caps_attr_group,
1537 	&input_poller_attribute_group,
1538 	NULL
1539 };
1540 
input_dev_release(struct device * device)1541 static void input_dev_release(struct device *device)
1542 {
1543 	struct input_dev *dev = to_input_dev(device);
1544 
1545 	input_ff_destroy(dev);
1546 	input_mt_destroy_slots(dev);
1547 	kfree(dev->poller);
1548 	kfree(dev->absinfo);
1549 	kfree(dev->vals);
1550 	kfree(dev);
1551 
1552 	module_put(THIS_MODULE);
1553 }
1554 
1555 /*
1556  * Input uevent interface - loading event handlers based on
1557  * device bitfields.
1558  */
input_add_uevent_bm_var(struct kobj_uevent_env * env,const char * name,unsigned long * bitmap,int max)1559 static int input_add_uevent_bm_var(struct kobj_uevent_env *env,
1560 				   const char *name, unsigned long *bitmap, int max)
1561 {
1562 	int len;
1563 
1564 	if (add_uevent_var(env, "%s", name))
1565 		return -ENOMEM;
1566 
1567 	len = input_print_bitmap(&env->buf[env->buflen - 1],
1568 				 sizeof(env->buf) - env->buflen,
1569 				 bitmap, max, false);
1570 	if (len >= (sizeof(env->buf) - env->buflen))
1571 		return -ENOMEM;
1572 
1573 	env->buflen += len;
1574 	return 0;
1575 }
1576 
input_add_uevent_modalias_var(struct kobj_uevent_env * env,struct input_dev * dev)1577 static int input_add_uevent_modalias_var(struct kobj_uevent_env *env,
1578 					 struct input_dev *dev)
1579 {
1580 	int len;
1581 
1582 	if (add_uevent_var(env, "MODALIAS="))
1583 		return -ENOMEM;
1584 
1585 	len = input_print_modalias(&env->buf[env->buflen - 1],
1586 				   sizeof(env->buf) - env->buflen,
1587 				   dev, 0);
1588 	if (len >= (sizeof(env->buf) - env->buflen))
1589 		return -ENOMEM;
1590 
1591 	env->buflen += len;
1592 	return 0;
1593 }
1594 
1595 #define INPUT_ADD_HOTPLUG_VAR(fmt, val...)				\
1596 	do {								\
1597 		int err = add_uevent_var(env, fmt, val);		\
1598 		if (err)						\
1599 			return err;					\
1600 	} while (0)
1601 
1602 #define INPUT_ADD_HOTPLUG_BM_VAR(name, bm, max)				\
1603 	do {								\
1604 		int err = input_add_uevent_bm_var(env, name, bm, max);	\
1605 		if (err)						\
1606 			return err;					\
1607 	} while (0)
1608 
1609 #define INPUT_ADD_HOTPLUG_MODALIAS_VAR(dev)				\
1610 	do {								\
1611 		int err = input_add_uevent_modalias_var(env, dev);	\
1612 		if (err)						\
1613 			return err;					\
1614 	} while (0)
1615 
input_dev_uevent(struct device * device,struct kobj_uevent_env * env)1616 static int input_dev_uevent(struct device *device, struct kobj_uevent_env *env)
1617 {
1618 	struct input_dev *dev = to_input_dev(device);
1619 
1620 	INPUT_ADD_HOTPLUG_VAR("PRODUCT=%x/%x/%x/%x",
1621 				dev->id.bustype, dev->id.vendor,
1622 				dev->id.product, dev->id.version);
1623 	if (dev->name)
1624 		INPUT_ADD_HOTPLUG_VAR("NAME=\"%s\"", dev->name);
1625 	if (dev->phys)
1626 		INPUT_ADD_HOTPLUG_VAR("PHYS=\"%s\"", dev->phys);
1627 	if (dev->uniq)
1628 		INPUT_ADD_HOTPLUG_VAR("UNIQ=\"%s\"", dev->uniq);
1629 
1630 	INPUT_ADD_HOTPLUG_BM_VAR("PROP=", dev->propbit, INPUT_PROP_MAX);
1631 
1632 	INPUT_ADD_HOTPLUG_BM_VAR("EV=", dev->evbit, EV_MAX);
1633 	if (test_bit(EV_KEY, dev->evbit))
1634 		INPUT_ADD_HOTPLUG_BM_VAR("KEY=", dev->keybit, KEY_MAX);
1635 	if (test_bit(EV_REL, dev->evbit))
1636 		INPUT_ADD_HOTPLUG_BM_VAR("REL=", dev->relbit, REL_MAX);
1637 	if (test_bit(EV_ABS, dev->evbit))
1638 		INPUT_ADD_HOTPLUG_BM_VAR("ABS=", dev->absbit, ABS_MAX);
1639 	if (test_bit(EV_MSC, dev->evbit))
1640 		INPUT_ADD_HOTPLUG_BM_VAR("MSC=", dev->mscbit, MSC_MAX);
1641 	if (test_bit(EV_LED, dev->evbit))
1642 		INPUT_ADD_HOTPLUG_BM_VAR("LED=", dev->ledbit, LED_MAX);
1643 	if (test_bit(EV_SND, dev->evbit))
1644 		INPUT_ADD_HOTPLUG_BM_VAR("SND=", dev->sndbit, SND_MAX);
1645 	if (test_bit(EV_FF, dev->evbit))
1646 		INPUT_ADD_HOTPLUG_BM_VAR("FF=", dev->ffbit, FF_MAX);
1647 	if (test_bit(EV_SW, dev->evbit))
1648 		INPUT_ADD_HOTPLUG_BM_VAR("SW=", dev->swbit, SW_MAX);
1649 
1650 	INPUT_ADD_HOTPLUG_MODALIAS_VAR(dev);
1651 
1652 	return 0;
1653 }
1654 
1655 #define INPUT_DO_TOGGLE(dev, type, bits, on)				\
1656 	do {								\
1657 		int i;							\
1658 		bool active;						\
1659 									\
1660 		if (!test_bit(EV_##type, dev->evbit))			\
1661 			break;						\
1662 									\
1663 		for_each_set_bit(i, dev->bits##bit, type##_CNT) {	\
1664 			active = test_bit(i, dev->bits);		\
1665 			if (!active && !on)				\
1666 				continue;				\
1667 									\
1668 			dev->event(dev, EV_##type, i, on ? active : 0);	\
1669 		}							\
1670 	} while (0)
1671 
input_dev_toggle(struct input_dev * dev,bool activate)1672 static void input_dev_toggle(struct input_dev *dev, bool activate)
1673 {
1674 	if (!dev->event)
1675 		return;
1676 
1677 	INPUT_DO_TOGGLE(dev, LED, led, activate);
1678 	INPUT_DO_TOGGLE(dev, SND, snd, activate);
1679 
1680 	if (activate && test_bit(EV_REP, dev->evbit)) {
1681 		dev->event(dev, EV_REP, REP_PERIOD, dev->rep[REP_PERIOD]);
1682 		dev->event(dev, EV_REP, REP_DELAY, dev->rep[REP_DELAY]);
1683 	}
1684 }
1685 
1686 /**
1687  * input_reset_device() - reset/restore the state of input device
1688  * @dev: input device whose state needs to be reset
1689  *
1690  * This function tries to reset the state of an opened input device and
1691  * bring internal state and state if the hardware in sync with each other.
1692  * We mark all keys as released, restore LED state, repeat rate, etc.
1693  */
input_reset_device(struct input_dev * dev)1694 void input_reset_device(struct input_dev *dev)
1695 {
1696 	unsigned long flags;
1697 
1698 	mutex_lock(&dev->mutex);
1699 	spin_lock_irqsave(&dev->event_lock, flags);
1700 
1701 	input_dev_toggle(dev, true);
1702 	input_dev_release_keys(dev);
1703 
1704 	spin_unlock_irqrestore(&dev->event_lock, flags);
1705 	mutex_unlock(&dev->mutex);
1706 }
1707 EXPORT_SYMBOL(input_reset_device);
1708 
1709 #ifdef CONFIG_PM_SLEEP
input_dev_suspend(struct device * dev)1710 static int input_dev_suspend(struct device *dev)
1711 {
1712 	struct input_dev *input_dev = to_input_dev(dev);
1713 
1714 	spin_lock_irq(&input_dev->event_lock);
1715 
1716 	/*
1717 	 * Keys that are pressed now are unlikely to be
1718 	 * still pressed when we resume.
1719 	 */
1720 	input_dev_release_keys(input_dev);
1721 
1722 	/* Turn off LEDs and sounds, if any are active. */
1723 	input_dev_toggle(input_dev, false);
1724 
1725 	spin_unlock_irq(&input_dev->event_lock);
1726 
1727 	return 0;
1728 }
1729 
input_dev_resume(struct device * dev)1730 static int input_dev_resume(struct device *dev)
1731 {
1732 	struct input_dev *input_dev = to_input_dev(dev);
1733 
1734 	spin_lock_irq(&input_dev->event_lock);
1735 
1736 	/* Restore state of LEDs and sounds, if any were active. */
1737 	input_dev_toggle(input_dev, true);
1738 
1739 	spin_unlock_irq(&input_dev->event_lock);
1740 
1741 	return 0;
1742 }
1743 
input_dev_freeze(struct device * dev)1744 static int input_dev_freeze(struct device *dev)
1745 {
1746 	struct input_dev *input_dev = to_input_dev(dev);
1747 
1748 	spin_lock_irq(&input_dev->event_lock);
1749 
1750 	/*
1751 	 * Keys that are pressed now are unlikely to be
1752 	 * still pressed when we resume.
1753 	 */
1754 	input_dev_release_keys(input_dev);
1755 
1756 	spin_unlock_irq(&input_dev->event_lock);
1757 
1758 	return 0;
1759 }
1760 
input_dev_poweroff(struct device * dev)1761 static int input_dev_poweroff(struct device *dev)
1762 {
1763 	struct input_dev *input_dev = to_input_dev(dev);
1764 
1765 	spin_lock_irq(&input_dev->event_lock);
1766 
1767 	/* Turn off LEDs and sounds, if any are active. */
1768 	input_dev_toggle(input_dev, false);
1769 
1770 	spin_unlock_irq(&input_dev->event_lock);
1771 
1772 	return 0;
1773 }
1774 
1775 static const struct dev_pm_ops input_dev_pm_ops = {
1776 	.suspend	= input_dev_suspend,
1777 	.resume		= input_dev_resume,
1778 	.freeze		= input_dev_freeze,
1779 	.poweroff	= input_dev_poweroff,
1780 	.restore	= input_dev_resume,
1781 };
1782 #endif /* CONFIG_PM */
1783 
1784 static const struct device_type input_dev_type = {
1785 	.groups		= input_dev_attr_groups,
1786 	.release	= input_dev_release,
1787 	.uevent		= input_dev_uevent,
1788 #ifdef CONFIG_PM_SLEEP
1789 	.pm		= &input_dev_pm_ops,
1790 #endif
1791 };
1792 
input_devnode(struct device * dev,umode_t * mode)1793 static char *input_devnode(struct device *dev, umode_t *mode)
1794 {
1795 	return kasprintf(GFP_KERNEL, "input/%s", dev_name(dev));
1796 }
1797 
1798 struct class input_class = {
1799 	.name		= "input",
1800 	.devnode	= input_devnode,
1801 };
1802 EXPORT_SYMBOL_GPL(input_class);
1803 
1804 /**
1805  * input_allocate_device - allocate memory for new input device
1806  *
1807  * Returns prepared struct input_dev or %NULL.
1808  *
1809  * NOTE: Use input_free_device() to free devices that have not been
1810  * registered; input_unregister_device() should be used for already
1811  * registered devices.
1812  */
input_allocate_device(void)1813 struct input_dev *input_allocate_device(void)
1814 {
1815 	static atomic_t input_no = ATOMIC_INIT(-1);
1816 	struct input_dev *dev;
1817 
1818 	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
1819 	if (dev) {
1820 		dev->dev.type = &input_dev_type;
1821 		dev->dev.class = &input_class;
1822 		device_initialize(&dev->dev);
1823 		mutex_init(&dev->mutex);
1824 		spin_lock_init(&dev->event_lock);
1825 		timer_setup(&dev->timer, NULL, 0);
1826 		INIT_LIST_HEAD(&dev->h_list);
1827 		INIT_LIST_HEAD(&dev->node);
1828 
1829 		dev_set_name(&dev->dev, "input%lu",
1830 			     (unsigned long)atomic_inc_return(&input_no));
1831 
1832 		__module_get(THIS_MODULE);
1833 	}
1834 
1835 	return dev;
1836 }
1837 EXPORT_SYMBOL(input_allocate_device);
1838 
1839 struct input_devres {
1840 	struct input_dev *input;
1841 };
1842 
devm_input_device_match(struct device * dev,void * res,void * data)1843 static int devm_input_device_match(struct device *dev, void *res, void *data)
1844 {
1845 	struct input_devres *devres = res;
1846 
1847 	return devres->input == data;
1848 }
1849 
devm_input_device_release(struct device * dev,void * res)1850 static void devm_input_device_release(struct device *dev, void *res)
1851 {
1852 	struct input_devres *devres = res;
1853 	struct input_dev *input = devres->input;
1854 
1855 	dev_dbg(dev, "%s: dropping reference to %s\n",
1856 		__func__, dev_name(&input->dev));
1857 	input_put_device(input);
1858 }
1859 
1860 /**
1861  * devm_input_allocate_device - allocate managed input device
1862  * @dev: device owning the input device being created
1863  *
1864  * Returns prepared struct input_dev or %NULL.
1865  *
1866  * Managed input devices do not need to be explicitly unregistered or
1867  * freed as it will be done automatically when owner device unbinds from
1868  * its driver (or binding fails). Once managed input device is allocated,
1869  * it is ready to be set up and registered in the same fashion as regular
1870  * input device. There are no special devm_input_device_[un]register()
1871  * variants, regular ones work with both managed and unmanaged devices,
1872  * should you need them. In most cases however, managed input device need
1873  * not be explicitly unregistered or freed.
1874  *
1875  * NOTE: the owner device is set up as parent of input device and users
1876  * should not override it.
1877  */
devm_input_allocate_device(struct device * dev)1878 struct input_dev *devm_input_allocate_device(struct device *dev)
1879 {
1880 	struct input_dev *input;
1881 	struct input_devres *devres;
1882 
1883 	devres = devres_alloc(devm_input_device_release,
1884 			      sizeof(*devres), GFP_KERNEL);
1885 	if (!devres)
1886 		return NULL;
1887 
1888 	input = input_allocate_device();
1889 	if (!input) {
1890 		devres_free(devres);
1891 		return NULL;
1892 	}
1893 
1894 	input->dev.parent = dev;
1895 	input->devres_managed = true;
1896 
1897 	devres->input = input;
1898 	devres_add(dev, devres);
1899 
1900 	return input;
1901 }
1902 EXPORT_SYMBOL(devm_input_allocate_device);
1903 
1904 /**
1905  * input_free_device - free memory occupied by input_dev structure
1906  * @dev: input device to free
1907  *
1908  * This function should only be used if input_register_device()
1909  * was not called yet or if it failed. Once device was registered
1910  * use input_unregister_device() and memory will be freed once last
1911  * reference to the device is dropped.
1912  *
1913  * Device should be allocated by input_allocate_device().
1914  *
1915  * NOTE: If there are references to the input device then memory
1916  * will not be freed until last reference is dropped.
1917  */
input_free_device(struct input_dev * dev)1918 void input_free_device(struct input_dev *dev)
1919 {
1920 	if (dev) {
1921 		if (dev->devres_managed)
1922 			WARN_ON(devres_destroy(dev->dev.parent,
1923 						devm_input_device_release,
1924 						devm_input_device_match,
1925 						dev));
1926 		input_put_device(dev);
1927 	}
1928 }
1929 EXPORT_SYMBOL(input_free_device);
1930 
1931 /**
1932  * input_set_timestamp - set timestamp for input events
1933  * @dev: input device to set timestamp for
1934  * @timestamp: the time at which the event has occurred
1935  *   in CLOCK_MONOTONIC
1936  *
1937  * This function is intended to provide to the input system a more
1938  * accurate time of when an event actually occurred. The driver should
1939  * call this function as soon as a timestamp is acquired ensuring
1940  * clock conversions in input_set_timestamp are done correctly.
1941  *
1942  * The system entering suspend state between timestamp acquisition and
1943  * calling input_set_timestamp can result in inaccurate conversions.
1944  */
input_set_timestamp(struct input_dev * dev,ktime_t timestamp)1945 void input_set_timestamp(struct input_dev *dev, ktime_t timestamp)
1946 {
1947 	dev->timestamp[INPUT_CLK_MONO] = timestamp;
1948 	dev->timestamp[INPUT_CLK_REAL] = ktime_mono_to_real(timestamp);
1949 	dev->timestamp[INPUT_CLK_BOOT] = ktime_mono_to_any(timestamp,
1950 							   TK_OFFS_BOOT);
1951 }
1952 EXPORT_SYMBOL(input_set_timestamp);
1953 
1954 /**
1955  * input_get_timestamp - get timestamp for input events
1956  * @dev: input device to get timestamp from
1957  *
1958  * A valid timestamp is a timestamp of non-zero value.
1959  */
input_get_timestamp(struct input_dev * dev)1960 ktime_t *input_get_timestamp(struct input_dev *dev)
1961 {
1962 	const ktime_t invalid_timestamp = ktime_set(0, 0);
1963 
1964 	if (!ktime_compare(dev->timestamp[INPUT_CLK_MONO], invalid_timestamp))
1965 		input_set_timestamp(dev, ktime_get());
1966 
1967 	return dev->timestamp;
1968 }
1969 EXPORT_SYMBOL(input_get_timestamp);
1970 
1971 /**
1972  * input_set_capability - mark device as capable of a certain event
1973  * @dev: device that is capable of emitting or accepting event
1974  * @type: type of the event (EV_KEY, EV_REL, etc...)
1975  * @code: event code
1976  *
1977  * In addition to setting up corresponding bit in appropriate capability
1978  * bitmap the function also adjusts dev->evbit.
1979  */
input_set_capability(struct input_dev * dev,unsigned int type,unsigned int code)1980 void input_set_capability(struct input_dev *dev, unsigned int type, unsigned int code)
1981 {
1982 	switch (type) {
1983 	case EV_KEY:
1984 		__set_bit(code, dev->keybit);
1985 		break;
1986 
1987 	case EV_REL:
1988 		__set_bit(code, dev->relbit);
1989 		break;
1990 
1991 	case EV_ABS:
1992 		input_alloc_absinfo(dev);
1993 		if (!dev->absinfo)
1994 			return;
1995 
1996 		__set_bit(code, dev->absbit);
1997 		break;
1998 
1999 	case EV_MSC:
2000 		__set_bit(code, dev->mscbit);
2001 		break;
2002 
2003 	case EV_SW:
2004 		__set_bit(code, dev->swbit);
2005 		break;
2006 
2007 	case EV_LED:
2008 		__set_bit(code, dev->ledbit);
2009 		break;
2010 
2011 	case EV_SND:
2012 		__set_bit(code, dev->sndbit);
2013 		break;
2014 
2015 	case EV_FF:
2016 		__set_bit(code, dev->ffbit);
2017 		break;
2018 
2019 	case EV_PWR:
2020 		/* do nothing */
2021 		break;
2022 
2023 	default:
2024 		pr_err("%s: unknown type %u (code %u)\n", __func__, type, code);
2025 		dump_stack();
2026 		return;
2027 	}
2028 
2029 	__set_bit(type, dev->evbit);
2030 }
2031 EXPORT_SYMBOL(input_set_capability);
2032 
input_estimate_events_per_packet(struct input_dev * dev)2033 static unsigned int input_estimate_events_per_packet(struct input_dev *dev)
2034 {
2035 	int mt_slots;
2036 	int i;
2037 	unsigned int events;
2038 
2039 	if (dev->mt) {
2040 		mt_slots = dev->mt->num_slots;
2041 	} else if (test_bit(ABS_MT_TRACKING_ID, dev->absbit)) {
2042 		mt_slots = dev->absinfo[ABS_MT_TRACKING_ID].maximum -
2043 			   dev->absinfo[ABS_MT_TRACKING_ID].minimum + 1,
2044 		mt_slots = clamp(mt_slots, 2, 32);
2045 	} else if (test_bit(ABS_MT_POSITION_X, dev->absbit)) {
2046 		mt_slots = 2;
2047 	} else {
2048 		mt_slots = 0;
2049 	}
2050 
2051 	events = mt_slots + 1; /* count SYN_MT_REPORT and SYN_REPORT */
2052 
2053 	if (test_bit(EV_ABS, dev->evbit))
2054 		for_each_set_bit(i, dev->absbit, ABS_CNT)
2055 			events += input_is_mt_axis(i) ? mt_slots : 1;
2056 
2057 	if (test_bit(EV_REL, dev->evbit))
2058 		events += bitmap_weight(dev->relbit, REL_CNT);
2059 
2060 	/* Make room for KEY and MSC events */
2061 	events += 7;
2062 
2063 	return events;
2064 }
2065 
2066 #define INPUT_CLEANSE_BITMASK(dev, type, bits)				\
2067 	do {								\
2068 		if (!test_bit(EV_##type, dev->evbit))			\
2069 			memset(dev->bits##bit, 0,			\
2070 				sizeof(dev->bits##bit));		\
2071 	} while (0)
2072 
input_cleanse_bitmasks(struct input_dev * dev)2073 static void input_cleanse_bitmasks(struct input_dev *dev)
2074 {
2075 	INPUT_CLEANSE_BITMASK(dev, KEY, key);
2076 	INPUT_CLEANSE_BITMASK(dev, REL, rel);
2077 	INPUT_CLEANSE_BITMASK(dev, ABS, abs);
2078 	INPUT_CLEANSE_BITMASK(dev, MSC, msc);
2079 	INPUT_CLEANSE_BITMASK(dev, LED, led);
2080 	INPUT_CLEANSE_BITMASK(dev, SND, snd);
2081 	INPUT_CLEANSE_BITMASK(dev, FF, ff);
2082 	INPUT_CLEANSE_BITMASK(dev, SW, sw);
2083 }
2084 
__input_unregister_device(struct input_dev * dev)2085 static void __input_unregister_device(struct input_dev *dev)
2086 {
2087 	struct input_handle *handle, *next;
2088 
2089 	input_disconnect_device(dev);
2090 
2091 	mutex_lock(&input_mutex);
2092 
2093 	list_for_each_entry_safe(handle, next, &dev->h_list, d_node)
2094 		handle->handler->disconnect(handle);
2095 	WARN_ON(!list_empty(&dev->h_list));
2096 
2097 	del_timer_sync(&dev->timer);
2098 	list_del_init(&dev->node);
2099 
2100 	input_wakeup_procfs_readers();
2101 
2102 	mutex_unlock(&input_mutex);
2103 
2104 	device_del(&dev->dev);
2105 }
2106 
devm_input_device_unregister(struct device * dev,void * res)2107 static void devm_input_device_unregister(struct device *dev, void *res)
2108 {
2109 	struct input_devres *devres = res;
2110 	struct input_dev *input = devres->input;
2111 
2112 	dev_dbg(dev, "%s: unregistering device %s\n",
2113 		__func__, dev_name(&input->dev));
2114 	__input_unregister_device(input);
2115 }
2116 
2117 /**
2118  * input_enable_softrepeat - enable software autorepeat
2119  * @dev: input device
2120  * @delay: repeat delay
2121  * @period: repeat period
2122  *
2123  * Enable software autorepeat on the input device.
2124  */
input_enable_softrepeat(struct input_dev * dev,int delay,int period)2125 void input_enable_softrepeat(struct input_dev *dev, int delay, int period)
2126 {
2127 	dev->timer.function = input_repeat_key;
2128 	dev->rep[REP_DELAY] = delay;
2129 	dev->rep[REP_PERIOD] = period;
2130 }
2131 EXPORT_SYMBOL(input_enable_softrepeat);
2132 
2133 /**
2134  * input_register_device - register device with input core
2135  * @dev: device to be registered
2136  *
2137  * This function registers device with input core. The device must be
2138  * allocated with input_allocate_device() and all it's capabilities
2139  * set up before registering.
2140  * If function fails the device must be freed with input_free_device().
2141  * Once device has been successfully registered it can be unregistered
2142  * with input_unregister_device(); input_free_device() should not be
2143  * called in this case.
2144  *
2145  * Note that this function is also used to register managed input devices
2146  * (ones allocated with devm_input_allocate_device()). Such managed input
2147  * devices need not be explicitly unregistered or freed, their tear down
2148  * is controlled by the devres infrastructure. It is also worth noting
2149  * that tear down of managed input devices is internally a 2-step process:
2150  * registered managed input device is first unregistered, but stays in
2151  * memory and can still handle input_event() calls (although events will
2152  * not be delivered anywhere). The freeing of managed input device will
2153  * happen later, when devres stack is unwound to the point where device
2154  * allocation was made.
2155  */
input_register_device(struct input_dev * dev)2156 int input_register_device(struct input_dev *dev)
2157 {
2158 	struct input_devres *devres = NULL;
2159 	struct input_handler *handler;
2160 	unsigned int packet_size;
2161 	const char *path;
2162 	int error;
2163 
2164 	if (test_bit(EV_ABS, dev->evbit) && !dev->absinfo) {
2165 		dev_err(&dev->dev,
2166 			"Absolute device without dev->absinfo, refusing to register\n");
2167 		return -EINVAL;
2168 	}
2169 
2170 	if (dev->devres_managed) {
2171 		devres = devres_alloc(devm_input_device_unregister,
2172 				      sizeof(*devres), GFP_KERNEL);
2173 		if (!devres)
2174 			return -ENOMEM;
2175 
2176 		devres->input = dev;
2177 	}
2178 
2179 	/* Every input device generates EV_SYN/SYN_REPORT events. */
2180 	__set_bit(EV_SYN, dev->evbit);
2181 
2182 	/* KEY_RESERVED is not supposed to be transmitted to userspace. */
2183 	__clear_bit(KEY_RESERVED, dev->keybit);
2184 
2185 	/* Make sure that bitmasks not mentioned in dev->evbit are clean. */
2186 	input_cleanse_bitmasks(dev);
2187 
2188 	packet_size = input_estimate_events_per_packet(dev);
2189 	if (dev->hint_events_per_packet < packet_size)
2190 		dev->hint_events_per_packet = packet_size;
2191 
2192 	dev->max_vals = dev->hint_events_per_packet + 2;
2193 	dev->vals = kcalloc(dev->max_vals, sizeof(*dev->vals), GFP_KERNEL);
2194 	if (!dev->vals) {
2195 		error = -ENOMEM;
2196 		goto err_devres_free;
2197 	}
2198 
2199 	/*
2200 	 * If delay and period are pre-set by the driver, then autorepeating
2201 	 * is handled by the driver itself and we don't do it in input.c.
2202 	 */
2203 	if (!dev->rep[REP_DELAY] && !dev->rep[REP_PERIOD])
2204 		input_enable_softrepeat(dev, 250, 33);
2205 
2206 	if (!dev->getkeycode)
2207 		dev->getkeycode = input_default_getkeycode;
2208 
2209 	if (!dev->setkeycode)
2210 		dev->setkeycode = input_default_setkeycode;
2211 
2212 	if (dev->poller)
2213 		input_dev_poller_finalize(dev->poller);
2214 
2215 	error = device_add(&dev->dev);
2216 	if (error)
2217 		goto err_free_vals;
2218 
2219 	path = kobject_get_path(&dev->dev.kobj, GFP_KERNEL);
2220 	pr_info("%s as %s\n",
2221 		dev->name ? dev->name : "Unspecified device",
2222 		path ? path : "N/A");
2223 	kfree(path);
2224 
2225 	error = mutex_lock_interruptible(&input_mutex);
2226 	if (error)
2227 		goto err_device_del;
2228 
2229 	list_add_tail(&dev->node, &input_dev_list);
2230 
2231 	list_for_each_entry(handler, &input_handler_list, node)
2232 		input_attach_handler(dev, handler);
2233 
2234 	input_wakeup_procfs_readers();
2235 
2236 	mutex_unlock(&input_mutex);
2237 
2238 	if (dev->devres_managed) {
2239 		dev_dbg(dev->dev.parent, "%s: registering %s with devres.\n",
2240 			__func__, dev_name(&dev->dev));
2241 		devres_add(dev->dev.parent, devres);
2242 	}
2243 	return 0;
2244 
2245 err_device_del:
2246 	device_del(&dev->dev);
2247 err_free_vals:
2248 	kfree(dev->vals);
2249 	dev->vals = NULL;
2250 err_devres_free:
2251 	devres_free(devres);
2252 	return error;
2253 }
2254 EXPORT_SYMBOL(input_register_device);
2255 
2256 /**
2257  * input_unregister_device - unregister previously registered device
2258  * @dev: device to be unregistered
2259  *
2260  * This function unregisters an input device. Once device is unregistered
2261  * the caller should not try to access it as it may get freed at any moment.
2262  */
input_unregister_device(struct input_dev * dev)2263 void input_unregister_device(struct input_dev *dev)
2264 {
2265 	if (dev->devres_managed) {
2266 		WARN_ON(devres_destroy(dev->dev.parent,
2267 					devm_input_device_unregister,
2268 					devm_input_device_match,
2269 					dev));
2270 		__input_unregister_device(dev);
2271 		/*
2272 		 * We do not do input_put_device() here because it will be done
2273 		 * when 2nd devres fires up.
2274 		 */
2275 	} else {
2276 		__input_unregister_device(dev);
2277 		input_put_device(dev);
2278 	}
2279 }
2280 EXPORT_SYMBOL(input_unregister_device);
2281 
2282 /**
2283  * input_register_handler - register a new input handler
2284  * @handler: handler to be registered
2285  *
2286  * This function registers a new input handler (interface) for input
2287  * devices in the system and attaches it to all input devices that
2288  * are compatible with the handler.
2289  */
input_register_handler(struct input_handler * handler)2290 int input_register_handler(struct input_handler *handler)
2291 {
2292 	struct input_dev *dev;
2293 	int error;
2294 
2295 	error = mutex_lock_interruptible(&input_mutex);
2296 	if (error)
2297 		return error;
2298 
2299 	INIT_LIST_HEAD(&handler->h_list);
2300 
2301 	list_add_tail(&handler->node, &input_handler_list);
2302 
2303 	list_for_each_entry(dev, &input_dev_list, node)
2304 		input_attach_handler(dev, handler);
2305 
2306 	input_wakeup_procfs_readers();
2307 
2308 	mutex_unlock(&input_mutex);
2309 	return 0;
2310 }
2311 EXPORT_SYMBOL(input_register_handler);
2312 
2313 /**
2314  * input_unregister_handler - unregisters an input handler
2315  * @handler: handler to be unregistered
2316  *
2317  * This function disconnects a handler from its input devices and
2318  * removes it from lists of known handlers.
2319  */
input_unregister_handler(struct input_handler * handler)2320 void input_unregister_handler(struct input_handler *handler)
2321 {
2322 	struct input_handle *handle, *next;
2323 
2324 	mutex_lock(&input_mutex);
2325 
2326 	list_for_each_entry_safe(handle, next, &handler->h_list, h_node)
2327 		handler->disconnect(handle);
2328 	WARN_ON(!list_empty(&handler->h_list));
2329 
2330 	list_del_init(&handler->node);
2331 
2332 	input_wakeup_procfs_readers();
2333 
2334 	mutex_unlock(&input_mutex);
2335 }
2336 EXPORT_SYMBOL(input_unregister_handler);
2337 
2338 /**
2339  * input_handler_for_each_handle - handle iterator
2340  * @handler: input handler to iterate
2341  * @data: data for the callback
2342  * @fn: function to be called for each handle
2343  *
2344  * Iterate over @bus's list of devices, and call @fn for each, passing
2345  * it @data and stop when @fn returns a non-zero value. The function is
2346  * using RCU to traverse the list and therefore may be using in atomic
2347  * contexts. The @fn callback is invoked from RCU critical section and
2348  * thus must not sleep.
2349  */
input_handler_for_each_handle(struct input_handler * handler,void * data,int (* fn)(struct input_handle *,void *))2350 int input_handler_for_each_handle(struct input_handler *handler, void *data,
2351 				  int (*fn)(struct input_handle *, void *))
2352 {
2353 	struct input_handle *handle;
2354 	int retval = 0;
2355 
2356 	rcu_read_lock();
2357 
2358 	list_for_each_entry_rcu(handle, &handler->h_list, h_node) {
2359 		retval = fn(handle, data);
2360 		if (retval)
2361 			break;
2362 	}
2363 
2364 	rcu_read_unlock();
2365 
2366 	return retval;
2367 }
2368 EXPORT_SYMBOL(input_handler_for_each_handle);
2369 
2370 /**
2371  * input_register_handle - register a new input handle
2372  * @handle: handle to register
2373  *
2374  * This function puts a new input handle onto device's
2375  * and handler's lists so that events can flow through
2376  * it once it is opened using input_open_device().
2377  *
2378  * This function is supposed to be called from handler's
2379  * connect() method.
2380  */
input_register_handle(struct input_handle * handle)2381 int input_register_handle(struct input_handle *handle)
2382 {
2383 	struct input_handler *handler = handle->handler;
2384 	struct input_dev *dev = handle->dev;
2385 	int error;
2386 
2387 	/*
2388 	 * We take dev->mutex here to prevent race with
2389 	 * input_release_device().
2390 	 */
2391 	error = mutex_lock_interruptible(&dev->mutex);
2392 	if (error)
2393 		return error;
2394 
2395 	/*
2396 	 * Filters go to the head of the list, normal handlers
2397 	 * to the tail.
2398 	 */
2399 	if (handler->filter)
2400 		list_add_rcu(&handle->d_node, &dev->h_list);
2401 	else
2402 		list_add_tail_rcu(&handle->d_node, &dev->h_list);
2403 
2404 	mutex_unlock(&dev->mutex);
2405 
2406 	/*
2407 	 * Since we are supposed to be called from ->connect()
2408 	 * which is mutually exclusive with ->disconnect()
2409 	 * we can't be racing with input_unregister_handle()
2410 	 * and so separate lock is not needed here.
2411 	 */
2412 	list_add_tail_rcu(&handle->h_node, &handler->h_list);
2413 
2414 	if (handler->start)
2415 		handler->start(handle);
2416 
2417 	return 0;
2418 }
2419 EXPORT_SYMBOL(input_register_handle);
2420 
2421 /**
2422  * input_unregister_handle - unregister an input handle
2423  * @handle: handle to unregister
2424  *
2425  * This function removes input handle from device's
2426  * and handler's lists.
2427  *
2428  * This function is supposed to be called from handler's
2429  * disconnect() method.
2430  */
input_unregister_handle(struct input_handle * handle)2431 void input_unregister_handle(struct input_handle *handle)
2432 {
2433 	struct input_dev *dev = handle->dev;
2434 
2435 	list_del_rcu(&handle->h_node);
2436 
2437 	/*
2438 	 * Take dev->mutex to prevent race with input_release_device().
2439 	 */
2440 	mutex_lock(&dev->mutex);
2441 	list_del_rcu(&handle->d_node);
2442 	mutex_unlock(&dev->mutex);
2443 
2444 	synchronize_rcu();
2445 }
2446 EXPORT_SYMBOL(input_unregister_handle);
2447 
2448 /**
2449  * input_get_new_minor - allocates a new input minor number
2450  * @legacy_base: beginning or the legacy range to be searched
2451  * @legacy_num: size of legacy range
2452  * @allow_dynamic: whether we can also take ID from the dynamic range
2453  *
2454  * This function allocates a new device minor for from input major namespace.
2455  * Caller can request legacy minor by specifying @legacy_base and @legacy_num
2456  * parameters and whether ID can be allocated from dynamic range if there are
2457  * no free IDs in legacy range.
2458  */
input_get_new_minor(int legacy_base,unsigned int legacy_num,bool allow_dynamic)2459 int input_get_new_minor(int legacy_base, unsigned int legacy_num,
2460 			bool allow_dynamic)
2461 {
2462 	/*
2463 	 * This function should be called from input handler's ->connect()
2464 	 * methods, which are serialized with input_mutex, so no additional
2465 	 * locking is needed here.
2466 	 */
2467 	if (legacy_base >= 0) {
2468 		int minor = ida_simple_get(&input_ida,
2469 					   legacy_base,
2470 					   legacy_base + legacy_num,
2471 					   GFP_KERNEL);
2472 		if (minor >= 0 || !allow_dynamic)
2473 			return minor;
2474 	}
2475 
2476 	return ida_simple_get(&input_ida,
2477 			      INPUT_FIRST_DYNAMIC_DEV, INPUT_MAX_CHAR_DEVICES,
2478 			      GFP_KERNEL);
2479 }
2480 EXPORT_SYMBOL(input_get_new_minor);
2481 
2482 /**
2483  * input_free_minor - release previously allocated minor
2484  * @minor: minor to be released
2485  *
2486  * This function releases previously allocated input minor so that it can be
2487  * reused later.
2488  */
input_free_minor(unsigned int minor)2489 void input_free_minor(unsigned int minor)
2490 {
2491 	ida_simple_remove(&input_ida, minor);
2492 }
2493 EXPORT_SYMBOL(input_free_minor);
2494 
input_init(void)2495 static int __init input_init(void)
2496 {
2497 	int err;
2498 
2499 	err = class_register(&input_class);
2500 	if (err) {
2501 		pr_err("unable to register input_dev class\n");
2502 		return err;
2503 	}
2504 
2505 	err = input_proc_init();
2506 	if (err)
2507 		goto fail1;
2508 
2509 	err = register_chrdev_region(MKDEV(INPUT_MAJOR, 0),
2510 				     INPUT_MAX_CHAR_DEVICES, "input");
2511 	if (err) {
2512 		pr_err("unable to register char major %d", INPUT_MAJOR);
2513 		goto fail2;
2514 	}
2515 
2516 	return 0;
2517 
2518  fail2:	input_proc_exit();
2519  fail1:	class_unregister(&input_class);
2520 	return err;
2521 }
2522 
input_exit(void)2523 static void __exit input_exit(void)
2524 {
2525 	input_proc_exit();
2526 	unregister_chrdev_region(MKDEV(INPUT_MAJOR, 0),
2527 				 INPUT_MAX_CHAR_DEVICES);
2528 	class_unregister(&input_class);
2529 }
2530 
2531 subsys_initcall(input_init);
2532 module_exit(input_exit);
2533