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