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