56b5e8f8fe885f4efbdd3b30bb6323187e21ed2b
[linux-2.6-microblaze.git] / drivers / tty / vt / keyboard.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Written for linux by Johan Myreen as a translation from
4  * the assembly version by Linus (with diacriticals added)
5  *
6  * Some additional features added by Christoph Niemann (ChN), March 1993
7  *
8  * Loadable keymaps by Risto Kankkunen, May 1993
9  *
10  * Diacriticals redone & other small changes, aeb@cwi.nl, June 1993
11  * Added decr/incr_console, dynamic keymaps, Unicode support,
12  * dynamic function/string keys, led setting,  Sept 1994
13  * `Sticky' modifier keys, 951006.
14  *
15  * 11-11-96: SAK should now work in the raw mode (Martin Mares)
16  *
17  * Modified to provide 'generic' keyboard support by Hamish Macdonald
18  * Merge with the m68k keyboard driver and split-off of the PC low-level
19  * parts by Geert Uytterhoeven, May 1997
20  *
21  * 27-05-97: Added support for the Magic SysRq Key (Martin Mares)
22  * 30-07-98: Dead keys redone, aeb@cwi.nl.
23  * 21-08-02: Converted to input API, major cleanup. (Vojtech Pavlik)
24  */
25
26 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
27
28 #include <linux/consolemap.h>
29 #include <linux/init.h>
30 #include <linux/input.h>
31 #include <linux/jiffies.h>
32 #include <linux/kbd_diacr.h>
33 #include <linux/kbd_kern.h>
34 #include <linux/leds.h>
35 #include <linux/mm.h>
36 #include <linux/module.h>
37 #include <linux/nospec.h>
38 #include <linux/notifier.h>
39 #include <linux/reboot.h>
40 #include <linux/sched/debug.h>
41 #include <linux/sched/signal.h>
42 #include <linux/slab.h>
43 #include <linux/spinlock.h>
44 #include <linux/string.h>
45 #include <linux/tty_flip.h>
46 #include <linux/tty.h>
47 #include <linux/uaccess.h>
48 #include <linux/vt_kern.h>
49
50 #include <asm/irq_regs.h>
51
52 /*
53  * Exported functions/variables
54  */
55
56 #define KBD_DEFMODE ((1 << VC_REPEAT) | (1 << VC_META))
57
58 #if defined(CONFIG_X86) || defined(CONFIG_PARISC)
59 #include <asm/kbdleds.h>
60 #else
61 static inline int kbd_defleds(void)
62 {
63         return 0;
64 }
65 #endif
66
67 #define KBD_DEFLOCK 0
68
69 /*
70  * Handler Tables.
71  */
72
73 #define K_HANDLERS\
74         k_self,         k_fn,           k_spec,         k_pad,\
75         k_dead,         k_cons,         k_cur,          k_shift,\
76         k_meta,         k_ascii,        k_lock,         k_lowercase,\
77         k_slock,        k_dead2,        k_brl,          k_ignore
78
79 typedef void (k_handler_fn)(struct vc_data *vc, unsigned char value,
80                             char up_flag);
81 static k_handler_fn K_HANDLERS;
82 static k_handler_fn *k_handler[16] = { K_HANDLERS };
83
84 #define FN_HANDLERS\
85         fn_null,        fn_enter,       fn_show_ptregs, fn_show_mem,\
86         fn_show_state,  fn_send_intr,   fn_lastcons,    fn_caps_toggle,\
87         fn_num,         fn_hold,        fn_scroll_forw, fn_scroll_back,\
88         fn_boot_it,     fn_caps_on,     fn_compose,     fn_SAK,\
89         fn_dec_console, fn_inc_console, fn_spawn_con,   fn_bare_num
90
91 typedef void (fn_handler_fn)(struct vc_data *vc);
92 static fn_handler_fn FN_HANDLERS;
93 static fn_handler_fn *fn_handler[] = { FN_HANDLERS };
94
95 /*
96  * Variables exported for vt_ioctl.c
97  */
98
99 struct vt_spawn_console vt_spawn_con = {
100         .lock = __SPIN_LOCK_UNLOCKED(vt_spawn_con.lock),
101         .pid  = NULL,
102         .sig  = 0,
103 };
104
105
106 /*
107  * Internal Data.
108  */
109
110 static struct kbd_struct kbd_table[MAX_NR_CONSOLES];
111 static struct kbd_struct *kbd = kbd_table;
112
113 /* maximum values each key_handler can handle */
114 static const unsigned char max_vals[] = {
115         [ KT_LATIN      ] = 255,
116         [ KT_FN         ] = ARRAY_SIZE(func_table) - 1,
117         [ KT_SPEC       ] = ARRAY_SIZE(fn_handler) - 1,
118         [ KT_PAD        ] = NR_PAD - 1,
119         [ KT_DEAD       ] = NR_DEAD - 1,
120         [ KT_CONS       ] = 255,
121         [ KT_CUR        ] = 3,
122         [ KT_SHIFT      ] = NR_SHIFT - 1,
123         [ KT_META       ] = 255,
124         [ KT_ASCII      ] = NR_ASCII - 1,
125         [ KT_LOCK       ] = NR_LOCK - 1,
126         [ KT_LETTER     ] = 255,
127         [ KT_SLOCK      ] = NR_LOCK - 1,
128         [ KT_DEAD2      ] = 255,
129         [ KT_BRL        ] = NR_BRL - 1,
130 };
131
132 static const int NR_TYPES = ARRAY_SIZE(max_vals);
133
134 static struct input_handler kbd_handler;
135 static DEFINE_SPINLOCK(kbd_event_lock);
136 static DEFINE_SPINLOCK(led_lock);
137 static DEFINE_SPINLOCK(func_buf_lock); /* guard 'func_buf'  and friends */
138 static DECLARE_BITMAP(key_down, KEY_CNT);       /* keyboard key bitmap */
139 static unsigned char shift_down[NR_SHIFT];              /* shift state counters.. */
140 static bool dead_key_next;
141
142 /* Handles a number being assembled on the number pad */
143 static bool npadch_active;
144 static unsigned int npadch_value;
145
146 static unsigned int diacr;
147 static bool rep;                        /* flag telling character repeat */
148
149 static int shift_state = 0;
150
151 static unsigned int ledstate = -1U;                     /* undefined */
152 static unsigned char ledioctl;
153
154 /*
155  * Notifier list for console keyboard events
156  */
157 static ATOMIC_NOTIFIER_HEAD(keyboard_notifier_list);
158
159 int register_keyboard_notifier(struct notifier_block *nb)
160 {
161         return atomic_notifier_chain_register(&keyboard_notifier_list, nb);
162 }
163 EXPORT_SYMBOL_GPL(register_keyboard_notifier);
164
165 int unregister_keyboard_notifier(struct notifier_block *nb)
166 {
167         return atomic_notifier_chain_unregister(&keyboard_notifier_list, nb);
168 }
169 EXPORT_SYMBOL_GPL(unregister_keyboard_notifier);
170
171 /*
172  * Translation of scancodes to keycodes. We set them on only the first
173  * keyboard in the list that accepts the scancode and keycode.
174  * Explanation for not choosing the first attached keyboard anymore:
175  *  USB keyboards for example have two event devices: one for all "normal"
176  *  keys and one for extra function keys (like "volume up", "make coffee",
177  *  etc.). So this means that scancodes for the extra function keys won't
178  *  be valid for the first event device, but will be for the second.
179  */
180
181 struct getset_keycode_data {
182         struct input_keymap_entry ke;
183         int error;
184 };
185
186 static int getkeycode_helper(struct input_handle *handle, void *data)
187 {
188         struct getset_keycode_data *d = data;
189
190         d->error = input_get_keycode(handle->dev, &d->ke);
191
192         return d->error == 0; /* stop as soon as we successfully get one */
193 }
194
195 static int getkeycode(unsigned int scancode)
196 {
197         struct getset_keycode_data d = {
198                 .ke     = {
199                         .flags          = 0,
200                         .len            = sizeof(scancode),
201                         .keycode        = 0,
202                 },
203                 .error  = -ENODEV,
204         };
205
206         memcpy(d.ke.scancode, &scancode, sizeof(scancode));
207
208         input_handler_for_each_handle(&kbd_handler, &d, getkeycode_helper);
209
210         return d.error ?: d.ke.keycode;
211 }
212
213 static int setkeycode_helper(struct input_handle *handle, void *data)
214 {
215         struct getset_keycode_data *d = data;
216
217         d->error = input_set_keycode(handle->dev, &d->ke);
218
219         return d->error == 0; /* stop as soon as we successfully set one */
220 }
221
222 static int setkeycode(unsigned int scancode, unsigned int keycode)
223 {
224         struct getset_keycode_data d = {
225                 .ke     = {
226                         .flags          = 0,
227                         .len            = sizeof(scancode),
228                         .keycode        = keycode,
229                 },
230                 .error  = -ENODEV,
231         };
232
233         memcpy(d.ke.scancode, &scancode, sizeof(scancode));
234
235         input_handler_for_each_handle(&kbd_handler, &d, setkeycode_helper);
236
237         return d.error;
238 }
239
240 /*
241  * Making beeps and bells. Note that we prefer beeps to bells, but when
242  * shutting the sound off we do both.
243  */
244
245 static int kd_sound_helper(struct input_handle *handle, void *data)
246 {
247         unsigned int *hz = data;
248         struct input_dev *dev = handle->dev;
249
250         if (test_bit(EV_SND, dev->evbit)) {
251                 if (test_bit(SND_TONE, dev->sndbit)) {
252                         input_inject_event(handle, EV_SND, SND_TONE, *hz);
253                         if (*hz)
254                                 return 0;
255                 }
256                 if (test_bit(SND_BELL, dev->sndbit))
257                         input_inject_event(handle, EV_SND, SND_BELL, *hz ? 1 : 0);
258         }
259
260         return 0;
261 }
262
263 static void kd_nosound(struct timer_list *unused)
264 {
265         static unsigned int zero;
266
267         input_handler_for_each_handle(&kbd_handler, &zero, kd_sound_helper);
268 }
269
270 static DEFINE_TIMER(kd_mksound_timer, kd_nosound);
271
272 void kd_mksound(unsigned int hz, unsigned int ticks)
273 {
274         del_timer_sync(&kd_mksound_timer);
275
276         input_handler_for_each_handle(&kbd_handler, &hz, kd_sound_helper);
277
278         if (hz && ticks)
279                 mod_timer(&kd_mksound_timer, jiffies + ticks);
280 }
281 EXPORT_SYMBOL(kd_mksound);
282
283 /*
284  * Setting the keyboard rate.
285  */
286
287 static int kbd_rate_helper(struct input_handle *handle, void *data)
288 {
289         struct input_dev *dev = handle->dev;
290         struct kbd_repeat *rpt = data;
291
292         if (test_bit(EV_REP, dev->evbit)) {
293
294                 if (rpt[0].delay > 0)
295                         input_inject_event(handle,
296                                            EV_REP, REP_DELAY, rpt[0].delay);
297                 if (rpt[0].period > 0)
298                         input_inject_event(handle,
299                                            EV_REP, REP_PERIOD, rpt[0].period);
300
301                 rpt[1].delay = dev->rep[REP_DELAY];
302                 rpt[1].period = dev->rep[REP_PERIOD];
303         }
304
305         return 0;
306 }
307
308 int kbd_rate(struct kbd_repeat *rpt)
309 {
310         struct kbd_repeat data[2] = { *rpt };
311
312         input_handler_for_each_handle(&kbd_handler, data, kbd_rate_helper);
313         *rpt = data[1]; /* Copy currently used settings */
314
315         return 0;
316 }
317
318 /*
319  * Helper Functions.
320  */
321 static void put_queue(struct vc_data *vc, int ch)
322 {
323         tty_insert_flip_char(&vc->port, ch, 0);
324         tty_schedule_flip(&vc->port);
325 }
326
327 static void puts_queue(struct vc_data *vc, const char *cp)
328 {
329         tty_insert_flip_string(&vc->port, cp, strlen(cp));
330         tty_schedule_flip(&vc->port);
331 }
332
333 static void applkey(struct vc_data *vc, int key, char mode)
334 {
335         static char buf[] = { 0x1b, 'O', 0x00, 0x00 };
336
337         buf[1] = (mode ? 'O' : '[');
338         buf[2] = key;
339         puts_queue(vc, buf);
340 }
341
342 /*
343  * Many other routines do put_queue, but I think either
344  * they produce ASCII, or they produce some user-assigned
345  * string, and in both cases we might assume that it is
346  * in utf-8 already.
347  */
348 static void to_utf8(struct vc_data *vc, uint c)
349 {
350         if (c < 0x80)
351                 /*  0******* */
352                 put_queue(vc, c);
353         else if (c < 0x800) {
354                 /* 110***** 10****** */
355                 put_queue(vc, 0xc0 | (c >> 6));
356                 put_queue(vc, 0x80 | (c & 0x3f));
357         } else if (c < 0x10000) {
358                 if (c >= 0xD800 && c < 0xE000)
359                         return;
360                 if (c == 0xFFFF)
361                         return;
362                 /* 1110**** 10****** 10****** */
363                 put_queue(vc, 0xe0 | (c >> 12));
364                 put_queue(vc, 0x80 | ((c >> 6) & 0x3f));
365                 put_queue(vc, 0x80 | (c & 0x3f));
366         } else if (c < 0x110000) {
367                 /* 11110*** 10****** 10****** 10****** */
368                 put_queue(vc, 0xf0 | (c >> 18));
369                 put_queue(vc, 0x80 | ((c >> 12) & 0x3f));
370                 put_queue(vc, 0x80 | ((c >> 6) & 0x3f));
371                 put_queue(vc, 0x80 | (c & 0x3f));
372         }
373 }
374
375 /*
376  * Called after returning from RAW mode or when changing consoles - recompute
377  * shift_down[] and shift_state from key_down[] maybe called when keymap is
378  * undefined, so that shiftkey release is seen. The caller must hold the
379  * kbd_event_lock.
380  */
381
382 static void do_compute_shiftstate(void)
383 {
384         unsigned int k, sym, val;
385
386         shift_state = 0;
387         memset(shift_down, 0, sizeof(shift_down));
388
389         for_each_set_bit(k, key_down, min(NR_KEYS, KEY_CNT)) {
390                 sym = U(key_maps[0][k]);
391                 if (KTYP(sym) != KT_SHIFT && KTYP(sym) != KT_SLOCK)
392                         continue;
393
394                 val = KVAL(sym);
395                 if (val == KVAL(K_CAPSSHIFT))
396                         val = KVAL(K_SHIFT);
397
398                 shift_down[val]++;
399                 shift_state |= BIT(val);
400         }
401 }
402
403 /* We still have to export this method to vt.c */
404 void compute_shiftstate(void)
405 {
406         unsigned long flags;
407         spin_lock_irqsave(&kbd_event_lock, flags);
408         do_compute_shiftstate();
409         spin_unlock_irqrestore(&kbd_event_lock, flags);
410 }
411
412 /*
413  * We have a combining character DIACR here, followed by the character CH.
414  * If the combination occurs in the table, return the corresponding value.
415  * Otherwise, if CH is a space or equals DIACR, return DIACR.
416  * Otherwise, conclude that DIACR was not combining after all,
417  * queue it and return CH.
418  */
419 static unsigned int handle_diacr(struct vc_data *vc, unsigned int ch)
420 {
421         unsigned int d = diacr;
422         unsigned int i;
423
424         diacr = 0;
425
426         if ((d & ~0xff) == BRL_UC_ROW) {
427                 if ((ch & ~0xff) == BRL_UC_ROW)
428                         return d | ch;
429         } else {
430                 for (i = 0; i < accent_table_size; i++)
431                         if (accent_table[i].diacr == d && accent_table[i].base == ch)
432                                 return accent_table[i].result;
433         }
434
435         if (ch == ' ' || ch == (BRL_UC_ROW|0) || ch == d)
436                 return d;
437
438         if (kbd->kbdmode == VC_UNICODE)
439                 to_utf8(vc, d);
440         else {
441                 int c = conv_uni_to_8bit(d);
442                 if (c != -1)
443                         put_queue(vc, c);
444         }
445
446         return ch;
447 }
448
449 /*
450  * Special function handlers
451  */
452 static void fn_enter(struct vc_data *vc)
453 {
454         if (diacr) {
455                 if (kbd->kbdmode == VC_UNICODE)
456                         to_utf8(vc, diacr);
457                 else {
458                         int c = conv_uni_to_8bit(diacr);
459                         if (c != -1)
460                                 put_queue(vc, c);
461                 }
462                 diacr = 0;
463         }
464
465         put_queue(vc, 13);
466         if (vc_kbd_mode(kbd, VC_CRLF))
467                 put_queue(vc, 10);
468 }
469
470 static void fn_caps_toggle(struct vc_data *vc)
471 {
472         if (rep)
473                 return;
474
475         chg_vc_kbd_led(kbd, VC_CAPSLOCK);
476 }
477
478 static void fn_caps_on(struct vc_data *vc)
479 {
480         if (rep)
481                 return;
482
483         set_vc_kbd_led(kbd, VC_CAPSLOCK);
484 }
485
486 static void fn_show_ptregs(struct vc_data *vc)
487 {
488         struct pt_regs *regs = get_irq_regs();
489
490         if (regs)
491                 show_regs(regs);
492 }
493
494 static void fn_hold(struct vc_data *vc)
495 {
496         struct tty_struct *tty = vc->port.tty;
497
498         if (rep || !tty)
499                 return;
500
501         /*
502          * Note: SCROLLOCK will be set (cleared) by stop_tty (start_tty);
503          * these routines are also activated by ^S/^Q.
504          * (And SCROLLOCK can also be set by the ioctl KDSKBLED.)
505          */
506         if (tty->stopped)
507                 start_tty(tty);
508         else
509                 stop_tty(tty);
510 }
511
512 static void fn_num(struct vc_data *vc)
513 {
514         if (vc_kbd_mode(kbd, VC_APPLIC))
515                 applkey(vc, 'P', 1);
516         else
517                 fn_bare_num(vc);
518 }
519
520 /*
521  * Bind this to Shift-NumLock if you work in application keypad mode
522  * but want to be able to change the NumLock flag.
523  * Bind this to NumLock if you prefer that the NumLock key always
524  * changes the NumLock flag.
525  */
526 static void fn_bare_num(struct vc_data *vc)
527 {
528         if (!rep)
529                 chg_vc_kbd_led(kbd, VC_NUMLOCK);
530 }
531
532 static void fn_lastcons(struct vc_data *vc)
533 {
534         /* switch to the last used console, ChN */
535         set_console(last_console);
536 }
537
538 static void fn_dec_console(struct vc_data *vc)
539 {
540         int i, cur = fg_console;
541
542         /* Currently switching?  Queue this next switch relative to that. */
543         if (want_console != -1)
544                 cur = want_console;
545
546         for (i = cur - 1; i != cur; i--) {
547                 if (i == -1)
548                         i = MAX_NR_CONSOLES - 1;
549                 if (vc_cons_allocated(i))
550                         break;
551         }
552         set_console(i);
553 }
554
555 static void fn_inc_console(struct vc_data *vc)
556 {
557         int i, cur = fg_console;
558
559         /* Currently switching?  Queue this next switch relative to that. */
560         if (want_console != -1)
561                 cur = want_console;
562
563         for (i = cur+1; i != cur; i++) {
564                 if (i == MAX_NR_CONSOLES)
565                         i = 0;
566                 if (vc_cons_allocated(i))
567                         break;
568         }
569         set_console(i);
570 }
571
572 static void fn_send_intr(struct vc_data *vc)
573 {
574         tty_insert_flip_char(&vc->port, 0, TTY_BREAK);
575         tty_schedule_flip(&vc->port);
576 }
577
578 static void fn_scroll_forw(struct vc_data *vc)
579 {
580         scrollfront(vc, 0);
581 }
582
583 static void fn_scroll_back(struct vc_data *vc)
584 {
585         scrollback(vc);
586 }
587
588 static void fn_show_mem(struct vc_data *vc)
589 {
590         show_mem(0, NULL);
591 }
592
593 static void fn_show_state(struct vc_data *vc)
594 {
595         show_state();
596 }
597
598 static void fn_boot_it(struct vc_data *vc)
599 {
600         ctrl_alt_del();
601 }
602
603 static void fn_compose(struct vc_data *vc)
604 {
605         dead_key_next = true;
606 }
607
608 static void fn_spawn_con(struct vc_data *vc)
609 {
610         spin_lock(&vt_spawn_con.lock);
611         if (vt_spawn_con.pid)
612                 if (kill_pid(vt_spawn_con.pid, vt_spawn_con.sig, 1)) {
613                         put_pid(vt_spawn_con.pid);
614                         vt_spawn_con.pid = NULL;
615                 }
616         spin_unlock(&vt_spawn_con.lock);
617 }
618
619 static void fn_SAK(struct vc_data *vc)
620 {
621         struct work_struct *SAK_work = &vc_cons[fg_console].SAK_work;
622         schedule_work(SAK_work);
623 }
624
625 static void fn_null(struct vc_data *vc)
626 {
627         do_compute_shiftstate();
628 }
629
630 /*
631  * Special key handlers
632  */
633 static void k_ignore(struct vc_data *vc, unsigned char value, char up_flag)
634 {
635 }
636
637 static void k_spec(struct vc_data *vc, unsigned char value, char up_flag)
638 {
639         if (up_flag)
640                 return;
641         if (value >= ARRAY_SIZE(fn_handler))
642                 return;
643         if ((kbd->kbdmode == VC_RAW ||
644              kbd->kbdmode == VC_MEDIUMRAW ||
645              kbd->kbdmode == VC_OFF) &&
646              value != KVAL(K_SAK))
647                 return;         /* SAK is allowed even in raw mode */
648         fn_handler[value](vc);
649 }
650
651 static void k_lowercase(struct vc_data *vc, unsigned char value, char up_flag)
652 {
653         pr_err("k_lowercase was called - impossible\n");
654 }
655
656 static void k_unicode(struct vc_data *vc, unsigned int value, char up_flag)
657 {
658         if (up_flag)
659                 return;         /* no action, if this is a key release */
660
661         if (diacr)
662                 value = handle_diacr(vc, value);
663
664         if (dead_key_next) {
665                 dead_key_next = false;
666                 diacr = value;
667                 return;
668         }
669         if (kbd->kbdmode == VC_UNICODE)
670                 to_utf8(vc, value);
671         else {
672                 int c = conv_uni_to_8bit(value);
673                 if (c != -1)
674                         put_queue(vc, c);
675         }
676 }
677
678 /*
679  * Handle dead key. Note that we now may have several
680  * dead keys modifying the same character. Very useful
681  * for Vietnamese.
682  */
683 static void k_deadunicode(struct vc_data *vc, unsigned int value, char up_flag)
684 {
685         if (up_flag)
686                 return;
687
688         diacr = (diacr ? handle_diacr(vc, value) : value);
689 }
690
691 static void k_self(struct vc_data *vc, unsigned char value, char up_flag)
692 {
693         k_unicode(vc, conv_8bit_to_uni(value), up_flag);
694 }
695
696 static void k_dead2(struct vc_data *vc, unsigned char value, char up_flag)
697 {
698         k_deadunicode(vc, value, up_flag);
699 }
700
701 /*
702  * Obsolete - for backwards compatibility only
703  */
704 static void k_dead(struct vc_data *vc, unsigned char value, char up_flag)
705 {
706         static const unsigned char ret_diacr[NR_DEAD] = {
707                 '`',    /* dead_grave */
708                 '\'',   /* dead_acute */
709                 '^',    /* dead_circumflex */
710                 '~',    /* dead_tilda */
711                 '"',    /* dead_diaeresis */
712                 ',',    /* dead_cedilla */
713                 '_',    /* dead_macron */
714                 'U',    /* dead_breve */
715                 '.',    /* dead_abovedot */
716                 '*',    /* dead_abovering */
717                 '=',    /* dead_doubleacute */
718                 'c',    /* dead_caron */
719                 'k',    /* dead_ogonek */
720                 'i',    /* dead_iota */
721                 '#',    /* dead_voiced_sound */
722                 'o',    /* dead_semivoiced_sound */
723                 '!',    /* dead_belowdot */
724                 '?',    /* dead_hook */
725                 '+',    /* dead_horn */
726                 '-',    /* dead_stroke */
727                 ')',    /* dead_abovecomma */
728                 '(',    /* dead_abovereversedcomma */
729                 ':',    /* dead_doublegrave */
730                 'n',    /* dead_invertedbreve */
731                 ';',    /* dead_belowcomma */
732                 '$',    /* dead_currency */
733                 '@',    /* dead_greek */
734         };
735
736         k_deadunicode(vc, ret_diacr[value], up_flag);
737 }
738
739 static void k_cons(struct vc_data *vc, unsigned char value, char up_flag)
740 {
741         if (up_flag)
742                 return;
743
744         set_console(value);
745 }
746
747 static void k_fn(struct vc_data *vc, unsigned char value, char up_flag)
748 {
749         if (up_flag)
750                 return;
751
752         if ((unsigned)value < ARRAY_SIZE(func_table)) {
753                 unsigned long flags;
754
755                 spin_lock_irqsave(&func_buf_lock, flags);
756                 if (func_table[value])
757                         puts_queue(vc, func_table[value]);
758                 spin_unlock_irqrestore(&func_buf_lock, flags);
759
760         } else
761                 pr_err("k_fn called with value=%d\n", value);
762 }
763
764 static void k_cur(struct vc_data *vc, unsigned char value, char up_flag)
765 {
766         static const char cur_chars[] = "BDCA";
767
768         if (up_flag)
769                 return;
770
771         applkey(vc, cur_chars[value], vc_kbd_mode(kbd, VC_CKMODE));
772 }
773
774 static void k_pad(struct vc_data *vc, unsigned char value, char up_flag)
775 {
776         static const char pad_chars[] = "0123456789+-*/\015,.?()#";
777         static const char app_map[] = "pqrstuvwxylSRQMnnmPQS";
778
779         if (up_flag)
780                 return;         /* no action, if this is a key release */
781
782         /* kludge... shift forces cursor/number keys */
783         if (vc_kbd_mode(kbd, VC_APPLIC) && !shift_down[KG_SHIFT]) {
784                 applkey(vc, app_map[value], 1);
785                 return;
786         }
787
788         if (!vc_kbd_led(kbd, VC_NUMLOCK)) {
789
790                 switch (value) {
791                 case KVAL(K_PCOMMA):
792                 case KVAL(K_PDOT):
793                         k_fn(vc, KVAL(K_REMOVE), 0);
794                         return;
795                 case KVAL(K_P0):
796                         k_fn(vc, KVAL(K_INSERT), 0);
797                         return;
798                 case KVAL(K_P1):
799                         k_fn(vc, KVAL(K_SELECT), 0);
800                         return;
801                 case KVAL(K_P2):
802                         k_cur(vc, KVAL(K_DOWN), 0);
803                         return;
804                 case KVAL(K_P3):
805                         k_fn(vc, KVAL(K_PGDN), 0);
806                         return;
807                 case KVAL(K_P4):
808                         k_cur(vc, KVAL(K_LEFT), 0);
809                         return;
810                 case KVAL(K_P6):
811                         k_cur(vc, KVAL(K_RIGHT), 0);
812                         return;
813                 case KVAL(K_P7):
814                         k_fn(vc, KVAL(K_FIND), 0);
815                         return;
816                 case KVAL(K_P8):
817                         k_cur(vc, KVAL(K_UP), 0);
818                         return;
819                 case KVAL(K_P9):
820                         k_fn(vc, KVAL(K_PGUP), 0);
821                         return;
822                 case KVAL(K_P5):
823                         applkey(vc, 'G', vc_kbd_mode(kbd, VC_APPLIC));
824                         return;
825                 }
826         }
827
828         put_queue(vc, pad_chars[value]);
829         if (value == KVAL(K_PENTER) && vc_kbd_mode(kbd, VC_CRLF))
830                 put_queue(vc, 10);
831 }
832
833 static void k_shift(struct vc_data *vc, unsigned char value, char up_flag)
834 {
835         int old_state = shift_state;
836
837         if (rep)
838                 return;
839         /*
840          * Mimic typewriter:
841          * a CapsShift key acts like Shift but undoes CapsLock
842          */
843         if (value == KVAL(K_CAPSSHIFT)) {
844                 value = KVAL(K_SHIFT);
845                 if (!up_flag)
846                         clr_vc_kbd_led(kbd, VC_CAPSLOCK);
847         }
848
849         if (up_flag) {
850                 /*
851                  * handle the case that two shift or control
852                  * keys are depressed simultaneously
853                  */
854                 if (shift_down[value])
855                         shift_down[value]--;
856         } else
857                 shift_down[value]++;
858
859         if (shift_down[value])
860                 shift_state |= (1 << value);
861         else
862                 shift_state &= ~(1 << value);
863
864         /* kludge */
865         if (up_flag && shift_state != old_state && npadch_active) {
866                 if (kbd->kbdmode == VC_UNICODE)
867                         to_utf8(vc, npadch_value);
868                 else
869                         put_queue(vc, npadch_value & 0xff);
870                 npadch_active = false;
871         }
872 }
873
874 static void k_meta(struct vc_data *vc, unsigned char value, char up_flag)
875 {
876         if (up_flag)
877                 return;
878
879         if (vc_kbd_mode(kbd, VC_META)) {
880                 put_queue(vc, '\033');
881                 put_queue(vc, value);
882         } else
883                 put_queue(vc, value | 0x80);
884 }
885
886 static void k_ascii(struct vc_data *vc, unsigned char value, char up_flag)
887 {
888         unsigned int base;
889
890         if (up_flag)
891                 return;
892
893         if (value < 10) {
894                 /* decimal input of code, while Alt depressed */
895                 base = 10;
896         } else {
897                 /* hexadecimal input of code, while AltGr depressed */
898                 value -= 10;
899                 base = 16;
900         }
901
902         if (!npadch_active) {
903                 npadch_value = 0;
904                 npadch_active = true;
905         }
906
907         npadch_value = npadch_value * base + value;
908 }
909
910 static void k_lock(struct vc_data *vc, unsigned char value, char up_flag)
911 {
912         if (up_flag || rep)
913                 return;
914
915         chg_vc_kbd_lock(kbd, value);
916 }
917
918 static void k_slock(struct vc_data *vc, unsigned char value, char up_flag)
919 {
920         k_shift(vc, value, up_flag);
921         if (up_flag || rep)
922                 return;
923
924         chg_vc_kbd_slock(kbd, value);
925         /* try to make Alt, oops, AltGr and such work */
926         if (!key_maps[kbd->lockstate ^ kbd->slockstate]) {
927                 kbd->slockstate = 0;
928                 chg_vc_kbd_slock(kbd, value);
929         }
930 }
931
932 /* by default, 300ms interval for combination release */
933 static unsigned brl_timeout = 300;
934 MODULE_PARM_DESC(brl_timeout, "Braille keys release delay in ms (0 for commit on first key release)");
935 module_param(brl_timeout, uint, 0644);
936
937 static unsigned brl_nbchords = 1;
938 MODULE_PARM_DESC(brl_nbchords, "Number of chords that produce a braille pattern (0 for dead chords)");
939 module_param(brl_nbchords, uint, 0644);
940
941 static void k_brlcommit(struct vc_data *vc, unsigned int pattern, char up_flag)
942 {
943         static unsigned long chords;
944         static unsigned committed;
945
946         if (!brl_nbchords)
947                 k_deadunicode(vc, BRL_UC_ROW | pattern, up_flag);
948         else {
949                 committed |= pattern;
950                 chords++;
951                 if (chords == brl_nbchords) {
952                         k_unicode(vc, BRL_UC_ROW | committed, up_flag);
953                         chords = 0;
954                         committed = 0;
955                 }
956         }
957 }
958
959 static void k_brl(struct vc_data *vc, unsigned char value, char up_flag)
960 {
961         static unsigned pressed, committing;
962         static unsigned long releasestart;
963
964         if (kbd->kbdmode != VC_UNICODE) {
965                 if (!up_flag)
966                         pr_warn("keyboard mode must be unicode for braille patterns\n");
967                 return;
968         }
969
970         if (!value) {
971                 k_unicode(vc, BRL_UC_ROW, up_flag);
972                 return;
973         }
974
975         if (value > 8)
976                 return;
977
978         if (!up_flag) {
979                 pressed |= 1 << (value - 1);
980                 if (!brl_timeout)
981                         committing = pressed;
982         } else if (brl_timeout) {
983                 if (!committing ||
984                     time_after(jiffies,
985                                releasestart + msecs_to_jiffies(brl_timeout))) {
986                         committing = pressed;
987                         releasestart = jiffies;
988                 }
989                 pressed &= ~(1 << (value - 1));
990                 if (!pressed && committing) {
991                         k_brlcommit(vc, committing, 0);
992                         committing = 0;
993                 }
994         } else {
995                 if (committing) {
996                         k_brlcommit(vc, committing, 0);
997                         committing = 0;
998                 }
999                 pressed &= ~(1 << (value - 1));
1000         }
1001 }
1002
1003 #if IS_ENABLED(CONFIG_INPUT_LEDS) && IS_ENABLED(CONFIG_LEDS_TRIGGERS)
1004
1005 struct kbd_led_trigger {
1006         struct led_trigger trigger;
1007         unsigned int mask;
1008 };
1009
1010 static int kbd_led_trigger_activate(struct led_classdev *cdev)
1011 {
1012         struct kbd_led_trigger *trigger =
1013                 container_of(cdev->trigger, struct kbd_led_trigger, trigger);
1014
1015         tasklet_disable(&keyboard_tasklet);
1016         if (ledstate != -1U)
1017                 led_trigger_event(&trigger->trigger,
1018                                   ledstate & trigger->mask ?
1019                                         LED_FULL : LED_OFF);
1020         tasklet_enable(&keyboard_tasklet);
1021
1022         return 0;
1023 }
1024
1025 #define KBD_LED_TRIGGER(_led_bit, _name) {                      \
1026                 .trigger = {                                    \
1027                         .name = _name,                          \
1028                         .activate = kbd_led_trigger_activate,   \
1029                 },                                              \
1030                 .mask   = BIT(_led_bit),                        \
1031         }
1032
1033 #define KBD_LOCKSTATE_TRIGGER(_led_bit, _name)          \
1034         KBD_LED_TRIGGER((_led_bit) + 8, _name)
1035
1036 static struct kbd_led_trigger kbd_led_triggers[] = {
1037         KBD_LED_TRIGGER(VC_SCROLLOCK, "kbd-scrolllock"),
1038         KBD_LED_TRIGGER(VC_NUMLOCK,   "kbd-numlock"),
1039         KBD_LED_TRIGGER(VC_CAPSLOCK,  "kbd-capslock"),
1040         KBD_LED_TRIGGER(VC_KANALOCK,  "kbd-kanalock"),
1041
1042         KBD_LOCKSTATE_TRIGGER(VC_SHIFTLOCK,  "kbd-shiftlock"),
1043         KBD_LOCKSTATE_TRIGGER(VC_ALTGRLOCK,  "kbd-altgrlock"),
1044         KBD_LOCKSTATE_TRIGGER(VC_CTRLLOCK,   "kbd-ctrllock"),
1045         KBD_LOCKSTATE_TRIGGER(VC_ALTLOCK,    "kbd-altlock"),
1046         KBD_LOCKSTATE_TRIGGER(VC_SHIFTLLOCK, "kbd-shiftllock"),
1047         KBD_LOCKSTATE_TRIGGER(VC_SHIFTRLOCK, "kbd-shiftrlock"),
1048         KBD_LOCKSTATE_TRIGGER(VC_CTRLLLOCK,  "kbd-ctrlllock"),
1049         KBD_LOCKSTATE_TRIGGER(VC_CTRLRLOCK,  "kbd-ctrlrlock"),
1050 };
1051
1052 static void kbd_propagate_led_state(unsigned int old_state,
1053                                     unsigned int new_state)
1054 {
1055         struct kbd_led_trigger *trigger;
1056         unsigned int changed = old_state ^ new_state;
1057         int i;
1058
1059         for (i = 0; i < ARRAY_SIZE(kbd_led_triggers); i++) {
1060                 trigger = &kbd_led_triggers[i];
1061
1062                 if (changed & trigger->mask)
1063                         led_trigger_event(&trigger->trigger,
1064                                           new_state & trigger->mask ?
1065                                                 LED_FULL : LED_OFF);
1066         }
1067 }
1068
1069 static int kbd_update_leds_helper(struct input_handle *handle, void *data)
1070 {
1071         unsigned int led_state = *(unsigned int *)data;
1072
1073         if (test_bit(EV_LED, handle->dev->evbit))
1074                 kbd_propagate_led_state(~led_state, led_state);
1075
1076         return 0;
1077 }
1078
1079 static void kbd_init_leds(void)
1080 {
1081         int error;
1082         int i;
1083
1084         for (i = 0; i < ARRAY_SIZE(kbd_led_triggers); i++) {
1085                 error = led_trigger_register(&kbd_led_triggers[i].trigger);
1086                 if (error)
1087                         pr_err("error %d while registering trigger %s\n",
1088                                error, kbd_led_triggers[i].trigger.name);
1089         }
1090 }
1091
1092 #else
1093
1094 static int kbd_update_leds_helper(struct input_handle *handle, void *data)
1095 {
1096         unsigned int leds = *(unsigned int *)data;
1097
1098         if (test_bit(EV_LED, handle->dev->evbit)) {
1099                 input_inject_event(handle, EV_LED, LED_SCROLLL, !!(leds & 0x01));
1100                 input_inject_event(handle, EV_LED, LED_NUML,    !!(leds & 0x02));
1101                 input_inject_event(handle, EV_LED, LED_CAPSL,   !!(leds & 0x04));
1102                 input_inject_event(handle, EV_SYN, SYN_REPORT, 0);
1103         }
1104
1105         return 0;
1106 }
1107
1108 static void kbd_propagate_led_state(unsigned int old_state,
1109                                     unsigned int new_state)
1110 {
1111         input_handler_for_each_handle(&kbd_handler, &new_state,
1112                                       kbd_update_leds_helper);
1113 }
1114
1115 static void kbd_init_leds(void)
1116 {
1117 }
1118
1119 #endif
1120
1121 /*
1122  * The leds display either (i) the status of NumLock, CapsLock, ScrollLock,
1123  * or (ii) whatever pattern of lights people want to show using KDSETLED,
1124  * or (iii) specified bits of specified words in kernel memory.
1125  */
1126 static unsigned char getledstate(void)
1127 {
1128         return ledstate & 0xff;
1129 }
1130
1131 void setledstate(struct kbd_struct *kb, unsigned int led)
1132 {
1133         unsigned long flags;
1134         spin_lock_irqsave(&led_lock, flags);
1135         if (!(led & ~7)) {
1136                 ledioctl = led;
1137                 kb->ledmode = LED_SHOW_IOCTL;
1138         } else
1139                 kb->ledmode = LED_SHOW_FLAGS;
1140
1141         set_leds();
1142         spin_unlock_irqrestore(&led_lock, flags);
1143 }
1144
1145 static inline unsigned char getleds(void)
1146 {
1147         struct kbd_struct *kb = kbd_table + fg_console;
1148
1149         if (kb->ledmode == LED_SHOW_IOCTL)
1150                 return ledioctl;
1151
1152         return kb->ledflagstate;
1153 }
1154
1155 /**
1156  *      vt_get_leds     -       helper for braille console
1157  *      @console: console to read
1158  *      @flag: flag we want to check
1159  *
1160  *      Check the status of a keyboard led flag and report it back
1161  */
1162 int vt_get_leds(int console, int flag)
1163 {
1164         struct kbd_struct *kb = kbd_table + console;
1165         int ret;
1166         unsigned long flags;
1167
1168         spin_lock_irqsave(&led_lock, flags);
1169         ret = vc_kbd_led(kb, flag);
1170         spin_unlock_irqrestore(&led_lock, flags);
1171
1172         return ret;
1173 }
1174 EXPORT_SYMBOL_GPL(vt_get_leds);
1175
1176 /**
1177  *      vt_set_led_state        -       set LED state of a console
1178  *      @console: console to set
1179  *      @leds: LED bits
1180  *
1181  *      Set the LEDs on a console. This is a wrapper for the VT layer
1182  *      so that we can keep kbd knowledge internal
1183  */
1184 void vt_set_led_state(int console, int leds)
1185 {
1186         struct kbd_struct *kb = kbd_table + console;
1187         setledstate(kb, leds);
1188 }
1189
1190 /**
1191  *      vt_kbd_con_start        -       Keyboard side of console start
1192  *      @console: console
1193  *
1194  *      Handle console start. This is a wrapper for the VT layer
1195  *      so that we can keep kbd knowledge internal
1196  *
1197  *      FIXME: We eventually need to hold the kbd lock here to protect
1198  *      the LED updating. We can't do it yet because fn_hold calls stop_tty
1199  *      and start_tty under the kbd_event_lock, while normal tty paths
1200  *      don't hold the lock. We probably need to split out an LED lock
1201  *      but not during an -rc release!
1202  */
1203 void vt_kbd_con_start(int console)
1204 {
1205         struct kbd_struct *kb = kbd_table + console;
1206         unsigned long flags;
1207         spin_lock_irqsave(&led_lock, flags);
1208         clr_vc_kbd_led(kb, VC_SCROLLOCK);
1209         set_leds();
1210         spin_unlock_irqrestore(&led_lock, flags);
1211 }
1212
1213 /**
1214  *      vt_kbd_con_stop         -       Keyboard side of console stop
1215  *      @console: console
1216  *
1217  *      Handle console stop. This is a wrapper for the VT layer
1218  *      so that we can keep kbd knowledge internal
1219  */
1220 void vt_kbd_con_stop(int console)
1221 {
1222         struct kbd_struct *kb = kbd_table + console;
1223         unsigned long flags;
1224         spin_lock_irqsave(&led_lock, flags);
1225         set_vc_kbd_led(kb, VC_SCROLLOCK);
1226         set_leds();
1227         spin_unlock_irqrestore(&led_lock, flags);
1228 }
1229
1230 /*
1231  * This is the tasklet that updates LED state of LEDs using standard
1232  * keyboard triggers. The reason we use tasklet is that we need to
1233  * handle the scenario when keyboard handler is not registered yet
1234  * but we already getting updates from the VT to update led state.
1235  */
1236 static void kbd_bh(unsigned long dummy)
1237 {
1238         unsigned int leds;
1239         unsigned long flags;
1240
1241         spin_lock_irqsave(&led_lock, flags);
1242         leds = getleds();
1243         leds |= (unsigned int)kbd->lockstate << 8;
1244         spin_unlock_irqrestore(&led_lock, flags);
1245
1246         if (leds != ledstate) {
1247                 kbd_propagate_led_state(ledstate, leds);
1248                 ledstate = leds;
1249         }
1250 }
1251
1252 DECLARE_TASKLET_DISABLED_OLD(keyboard_tasklet, kbd_bh);
1253
1254 #if defined(CONFIG_X86) || defined(CONFIG_IA64) || defined(CONFIG_ALPHA) ||\
1255     defined(CONFIG_MIPS) || defined(CONFIG_PPC) || defined(CONFIG_SPARC) ||\
1256     defined(CONFIG_PARISC) || defined(CONFIG_SUPERH) ||\
1257     (defined(CONFIG_ARM) && defined(CONFIG_KEYBOARD_ATKBD) && !defined(CONFIG_ARCH_RPC))
1258
1259 static inline bool kbd_is_hw_raw(const struct input_dev *dev)
1260 {
1261         if (!test_bit(EV_MSC, dev->evbit) || !test_bit(MSC_RAW, dev->mscbit))
1262                 return false;
1263
1264         return dev->id.bustype == BUS_I8042 &&
1265                 dev->id.vendor == 0x0001 && dev->id.product == 0x0001;
1266 }
1267
1268 static const unsigned short x86_keycodes[256] =
1269         { 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,
1270          16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
1271          32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
1272          48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
1273          64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
1274          80, 81, 82, 83, 84,118, 86, 87, 88,115,120,119,121,112,123, 92,
1275         284,285,309,  0,312, 91,327,328,329,331,333,335,336,337,338,339,
1276         367,288,302,304,350, 89,334,326,267,126,268,269,125,347,348,349,
1277         360,261,262,263,268,376,100,101,321,316,373,286,289,102,351,355,
1278         103,104,105,275,287,279,258,106,274,107,294,364,358,363,362,361,
1279         291,108,381,281,290,272,292,305,280, 99,112,257,306,359,113,114,
1280         264,117,271,374,379,265,266, 93, 94, 95, 85,259,375,260, 90,116,
1281         377,109,111,277,278,282,283,295,296,297,299,300,301,293,303,307,
1282         308,310,313,314,315,317,318,319,320,357,322,323,324,325,276,330,
1283         332,340,365,342,343,344,345,346,356,270,341,368,369,370,371,372 };
1284
1285 #ifdef CONFIG_SPARC
1286 static int sparc_l1_a_state;
1287 extern void sun_do_break(void);
1288 #endif
1289
1290 static int emulate_raw(struct vc_data *vc, unsigned int keycode,
1291                        unsigned char up_flag)
1292 {
1293         int code;
1294
1295         switch (keycode) {
1296
1297         case KEY_PAUSE:
1298                 put_queue(vc, 0xe1);
1299                 put_queue(vc, 0x1d | up_flag);
1300                 put_queue(vc, 0x45 | up_flag);
1301                 break;
1302
1303         case KEY_HANGEUL:
1304                 if (!up_flag)
1305                         put_queue(vc, 0xf2);
1306                 break;
1307
1308         case KEY_HANJA:
1309                 if (!up_flag)
1310                         put_queue(vc, 0xf1);
1311                 break;
1312
1313         case KEY_SYSRQ:
1314                 /*
1315                  * Real AT keyboards (that's what we're trying
1316                  * to emulate here) emit 0xe0 0x2a 0xe0 0x37 when
1317                  * pressing PrtSc/SysRq alone, but simply 0x54
1318                  * when pressing Alt+PrtSc/SysRq.
1319                  */
1320                 if (test_bit(KEY_LEFTALT, key_down) ||
1321                     test_bit(KEY_RIGHTALT, key_down)) {
1322                         put_queue(vc, 0x54 | up_flag);
1323                 } else {
1324                         put_queue(vc, 0xe0);
1325                         put_queue(vc, 0x2a | up_flag);
1326                         put_queue(vc, 0xe0);
1327                         put_queue(vc, 0x37 | up_flag);
1328                 }
1329                 break;
1330
1331         default:
1332                 if (keycode > 255)
1333                         return -1;
1334
1335                 code = x86_keycodes[keycode];
1336                 if (!code)
1337                         return -1;
1338
1339                 if (code & 0x100)
1340                         put_queue(vc, 0xe0);
1341                 put_queue(vc, (code & 0x7f) | up_flag);
1342
1343                 break;
1344         }
1345
1346         return 0;
1347 }
1348
1349 #else
1350
1351 static inline bool kbd_is_hw_raw(const struct input_dev *dev)
1352 {
1353         return false;
1354 }
1355
1356 static int emulate_raw(struct vc_data *vc, unsigned int keycode, unsigned char up_flag)
1357 {
1358         if (keycode > 127)
1359                 return -1;
1360
1361         put_queue(vc, keycode | up_flag);
1362         return 0;
1363 }
1364 #endif
1365
1366 static void kbd_rawcode(unsigned char data)
1367 {
1368         struct vc_data *vc = vc_cons[fg_console].d;
1369
1370         kbd = kbd_table + vc->vc_num;
1371         if (kbd->kbdmode == VC_RAW)
1372                 put_queue(vc, data);
1373 }
1374
1375 static void kbd_keycode(unsigned int keycode, int down, bool hw_raw)
1376 {
1377         struct vc_data *vc = vc_cons[fg_console].d;
1378         unsigned short keysym, *key_map;
1379         unsigned char type;
1380         bool raw_mode;
1381         struct tty_struct *tty;
1382         int shift_final;
1383         struct keyboard_notifier_param param = { .vc = vc, .value = keycode, .down = down };
1384         int rc;
1385
1386         tty = vc->port.tty;
1387
1388         if (tty && (!tty->driver_data)) {
1389                 /* No driver data? Strange. Okay we fix it then. */
1390                 tty->driver_data = vc;
1391         }
1392
1393         kbd = kbd_table + vc->vc_num;
1394
1395 #ifdef CONFIG_SPARC
1396         if (keycode == KEY_STOP)
1397                 sparc_l1_a_state = down;
1398 #endif
1399
1400         rep = (down == 2);
1401
1402         raw_mode = (kbd->kbdmode == VC_RAW);
1403         if (raw_mode && !hw_raw)
1404                 if (emulate_raw(vc, keycode, !down << 7))
1405                         if (keycode < BTN_MISC && printk_ratelimit())
1406                                 pr_warn("can't emulate rawmode for keycode %d\n",
1407                                         keycode);
1408
1409 #ifdef CONFIG_SPARC
1410         if (keycode == KEY_A && sparc_l1_a_state) {
1411                 sparc_l1_a_state = false;
1412                 sun_do_break();
1413         }
1414 #endif
1415
1416         if (kbd->kbdmode == VC_MEDIUMRAW) {
1417                 /*
1418                  * This is extended medium raw mode, with keys above 127
1419                  * encoded as 0, high 7 bits, low 7 bits, with the 0 bearing
1420                  * the 'up' flag if needed. 0 is reserved, so this shouldn't
1421                  * interfere with anything else. The two bytes after 0 will
1422                  * always have the up flag set not to interfere with older
1423                  * applications. This allows for 16384 different keycodes,
1424                  * which should be enough.
1425                  */
1426                 if (keycode < 128) {
1427                         put_queue(vc, keycode | (!down << 7));
1428                 } else {
1429                         put_queue(vc, !down << 7);
1430                         put_queue(vc, (keycode >> 7) | 0x80);
1431                         put_queue(vc, keycode | 0x80);
1432                 }
1433                 raw_mode = true;
1434         }
1435
1436         if (down)
1437                 set_bit(keycode, key_down);
1438         else
1439                 clear_bit(keycode, key_down);
1440
1441         if (rep &&
1442             (!vc_kbd_mode(kbd, VC_REPEAT) ||
1443              (tty && !L_ECHO(tty) && tty_chars_in_buffer(tty)))) {
1444                 /*
1445                  * Don't repeat a key if the input buffers are not empty and the
1446                  * characters get aren't echoed locally. This makes key repeat
1447                  * usable with slow applications and under heavy loads.
1448                  */
1449                 return;
1450         }
1451
1452         param.shift = shift_final = (shift_state | kbd->slockstate) ^ kbd->lockstate;
1453         param.ledstate = kbd->ledflagstate;
1454         key_map = key_maps[shift_final];
1455
1456         rc = atomic_notifier_call_chain(&keyboard_notifier_list,
1457                                         KBD_KEYCODE, &param);
1458         if (rc == NOTIFY_STOP || !key_map) {
1459                 atomic_notifier_call_chain(&keyboard_notifier_list,
1460                                            KBD_UNBOUND_KEYCODE, &param);
1461                 do_compute_shiftstate();
1462                 kbd->slockstate = 0;
1463                 return;
1464         }
1465
1466         if (keycode < NR_KEYS)
1467                 keysym = key_map[keycode];
1468         else if (keycode >= KEY_BRL_DOT1 && keycode <= KEY_BRL_DOT8)
1469                 keysym = U(K(KT_BRL, keycode - KEY_BRL_DOT1 + 1));
1470         else
1471                 return;
1472
1473         type = KTYP(keysym);
1474
1475         if (type < 0xf0) {
1476                 param.value = keysym;
1477                 rc = atomic_notifier_call_chain(&keyboard_notifier_list,
1478                                                 KBD_UNICODE, &param);
1479                 if (rc != NOTIFY_STOP)
1480                         if (down && !raw_mode)
1481                                 k_unicode(vc, keysym, !down);
1482                 return;
1483         }
1484
1485         type -= 0xf0;
1486
1487         if (type == KT_LETTER) {
1488                 type = KT_LATIN;
1489                 if (vc_kbd_led(kbd, VC_CAPSLOCK)) {
1490                         key_map = key_maps[shift_final ^ (1 << KG_SHIFT)];
1491                         if (key_map)
1492                                 keysym = key_map[keycode];
1493                 }
1494         }
1495
1496         param.value = keysym;
1497         rc = atomic_notifier_call_chain(&keyboard_notifier_list,
1498                                         KBD_KEYSYM, &param);
1499         if (rc == NOTIFY_STOP)
1500                 return;
1501
1502         if ((raw_mode || kbd->kbdmode == VC_OFF) && type != KT_SPEC && type != KT_SHIFT)
1503                 return;
1504
1505         (*k_handler[type])(vc, keysym & 0xff, !down);
1506
1507         param.ledstate = kbd->ledflagstate;
1508         atomic_notifier_call_chain(&keyboard_notifier_list, KBD_POST_KEYSYM, &param);
1509
1510         if (type != KT_SLOCK)
1511                 kbd->slockstate = 0;
1512 }
1513
1514 static void kbd_event(struct input_handle *handle, unsigned int event_type,
1515                       unsigned int event_code, int value)
1516 {
1517         /* We are called with interrupts disabled, just take the lock */
1518         spin_lock(&kbd_event_lock);
1519
1520         if (event_type == EV_MSC && event_code == MSC_RAW &&
1521                         kbd_is_hw_raw(handle->dev))
1522                 kbd_rawcode(value);
1523         if (event_type == EV_KEY && event_code <= KEY_MAX)
1524                 kbd_keycode(event_code, value, kbd_is_hw_raw(handle->dev));
1525
1526         spin_unlock(&kbd_event_lock);
1527
1528         tasklet_schedule(&keyboard_tasklet);
1529         do_poke_blanked_console = 1;
1530         schedule_console_callback();
1531 }
1532
1533 static bool kbd_match(struct input_handler *handler, struct input_dev *dev)
1534 {
1535         if (test_bit(EV_SND, dev->evbit))
1536                 return true;
1537
1538         if (test_bit(EV_KEY, dev->evbit)) {
1539                 if (find_next_bit(dev->keybit, BTN_MISC, KEY_RESERVED) <
1540                                 BTN_MISC)
1541                         return true;
1542                 if (find_next_bit(dev->keybit, KEY_BRL_DOT10 + 1,
1543                                         KEY_BRL_DOT1) <= KEY_BRL_DOT10)
1544                         return true;
1545         }
1546
1547         return false;
1548 }
1549
1550 /*
1551  * When a keyboard (or other input device) is found, the kbd_connect
1552  * function is called. The function then looks at the device, and if it
1553  * likes it, it can open it and get events from it. In this (kbd_connect)
1554  * function, we should decide which VT to bind that keyboard to initially.
1555  */
1556 static int kbd_connect(struct input_handler *handler, struct input_dev *dev,
1557                         const struct input_device_id *id)
1558 {
1559         struct input_handle *handle;
1560         int error;
1561
1562         handle = kzalloc(sizeof(struct input_handle), GFP_KERNEL);
1563         if (!handle)
1564                 return -ENOMEM;
1565
1566         handle->dev = dev;
1567         handle->handler = handler;
1568         handle->name = "kbd";
1569
1570         error = input_register_handle(handle);
1571         if (error)
1572                 goto err_free_handle;
1573
1574         error = input_open_device(handle);
1575         if (error)
1576                 goto err_unregister_handle;
1577
1578         return 0;
1579
1580  err_unregister_handle:
1581         input_unregister_handle(handle);
1582  err_free_handle:
1583         kfree(handle);
1584         return error;
1585 }
1586
1587 static void kbd_disconnect(struct input_handle *handle)
1588 {
1589         input_close_device(handle);
1590         input_unregister_handle(handle);
1591         kfree(handle);
1592 }
1593
1594 /*
1595  * Start keyboard handler on the new keyboard by refreshing LED state to
1596  * match the rest of the system.
1597  */
1598 static void kbd_start(struct input_handle *handle)
1599 {
1600         tasklet_disable(&keyboard_tasklet);
1601
1602         if (ledstate != -1U)
1603                 kbd_update_leds_helper(handle, &ledstate);
1604
1605         tasklet_enable(&keyboard_tasklet);
1606 }
1607
1608 static const struct input_device_id kbd_ids[] = {
1609         {
1610                 .flags = INPUT_DEVICE_ID_MATCH_EVBIT,
1611                 .evbit = { BIT_MASK(EV_KEY) },
1612         },
1613
1614         {
1615                 .flags = INPUT_DEVICE_ID_MATCH_EVBIT,
1616                 .evbit = { BIT_MASK(EV_SND) },
1617         },
1618
1619         { },    /* Terminating entry */
1620 };
1621
1622 MODULE_DEVICE_TABLE(input, kbd_ids);
1623
1624 static struct input_handler kbd_handler = {
1625         .event          = kbd_event,
1626         .match          = kbd_match,
1627         .connect        = kbd_connect,
1628         .disconnect     = kbd_disconnect,
1629         .start          = kbd_start,
1630         .name           = "kbd",
1631         .id_table       = kbd_ids,
1632 };
1633
1634 int __init kbd_init(void)
1635 {
1636         int i;
1637         int error;
1638
1639         for (i = 0; i < MAX_NR_CONSOLES; i++) {
1640                 kbd_table[i].ledflagstate = kbd_defleds();
1641                 kbd_table[i].default_ledflagstate = kbd_defleds();
1642                 kbd_table[i].ledmode = LED_SHOW_FLAGS;
1643                 kbd_table[i].lockstate = KBD_DEFLOCK;
1644                 kbd_table[i].slockstate = 0;
1645                 kbd_table[i].modeflags = KBD_DEFMODE;
1646                 kbd_table[i].kbdmode = default_utf8 ? VC_UNICODE : VC_XLATE;
1647         }
1648
1649         kbd_init_leds();
1650
1651         error = input_register_handler(&kbd_handler);
1652         if (error)
1653                 return error;
1654
1655         tasklet_enable(&keyboard_tasklet);
1656         tasklet_schedule(&keyboard_tasklet);
1657
1658         return 0;
1659 }
1660
1661 /* Ioctl support code */
1662
1663 /**
1664  *      vt_do_diacrit           -       diacritical table updates
1665  *      @cmd: ioctl request
1666  *      @udp: pointer to user data for ioctl
1667  *      @perm: permissions check computed by caller
1668  *
1669  *      Update the diacritical tables atomically and safely. Lock them
1670  *      against simultaneous keypresses
1671  */
1672 int vt_do_diacrit(unsigned int cmd, void __user *udp, int perm)
1673 {
1674         unsigned long flags;
1675         int asize;
1676         int ret = 0;
1677
1678         switch (cmd) {
1679         case KDGKBDIACR:
1680         {
1681                 struct kbdiacrs __user *a = udp;
1682                 struct kbdiacr *dia;
1683                 int i;
1684
1685                 dia = kmalloc_array(MAX_DIACR, sizeof(struct kbdiacr),
1686                                                                 GFP_KERNEL);
1687                 if (!dia)
1688                         return -ENOMEM;
1689
1690                 /* Lock the diacriticals table, make a copy and then
1691                    copy it after we unlock */
1692                 spin_lock_irqsave(&kbd_event_lock, flags);
1693
1694                 asize = accent_table_size;
1695                 for (i = 0; i < asize; i++) {
1696                         dia[i].diacr = conv_uni_to_8bit(
1697                                                 accent_table[i].diacr);
1698                         dia[i].base = conv_uni_to_8bit(
1699                                                 accent_table[i].base);
1700                         dia[i].result = conv_uni_to_8bit(
1701                                                 accent_table[i].result);
1702                 }
1703                 spin_unlock_irqrestore(&kbd_event_lock, flags);
1704
1705                 if (put_user(asize, &a->kb_cnt))
1706                         ret = -EFAULT;
1707                 else  if (copy_to_user(a->kbdiacr, dia,
1708                                 asize * sizeof(struct kbdiacr)))
1709                         ret = -EFAULT;
1710                 kfree(dia);
1711                 return ret;
1712         }
1713         case KDGKBDIACRUC:
1714         {
1715                 struct kbdiacrsuc __user *a = udp;
1716                 void *buf;
1717
1718                 buf = kmalloc_array(MAX_DIACR, sizeof(struct kbdiacruc),
1719                                                                 GFP_KERNEL);
1720                 if (buf == NULL)
1721                         return -ENOMEM;
1722
1723                 /* Lock the diacriticals table, make a copy and then
1724                    copy it after we unlock */
1725                 spin_lock_irqsave(&kbd_event_lock, flags);
1726
1727                 asize = accent_table_size;
1728                 memcpy(buf, accent_table, asize * sizeof(struct kbdiacruc));
1729
1730                 spin_unlock_irqrestore(&kbd_event_lock, flags);
1731
1732                 if (put_user(asize, &a->kb_cnt))
1733                         ret = -EFAULT;
1734                 else if (copy_to_user(a->kbdiacruc, buf,
1735                                 asize*sizeof(struct kbdiacruc)))
1736                         ret = -EFAULT;
1737                 kfree(buf);
1738                 return ret;
1739         }
1740
1741         case KDSKBDIACR:
1742         {
1743                 struct kbdiacrs __user *a = udp;
1744                 struct kbdiacr *dia = NULL;
1745                 unsigned int ct;
1746                 int i;
1747
1748                 if (!perm)
1749                         return -EPERM;
1750                 if (get_user(ct, &a->kb_cnt))
1751                         return -EFAULT;
1752                 if (ct >= MAX_DIACR)
1753                         return -EINVAL;
1754
1755                 if (ct) {
1756
1757                         dia = memdup_user(a->kbdiacr,
1758                                         sizeof(struct kbdiacr) * ct);
1759                         if (IS_ERR(dia))
1760                                 return PTR_ERR(dia);
1761
1762                 }
1763
1764                 spin_lock_irqsave(&kbd_event_lock, flags);
1765                 accent_table_size = ct;
1766                 for (i = 0; i < ct; i++) {
1767                         accent_table[i].diacr =
1768                                         conv_8bit_to_uni(dia[i].diacr);
1769                         accent_table[i].base =
1770                                         conv_8bit_to_uni(dia[i].base);
1771                         accent_table[i].result =
1772                                         conv_8bit_to_uni(dia[i].result);
1773                 }
1774                 spin_unlock_irqrestore(&kbd_event_lock, flags);
1775                 kfree(dia);
1776                 return 0;
1777         }
1778
1779         case KDSKBDIACRUC:
1780         {
1781                 struct kbdiacrsuc __user *a = udp;
1782                 unsigned int ct;
1783                 void *buf = NULL;
1784
1785                 if (!perm)
1786                         return -EPERM;
1787
1788                 if (get_user(ct, &a->kb_cnt))
1789                         return -EFAULT;
1790
1791                 if (ct >= MAX_DIACR)
1792                         return -EINVAL;
1793
1794                 if (ct) {
1795                         buf = memdup_user(a->kbdiacruc,
1796                                           ct * sizeof(struct kbdiacruc));
1797                         if (IS_ERR(buf))
1798                                 return PTR_ERR(buf);
1799                 } 
1800                 spin_lock_irqsave(&kbd_event_lock, flags);
1801                 if (ct)
1802                         memcpy(accent_table, buf,
1803                                         ct * sizeof(struct kbdiacruc));
1804                 accent_table_size = ct;
1805                 spin_unlock_irqrestore(&kbd_event_lock, flags);
1806                 kfree(buf);
1807                 return 0;
1808         }
1809         }
1810         return ret;
1811 }
1812
1813 /**
1814  *      vt_do_kdskbmode         -       set keyboard mode ioctl
1815  *      @console: the console to use
1816  *      @arg: the requested mode
1817  *
1818  *      Update the keyboard mode bits while holding the correct locks.
1819  *      Return 0 for success or an error code.
1820  */
1821 int vt_do_kdskbmode(int console, unsigned int arg)
1822 {
1823         struct kbd_struct *kb = kbd_table + console;
1824         int ret = 0;
1825         unsigned long flags;
1826
1827         spin_lock_irqsave(&kbd_event_lock, flags);
1828         switch(arg) {
1829         case K_RAW:
1830                 kb->kbdmode = VC_RAW;
1831                 break;
1832         case K_MEDIUMRAW:
1833                 kb->kbdmode = VC_MEDIUMRAW;
1834                 break;
1835         case K_XLATE:
1836                 kb->kbdmode = VC_XLATE;
1837                 do_compute_shiftstate();
1838                 break;
1839         case K_UNICODE:
1840                 kb->kbdmode = VC_UNICODE;
1841                 do_compute_shiftstate();
1842                 break;
1843         case K_OFF:
1844                 kb->kbdmode = VC_OFF;
1845                 break;
1846         default:
1847                 ret = -EINVAL;
1848         }
1849         spin_unlock_irqrestore(&kbd_event_lock, flags);
1850         return ret;
1851 }
1852
1853 /**
1854  *      vt_do_kdskbmeta         -       set keyboard meta state
1855  *      @console: the console to use
1856  *      @arg: the requested meta state
1857  *
1858  *      Update the keyboard meta bits while holding the correct locks.
1859  *      Return 0 for success or an error code.
1860  */
1861 int vt_do_kdskbmeta(int console, unsigned int arg)
1862 {
1863         struct kbd_struct *kb = kbd_table + console;
1864         int ret = 0;
1865         unsigned long flags;
1866
1867         spin_lock_irqsave(&kbd_event_lock, flags);
1868         switch(arg) {
1869         case K_METABIT:
1870                 clr_vc_kbd_mode(kb, VC_META);
1871                 break;
1872         case K_ESCPREFIX:
1873                 set_vc_kbd_mode(kb, VC_META);
1874                 break;
1875         default:
1876                 ret = -EINVAL;
1877         }
1878         spin_unlock_irqrestore(&kbd_event_lock, flags);
1879         return ret;
1880 }
1881
1882 int vt_do_kbkeycode_ioctl(int cmd, struct kbkeycode __user *user_kbkc,
1883                                                                 int perm)
1884 {
1885         struct kbkeycode tmp;
1886         int kc = 0;
1887
1888         if (copy_from_user(&tmp, user_kbkc, sizeof(struct kbkeycode)))
1889                 return -EFAULT;
1890         switch (cmd) {
1891         case KDGETKEYCODE:
1892                 kc = getkeycode(tmp.scancode);
1893                 if (kc >= 0)
1894                         kc = put_user(kc, &user_kbkc->keycode);
1895                 break;
1896         case KDSETKEYCODE:
1897                 if (!perm)
1898                         return -EPERM;
1899                 kc = setkeycode(tmp.scancode, tmp.keycode);
1900                 break;
1901         }
1902         return kc;
1903 }
1904
1905 static unsigned short vt_kdgkbent(unsigned char kbdmode, unsigned char idx,
1906                 unsigned char map)
1907 {
1908         unsigned short *key_map, val;
1909         unsigned long flags;
1910
1911         /* Ensure another thread doesn't free it under us */
1912         spin_lock_irqsave(&kbd_event_lock, flags);
1913         key_map = key_maps[map];
1914         if (key_map) {
1915                 val = U(key_map[idx]);
1916                 if (kbdmode != VC_UNICODE && KTYP(val) >= NR_TYPES)
1917                         val = K_HOLE;
1918         } else
1919                 val = idx ? K_HOLE : K_NOSUCHMAP;
1920         spin_unlock_irqrestore(&kbd_event_lock, flags);
1921
1922         return val;
1923 }
1924
1925 static int vt_kdskbent(unsigned char kbdmode, unsigned char idx,
1926                 unsigned char map, unsigned short val)
1927 {
1928         unsigned long flags;
1929         unsigned short *key_map, *new_map, oldval;
1930
1931         if (!idx && val == K_NOSUCHMAP) {
1932                 spin_lock_irqsave(&kbd_event_lock, flags);
1933                 /* deallocate map */
1934                 key_map = key_maps[map];
1935                 if (map && key_map) {
1936                         key_maps[map] = NULL;
1937                         if (key_map[0] == U(K_ALLOCATED)) {
1938                                 kfree(key_map);
1939                                 keymap_count--;
1940                         }
1941                 }
1942                 spin_unlock_irqrestore(&kbd_event_lock, flags);
1943
1944                 return 0;
1945         }
1946
1947         if (KTYP(val) < NR_TYPES) {
1948                 if (KVAL(val) > max_vals[KTYP(val)])
1949                         return -EINVAL;
1950         } else if (kbdmode != VC_UNICODE)
1951                 return -EINVAL;
1952
1953         /* ++Geert: non-PC keyboards may generate keycode zero */
1954 #if !defined(__mc68000__) && !defined(__powerpc__)
1955         /* assignment to entry 0 only tests validity of args */
1956         if (!idx)
1957                 return 0;
1958 #endif
1959
1960         new_map = kmalloc(sizeof(plain_map), GFP_KERNEL);
1961         if (!new_map)
1962                 return -ENOMEM;
1963
1964         spin_lock_irqsave(&kbd_event_lock, flags);
1965         key_map = key_maps[map];
1966         if (key_map == NULL) {
1967                 int j;
1968
1969                 if (keymap_count >= MAX_NR_OF_USER_KEYMAPS &&
1970                     !capable(CAP_SYS_RESOURCE)) {
1971                         spin_unlock_irqrestore(&kbd_event_lock, flags);
1972                         kfree(new_map);
1973                         return -EPERM;
1974                 }
1975                 key_maps[map] = new_map;
1976                 key_map = new_map;
1977                 key_map[0] = U(K_ALLOCATED);
1978                 for (j = 1; j < NR_KEYS; j++)
1979                         key_map[j] = U(K_HOLE);
1980                 keymap_count++;
1981         } else
1982                 kfree(new_map);
1983
1984         oldval = U(key_map[idx]);
1985         if (val == oldval)
1986                 goto out;
1987
1988         /* Attention Key */
1989         if ((oldval == K_SAK || val == K_SAK) && !capable(CAP_SYS_ADMIN)) {
1990                 spin_unlock_irqrestore(&kbd_event_lock, flags);
1991                 return -EPERM;
1992         }
1993
1994         key_map[idx] = U(val);
1995         if (!map && (KTYP(oldval) == KT_SHIFT || KTYP(val) == KT_SHIFT))
1996                 do_compute_shiftstate();
1997 out:
1998         spin_unlock_irqrestore(&kbd_event_lock, flags);
1999
2000         return 0;
2001 }
2002
2003 int vt_do_kdsk_ioctl(int cmd, struct kbentry __user *user_kbe, int perm,
2004                                                 int console)
2005 {
2006         struct kbd_struct *kb = kbd_table + console;
2007         struct kbentry kbe;
2008
2009         if (copy_from_user(&kbe, user_kbe, sizeof(struct kbentry)))
2010                 return -EFAULT;
2011
2012         switch (cmd) {
2013         case KDGKBENT:
2014                 return put_user(vt_kdgkbent(kb->kbdmode, kbe.kb_index,
2015                                         kbe.kb_table),
2016                                 &user_kbe->kb_value);
2017         case KDSKBENT:
2018                 if (!perm || !capable(CAP_SYS_TTY_CONFIG))
2019                         return -EPERM;
2020                 return vt_kdskbent(kb->kbdmode, kbe.kb_index, kbe.kb_table,
2021                                 kbe.kb_value);
2022         }
2023         return 0;
2024 }
2025
2026 static char *vt_kdskbsent(char *kbs, unsigned char cur)
2027 {
2028         static DECLARE_BITMAP(is_kmalloc, MAX_NR_FUNC);
2029         char *cur_f = func_table[cur];
2030
2031         if (cur_f && strlen(cur_f) >= strlen(kbs)) {
2032                 strcpy(cur_f, kbs);
2033                 return kbs;
2034         }
2035
2036         func_table[cur] = kbs;
2037
2038         return __test_and_set_bit(cur, is_kmalloc) ? cur_f : NULL;
2039 }
2040
2041 int vt_do_kdgkb_ioctl(int cmd, struct kbsentry __user *user_kdgkb, int perm)
2042 {
2043         unsigned char kb_func;
2044         unsigned long flags;
2045         char *kbs;
2046         int ret;
2047
2048         if (get_user(kb_func, &user_kdgkb->kb_func))
2049                 return -EFAULT;
2050
2051         kb_func = array_index_nospec(kb_func, MAX_NR_FUNC);
2052
2053         switch (cmd) {
2054         case KDGKBSENT: {
2055                 /* size should have been a struct member */
2056                 ssize_t len = sizeof(user_kdgkb->kb_string);
2057
2058                 kbs = kmalloc(len, GFP_KERNEL);
2059                 if (!kbs)
2060                         return -ENOMEM;
2061
2062                 spin_lock_irqsave(&func_buf_lock, flags);
2063                 len = strlcpy(kbs, func_table[kb_func] ? : "", len);
2064                 spin_unlock_irqrestore(&func_buf_lock, flags);
2065
2066                 ret = copy_to_user(user_kdgkb->kb_string, kbs, len + 1) ?
2067                         -EFAULT : 0;
2068
2069                 break;
2070         }
2071         case KDSKBSENT:
2072                 if (!perm || !capable(CAP_SYS_TTY_CONFIG))
2073                         return -EPERM;
2074
2075                 kbs = strndup_user(user_kdgkb->kb_string,
2076                                 sizeof(user_kdgkb->kb_string));
2077                 if (IS_ERR(kbs))
2078                         return PTR_ERR(kbs);
2079
2080                 spin_lock_irqsave(&func_buf_lock, flags);
2081                 kbs = vt_kdskbsent(kbs, kb_func);
2082                 spin_unlock_irqrestore(&func_buf_lock, flags);
2083
2084                 ret = 0;
2085                 break;
2086         }
2087
2088         kfree(kbs);
2089
2090         return ret;
2091 }
2092
2093 int vt_do_kdskled(int console, int cmd, unsigned long arg, int perm)
2094 {
2095         struct kbd_struct *kb = kbd_table + console;
2096         unsigned long flags;
2097         unsigned char ucval;
2098
2099         switch(cmd) {
2100         /* the ioctls below read/set the flags usually shown in the leds */
2101         /* don't use them - they will go away without warning */
2102         case KDGKBLED:
2103                 spin_lock_irqsave(&kbd_event_lock, flags);
2104                 ucval = kb->ledflagstate | (kb->default_ledflagstate << 4);
2105                 spin_unlock_irqrestore(&kbd_event_lock, flags);
2106                 return put_user(ucval, (char __user *)arg);
2107
2108         case KDSKBLED:
2109                 if (!perm)
2110                         return -EPERM;
2111                 if (arg & ~0x77)
2112                         return -EINVAL;
2113                 spin_lock_irqsave(&led_lock, flags);
2114                 kb->ledflagstate = (arg & 7);
2115                 kb->default_ledflagstate = ((arg >> 4) & 7);
2116                 set_leds();
2117                 spin_unlock_irqrestore(&led_lock, flags);
2118                 return 0;
2119
2120         /* the ioctls below only set the lights, not the functions */
2121         /* for those, see KDGKBLED and KDSKBLED above */
2122         case KDGETLED:
2123                 ucval = getledstate();
2124                 return put_user(ucval, (char __user *)arg);
2125
2126         case KDSETLED:
2127                 if (!perm)
2128                         return -EPERM;
2129                 setledstate(kb, arg);
2130                 return 0;
2131         }
2132         return -ENOIOCTLCMD;
2133 }
2134
2135 int vt_do_kdgkbmode(int console)
2136 {
2137         struct kbd_struct *kb = kbd_table + console;
2138         /* This is a spot read so needs no locking */
2139         switch (kb->kbdmode) {
2140         case VC_RAW:
2141                 return K_RAW;
2142         case VC_MEDIUMRAW:
2143                 return K_MEDIUMRAW;
2144         case VC_UNICODE:
2145                 return K_UNICODE;
2146         case VC_OFF:
2147                 return K_OFF;
2148         default:
2149                 return K_XLATE;
2150         }
2151 }
2152
2153 /**
2154  *      vt_do_kdgkbmeta         -       report meta status
2155  *      @console: console to report
2156  *
2157  *      Report the meta flag status of this console
2158  */
2159 int vt_do_kdgkbmeta(int console)
2160 {
2161         struct kbd_struct *kb = kbd_table + console;
2162         /* Again a spot read so no locking */
2163         return vc_kbd_mode(kb, VC_META) ? K_ESCPREFIX : K_METABIT;
2164 }
2165
2166 /**
2167  *      vt_reset_unicode        -       reset the unicode status
2168  *      @console: console being reset
2169  *
2170  *      Restore the unicode console state to its default
2171  */
2172 void vt_reset_unicode(int console)
2173 {
2174         unsigned long flags;
2175
2176         spin_lock_irqsave(&kbd_event_lock, flags);
2177         kbd_table[console].kbdmode = default_utf8 ? VC_UNICODE : VC_XLATE;
2178         spin_unlock_irqrestore(&kbd_event_lock, flags);
2179 }
2180
2181 /**
2182  *      vt_get_shiftstate       -       shift bit state
2183  *
2184  *      Report the shift bits from the keyboard state. We have to export
2185  *      this to support some oddities in the vt layer.
2186  */
2187 int vt_get_shift_state(void)
2188 {
2189         /* Don't lock as this is a transient report */
2190         return shift_state;
2191 }
2192
2193 /**
2194  *      vt_reset_keyboard       -       reset keyboard state
2195  *      @console: console to reset
2196  *
2197  *      Reset the keyboard bits for a console as part of a general console
2198  *      reset event
2199  */
2200 void vt_reset_keyboard(int console)
2201 {
2202         struct kbd_struct *kb = kbd_table + console;
2203         unsigned long flags;
2204
2205         spin_lock_irqsave(&kbd_event_lock, flags);
2206         set_vc_kbd_mode(kb, VC_REPEAT);
2207         clr_vc_kbd_mode(kb, VC_CKMODE);
2208         clr_vc_kbd_mode(kb, VC_APPLIC);
2209         clr_vc_kbd_mode(kb, VC_CRLF);
2210         kb->lockstate = 0;
2211         kb->slockstate = 0;
2212         spin_lock(&led_lock);
2213         kb->ledmode = LED_SHOW_FLAGS;
2214         kb->ledflagstate = kb->default_ledflagstate;
2215         spin_unlock(&led_lock);
2216         /* do not do set_leds here because this causes an endless tasklet loop
2217            when the keyboard hasn't been initialized yet */
2218         spin_unlock_irqrestore(&kbd_event_lock, flags);
2219 }
2220
2221 /**
2222  *      vt_get_kbd_mode_bit     -       read keyboard status bits
2223  *      @console: console to read from
2224  *      @bit: mode bit to read
2225  *
2226  *      Report back a vt mode bit. We do this without locking so the
2227  *      caller must be sure that there are no synchronization needs
2228  */
2229
2230 int vt_get_kbd_mode_bit(int console, int bit)
2231 {
2232         struct kbd_struct *kb = kbd_table + console;
2233         return vc_kbd_mode(kb, bit);
2234 }
2235
2236 /**
2237  *      vt_set_kbd_mode_bit     -       read keyboard status bits
2238  *      @console: console to read from
2239  *      @bit: mode bit to read
2240  *
2241  *      Set a vt mode bit. We do this without locking so the
2242  *      caller must be sure that there are no synchronization needs
2243  */
2244
2245 void vt_set_kbd_mode_bit(int console, int bit)
2246 {
2247         struct kbd_struct *kb = kbd_table + console;
2248         unsigned long flags;
2249
2250         spin_lock_irqsave(&kbd_event_lock, flags);
2251         set_vc_kbd_mode(kb, bit);
2252         spin_unlock_irqrestore(&kbd_event_lock, flags);
2253 }
2254
2255 /**
2256  *      vt_clr_kbd_mode_bit     -       read keyboard status bits
2257  *      @console: console to read from
2258  *      @bit: mode bit to read
2259  *
2260  *      Report back a vt mode bit. We do this without locking so the
2261  *      caller must be sure that there are no synchronization needs
2262  */
2263
2264 void vt_clr_kbd_mode_bit(int console, int bit)
2265 {
2266         struct kbd_struct *kb = kbd_table + console;
2267         unsigned long flags;
2268
2269         spin_lock_irqsave(&kbd_event_lock, flags);
2270         clr_vc_kbd_mode(kb, bit);
2271         spin_unlock_irqrestore(&kbd_event_lock, flags);
2272 }