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