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