xref: /linux/drivers/tty/vt/keyboard.c (revision fab183d632628381b466a41479489541ac0e29a0)
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
kbd_defleds(void)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 
register_keyboard_notifier(struct notifier_block * nb)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 
unregister_keyboard_notifier(struct notifier_block * nb)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 
getkeycode_helper(struct input_handle * handle,void * data)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 
getkeycode(unsigned int scancode)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 
setkeycode_helper(struct input_handle * handle,void * data)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 
setkeycode(unsigned int scancode,unsigned int keycode)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 
kd_sound_helper(struct input_handle * handle,void * data)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 
kd_nosound(struct timer_list * unused)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 
kd_mksound(unsigned int hz,unsigned int ticks)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 
kbd_rate_helper(struct input_handle * handle,void * data)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 
kbd_rate(struct kbd_repeat * rpt)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  */
put_queue(struct vc_data * vc,int ch)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 
puts_queue(struct vc_data * vc,const char * cp)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 
applkey(struct vc_data * vc,int key,char mode)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  */
to_utf8(struct vc_data * vc,uint c)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 
put_queue_utf8(struct vc_data * vc,u32 value)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 */
set_leds(void)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 
do_compute_shiftstate(void)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 */
vt_set_leds_compute_shiftstate(void)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  */
handle_diacr(struct vc_data * vc,unsigned int ch)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  */
fn_enter(struct vc_data * vc)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 
fn_caps_toggle(struct vc_data * vc)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 
fn_caps_on(struct vc_data * vc)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 
fn_show_ptregs(struct vc_data * vc)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 
fn_hold(struct vc_data * vc)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 
fn_num(struct vc_data * vc)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  */
fn_bare_num(struct vc_data * vc)542 static void fn_bare_num(struct vc_data *vc)
543 {
544 	if (!rep)
545 		chg_vc_kbd_led(kbd, VC_NUMLOCK);
546 }
547 
fn_lastcons(struct vc_data * vc)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 
fn_dec_console(struct vc_data * vc)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 
fn_inc_console(struct vc_data * vc)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 
fn_send_intr(struct vc_data * vc)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 
fn_scroll_forw(struct vc_data * vc)594 static void fn_scroll_forw(struct vc_data *vc)
595 {
596 	scrollfront(vc, 0);
597 }
598 
fn_scroll_back(struct vc_data * vc)599 static void fn_scroll_back(struct vc_data *vc)
600 {
601 	scrollback(vc);
602 }
603 
fn_show_mem(struct vc_data * vc)604 static void fn_show_mem(struct vc_data *vc)
605 {
606 	show_mem();
607 }
608 
fn_show_state(struct vc_data * vc)609 static void fn_show_state(struct vc_data *vc)
610 {
611 	show_state();
612 }
613 
fn_boot_it(struct vc_data * vc)614 static void fn_boot_it(struct vc_data *vc)
615 {
616 	ctrl_alt_del();
617 }
618 
fn_compose(struct vc_data * vc)619 static void fn_compose(struct vc_data *vc)
620 {
621 	dead_key_next = true;
622 }
623 
fn_spawn_con(struct vc_data * vc)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 
fn_SAK(struct vc_data * vc)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 
fn_null(struct vc_data * vc)640 static void fn_null(struct vc_data *vc)
641 {
642 	do_compute_shiftstate();
643 }
644 
645 /*
646  * Special key handlers
647  */
k_spec(struct vc_data * vc,unsigned char value,char up_flag)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 
k_lowercase(struct vc_data * vc,unsigned char value,char up_flag)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 
k_unicode(struct vc_data * vc,unsigned int value,char up_flag)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  */
k_deadunicode(struct vc_data * vc,unsigned int value,char up_flag)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 
k_self(struct vc_data * vc,unsigned char value,char up_flag)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 
k_dead2(struct vc_data * vc,unsigned char value,char up_flag)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  */
k_dead(struct vc_data * vc,unsigned char value,char up_flag)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 
k_cons(struct vc_data * vc,unsigned char value,char up_flag)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 
k_fn(struct vc_data * vc,unsigned char value,char up_flag)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  */
csi_modifier_param(void)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 
k_cur(struct vc_data * vc,unsigned char value,char up_flag)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 
k_pad(struct vc_data * vc,unsigned char value,char up_flag)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 
k_shift(struct vc_data * vc,unsigned char value,char up_flag)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 
k_meta(struct vc_data * vc,unsigned char value,char up_flag)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 
k_ascii(struct vc_data * vc,unsigned char value,char up_flag)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 
k_lock(struct vc_data * vc,unsigned char value,char up_flag)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 
k_slock(struct vc_data * vc,unsigned char value,char up_flag)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 
k_brlcommit(struct vc_data * vc,unsigned int pattern,char up_flag)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 
k_brl(struct vc_data * vc,unsigned char value,char up_flag)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  */
k_csi(struct vc_data * vc,unsigned char value,char up_flag)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 
kbd_led_trigger_activate(struct led_classdev * cdev)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 
kbd_propagate_led_state(unsigned int old_state,unsigned int new_state)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 
kbd_update_leds_helper(struct input_handle * handle,void * data)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 
kbd_init_leds(void)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 
kbd_update_leds_helper(struct input_handle * handle,void * data)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 
kbd_propagate_led_state(unsigned int old_state,unsigned int new_state)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 
kbd_init_leds(void)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  */
getledstate(void)1187 static unsigned char getledstate(void)
1188 {
1189 	return ledstate & 0xff;
1190 }
1191 
setledstate(struct kbd_struct * kb,unsigned int led)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 
getleds(void)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  */
vt_get_leds(unsigned int console,int flag)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  */
vt_set_led_state(unsigned int console,int leds)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  */
vt_kbd_con_start(unsigned int console)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  */
vt_kbd_con_stop(unsigned int console)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  */
kbd_bh(struct tasklet_struct * unused)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 
kbd_is_hw_raw(const struct input_dev * dev)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 
emulate_raw(struct vc_data * vc,unsigned int keycode,unsigned char up_flag)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 
kbd_is_hw_raw(const struct input_dev * dev)1405 static inline bool kbd_is_hw_raw(const struct input_dev *dev)
1406 {
1407 	return false;
1408 }
1409 
emulate_raw(struct vc_data * vc,unsigned int keycode,unsigned char up_flag)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 
kbd_rawcode(unsigned char data)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 
kbd_keycode(unsigned int keycode,int down,bool hw_raw)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 = tty_port_tty_get(&vc->port);
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 		tty_kref_put(tty);
1501 		return;
1502 	}
1503 
1504 	tty_kref_put(tty);
1505 
1506 	param.shift = shift_final = (shift_state | kbd->slockstate) ^ kbd->lockstate;
1507 	param.ledstate = kbd->ledflagstate;
1508 	key_map = key_maps[shift_final];
1509 
1510 	/*
1511 	 * Fall back to the plain map if modifiers are active, the modifier-
1512 	 * specific map is missing or has no entry, and the plain map has a
1513 	 * modifier-aware key type (KT_CUR or KT_CSI). These handlers encode
1514 	 * the modifier state into the emitted escape sequence.
1515 	 */
1516 	if (shift_final && keycode < NR_KEYS &&
1517 	    (!key_map || key_map[keycode] == K_HOLE) && key_maps[0]) {
1518 		unsigned short plain = key_maps[0][keycode];
1519 		unsigned char type = KTYP(plain);
1520 
1521 		if (type >= 0xf0 && (type - 0xf0 == KT_CUR || type - 0xf0 == KT_CSI))
1522 			key_map = key_maps[0];
1523 	}
1524 
1525 	rc = atomic_notifier_call_chain(&keyboard_notifier_list,
1526 					KBD_KEYCODE, &param);
1527 	if (rc == NOTIFY_STOP || !key_map) {
1528 		atomic_notifier_call_chain(&keyboard_notifier_list,
1529 					   KBD_UNBOUND_KEYCODE, &param);
1530 		do_compute_shiftstate();
1531 		kbd->slockstate = 0;
1532 		return;
1533 	}
1534 
1535 	if (keycode < NR_KEYS)
1536 		keysym = key_map[keycode];
1537 	else if (keycode >= KEY_BRL_DOT1 && keycode <= KEY_BRL_DOT8)
1538 		keysym = U(K(KT_BRL, keycode - KEY_BRL_DOT1 + 1));
1539 	else
1540 		return;
1541 
1542 	type = KTYP(keysym);
1543 
1544 	if (type < 0xf0) {
1545 		param.value = keysym;
1546 		rc = atomic_notifier_call_chain(&keyboard_notifier_list,
1547 						KBD_UNICODE, &param);
1548 		if (rc != NOTIFY_STOP)
1549 			if (down && !(raw_mode || kbd->kbdmode == VC_OFF))
1550 				k_unicode(vc, keysym, !down);
1551 		return;
1552 	}
1553 
1554 	type -= 0xf0;
1555 
1556 	if (type == KT_LETTER) {
1557 		type = KT_LATIN;
1558 		if (vc_kbd_led(kbd, VC_CAPSLOCK)) {
1559 			key_map = key_maps[shift_final ^ BIT(KG_SHIFT)];
1560 			if (key_map)
1561 				keysym = key_map[keycode];
1562 		}
1563 	}
1564 
1565 	param.value = keysym;
1566 	rc = atomic_notifier_call_chain(&keyboard_notifier_list,
1567 					KBD_KEYSYM, &param);
1568 	if (rc == NOTIFY_STOP)
1569 		return;
1570 
1571 	if ((raw_mode || kbd->kbdmode == VC_OFF) && type != KT_SPEC && type != KT_SHIFT)
1572 		return;
1573 
1574 	(*k_handler[type])(vc, KVAL(keysym), !down);
1575 
1576 	param.ledstate = kbd->ledflagstate;
1577 	atomic_notifier_call_chain(&keyboard_notifier_list, KBD_POST_KEYSYM, &param);
1578 
1579 	if (type != KT_SLOCK)
1580 		kbd->slockstate = 0;
1581 }
1582 
kbd_event(struct input_handle * handle,unsigned int event_type,unsigned int event_code,int value)1583 static void kbd_event(struct input_handle *handle, unsigned int event_type,
1584 		      unsigned int event_code, int value)
1585 {
1586 	/* We are called with interrupts disabled, just take the lock */
1587 	scoped_guard(spinlock, &kbd_event_lock) {
1588 		if (event_type == EV_MSC && event_code == MSC_RAW &&
1589 				kbd_is_hw_raw(handle->dev))
1590 			kbd_rawcode(value);
1591 		if (event_type == EV_KEY && event_code <= KEY_MAX)
1592 			kbd_keycode(event_code, value, kbd_is_hw_raw(handle->dev));
1593 	}
1594 
1595 	tasklet_schedule(&keyboard_tasklet);
1596 	do_poke_blanked_console = 1;
1597 	schedule_console_callback();
1598 }
1599 
kbd_match(struct input_handler * handler,struct input_dev * dev)1600 static bool kbd_match(struct input_handler *handler, struct input_dev *dev)
1601 {
1602 	if (test_bit(EV_SND, dev->evbit))
1603 		return true;
1604 
1605 	if (test_bit(EV_KEY, dev->evbit)) {
1606 		if (find_next_bit(dev->keybit, BTN_MISC, KEY_RESERVED) <
1607 				BTN_MISC)
1608 			return true;
1609 		if (find_next_bit(dev->keybit, KEY_BRL_DOT10 + 1,
1610 					KEY_BRL_DOT1) <= KEY_BRL_DOT10)
1611 			return true;
1612 	}
1613 
1614 	return false;
1615 }
1616 
1617 /*
1618  * When a keyboard (or other input device) is found, the kbd_connect
1619  * function is called. The function then looks at the device, and if it
1620  * likes it, it can open it and get events from it. In this (kbd_connect)
1621  * function, we should decide which VT to bind that keyboard to initially.
1622  */
kbd_connect(struct input_handler * handler,struct input_dev * dev,const struct input_device_id * id)1623 static int kbd_connect(struct input_handler *handler, struct input_dev *dev,
1624 			const struct input_device_id *id)
1625 {
1626 	int error;
1627 
1628 	struct input_handle __free(kfree) *handle = kzalloc_obj(*handle);
1629 	if (!handle)
1630 		return -ENOMEM;
1631 
1632 	handle->dev = dev;
1633 	handle->handler = handler;
1634 	handle->name = "kbd";
1635 
1636 	error = input_register_handle(handle);
1637 	if (error)
1638 		return error;
1639 
1640 	error = input_open_device(handle);
1641 	if (error)
1642 		goto err_unregister_handle;
1643 
1644 	retain_and_null_ptr(handle);
1645 
1646 	return 0;
1647 
1648  err_unregister_handle:
1649 	input_unregister_handle(handle);
1650 	return error;
1651 }
1652 
kbd_disconnect(struct input_handle * handle)1653 static void kbd_disconnect(struct input_handle *handle)
1654 {
1655 	input_close_device(handle);
1656 	input_unregister_handle(handle);
1657 	kfree(handle);
1658 }
1659 
1660 /*
1661  * Start keyboard handler on the new keyboard by refreshing LED state to
1662  * match the rest of the system.
1663  */
kbd_start(struct input_handle * handle)1664 static void kbd_start(struct input_handle *handle)
1665 {
1666 	tasklet_disable(&keyboard_tasklet);
1667 
1668 	if (ledstate != -1U)
1669 		kbd_update_leds_helper(handle, &ledstate);
1670 
1671 	tasklet_enable(&keyboard_tasklet);
1672 }
1673 
1674 static const struct input_device_id kbd_ids[] = {
1675 	{
1676 		.flags = INPUT_DEVICE_ID_MATCH_EVBIT,
1677 		.evbit = { BIT_MASK(EV_KEY) },
1678 	},
1679 
1680 	{
1681 		.flags = INPUT_DEVICE_ID_MATCH_EVBIT,
1682 		.evbit = { BIT_MASK(EV_SND) },
1683 	},
1684 
1685 	{ },    /* Terminating entry */
1686 };
1687 
1688 MODULE_DEVICE_TABLE(input, kbd_ids);
1689 
1690 static struct input_handler kbd_handler = {
1691 	.event		= kbd_event,
1692 	.match		= kbd_match,
1693 	.connect	= kbd_connect,
1694 	.disconnect	= kbd_disconnect,
1695 	.start		= kbd_start,
1696 	.name		= "kbd",
1697 	.id_table	= kbd_ids,
1698 };
1699 
kbd_init(void)1700 int __init kbd_init(void)
1701 {
1702 	int i;
1703 	int error;
1704 
1705 	for (i = 0; i < MAX_NR_CONSOLES; i++) {
1706 		kbd_table[i].ledflagstate = kbd_defleds();
1707 		kbd_table[i].default_ledflagstate = kbd_defleds();
1708 		kbd_table[i].ledmode = LED_SHOW_FLAGS;
1709 		kbd_table[i].lockstate = KBD_DEFLOCK;
1710 		kbd_table[i].slockstate = 0;
1711 		kbd_table[i].modeflags = KBD_DEFMODE;
1712 		kbd_table[i].kbdmode = default_utf8 ? VC_UNICODE : VC_XLATE;
1713 	}
1714 
1715 	kbd_init_leds();
1716 
1717 	error = input_register_handler(&kbd_handler);
1718 	if (error)
1719 		return error;
1720 
1721 	tasklet_enable(&keyboard_tasklet);
1722 	tasklet_schedule(&keyboard_tasklet);
1723 
1724 	return 0;
1725 }
1726 
1727 /* Ioctl support code */
1728 
vt_do_kdgkbdiacr(void __user * udp)1729 static int vt_do_kdgkbdiacr(void __user *udp)
1730 {
1731 	struct kbdiacrs __user *a = udp;
1732 	int i, asize;
1733 
1734 	struct kbdiacr __free(kfree) *dia = kmalloc_array(MAX_DIACR, sizeof(struct kbdiacr),
1735 							  GFP_KERNEL);
1736 	if (!dia)
1737 		return -ENOMEM;
1738 
1739 	/* Lock the diacriticals table, make a copy and then
1740 	   copy it after we unlock */
1741 	scoped_guard(spinlock_irqsave, &kbd_event_lock) {
1742 		asize = accent_table_size;
1743 		for (i = 0; i < asize; i++) {
1744 			dia[i].diacr = conv_uni_to_8bit(accent_table[i].diacr);
1745 			dia[i].base = conv_uni_to_8bit(accent_table[i].base);
1746 			dia[i].result = conv_uni_to_8bit(accent_table[i].result);
1747 		}
1748 	}
1749 
1750 	if (put_user(asize, &a->kb_cnt))
1751 		return -EFAULT;
1752 	if (copy_to_user(a->kbdiacr, dia, asize * sizeof(struct kbdiacr)))
1753 		return -EFAULT;
1754 	return 0;
1755 }
1756 
vt_do_kdgkbdiacruc(void __user * udp)1757 static int vt_do_kdgkbdiacruc(void __user *udp)
1758 {
1759 	struct kbdiacrsuc __user *a = udp;
1760 	int asize;
1761 
1762 	void __free(kfree) *buf = kmalloc_array(MAX_DIACR, sizeof(struct kbdiacruc),
1763 						GFP_KERNEL);
1764 	if (buf == NULL)
1765 		return -ENOMEM;
1766 
1767 	/* Lock the diacriticals table, make a copy and then
1768 	   copy it after we unlock */
1769 	scoped_guard(spinlock_irqsave, &kbd_event_lock) {
1770 		asize = accent_table_size;
1771 		memcpy(buf, accent_table, asize * sizeof(struct kbdiacruc));
1772 	}
1773 
1774 	if (put_user(asize, &a->kb_cnt))
1775 		return -EFAULT;
1776 	if (copy_to_user(a->kbdiacruc, buf, asize * sizeof(struct kbdiacruc)))
1777 		return -EFAULT;
1778 
1779 	return 0;
1780 }
1781 
vt_do_kdskbdiacr(void __user * udp,int perm)1782 static int vt_do_kdskbdiacr(void __user *udp, int perm)
1783 {
1784 	struct kbdiacrs __user *a = udp;
1785 	struct kbdiacr __free(kfree) *dia = NULL;
1786 	unsigned int ct;
1787 	int i;
1788 
1789 	if (!perm)
1790 		return -EPERM;
1791 	if (get_user(ct, &a->kb_cnt))
1792 		return -EFAULT;
1793 	if (ct >= MAX_DIACR)
1794 		return -EINVAL;
1795 
1796 	if (ct) {
1797 		dia = memdup_array_user(a->kbdiacr,
1798 					ct, sizeof(struct kbdiacr));
1799 		if (IS_ERR(dia))
1800 			return PTR_ERR(dia);
1801 	}
1802 
1803 	guard(spinlock_irqsave)(&kbd_event_lock);
1804 	accent_table_size = ct;
1805 	for (i = 0; i < ct; i++) {
1806 		accent_table[i].diacr =
1807 				conv_8bit_to_uni(dia[i].diacr);
1808 		accent_table[i].base =
1809 				conv_8bit_to_uni(dia[i].base);
1810 		accent_table[i].result =
1811 				conv_8bit_to_uni(dia[i].result);
1812 	}
1813 
1814 	return 0;
1815 }
1816 
vt_do_kdskbdiacruc(void __user * udp,int perm)1817 static int vt_do_kdskbdiacruc(void __user *udp, int perm)
1818 {
1819 	struct kbdiacrsuc __user *a = udp;
1820 	unsigned int ct;
1821 	void __free(kfree) *buf = NULL;
1822 
1823 	if (!perm)
1824 		return -EPERM;
1825 
1826 	if (get_user(ct, &a->kb_cnt))
1827 		return -EFAULT;
1828 
1829 	if (ct >= MAX_DIACR)
1830 		return -EINVAL;
1831 
1832 	if (ct) {
1833 		buf = memdup_array_user(a->kbdiacruc,
1834 					ct, sizeof(struct kbdiacruc));
1835 		if (IS_ERR(buf))
1836 			return PTR_ERR(buf);
1837 	}
1838 	guard(spinlock_irqsave)(&kbd_event_lock);
1839 	if (ct)
1840 		memcpy(accent_table, buf,
1841 				ct * sizeof(struct kbdiacruc));
1842 	accent_table_size = ct;
1843 	return 0;
1844 }
1845 
1846 /**
1847  *	vt_do_diacrit		-	diacritical table updates
1848  *	@cmd: ioctl request
1849  *	@udp: pointer to user data for ioctl
1850  *	@perm: permissions check computed by caller
1851  *
1852  *	Update the diacritical tables atomically and safely. Lock them
1853  *	against simultaneous keypresses
1854  */
vt_do_diacrit(unsigned int cmd,void __user * udp,int perm)1855 int vt_do_diacrit(unsigned int cmd, void __user *udp, int perm)
1856 {
1857 	switch (cmd) {
1858 	case KDGKBDIACR:
1859 		return vt_do_kdgkbdiacr(udp);
1860 	case KDGKBDIACRUC:
1861 		return vt_do_kdgkbdiacruc(udp);
1862 	case KDSKBDIACR:
1863 		return vt_do_kdskbdiacr(udp, perm);
1864 	case KDSKBDIACRUC:
1865 		return vt_do_kdskbdiacruc(udp, perm);
1866 	}
1867 	return 0;
1868 }
1869 
1870 /**
1871  *	vt_do_kdskbmode		-	set keyboard mode ioctl
1872  *	@console: the console to use
1873  *	@arg: the requested mode
1874  *
1875  *	Update the keyboard mode bits while holding the correct locks.
1876  *	Return 0 for success or an error code.
1877  */
vt_do_kdskbmode(unsigned int console,unsigned int arg)1878 int vt_do_kdskbmode(unsigned int console, unsigned int arg)
1879 {
1880 	struct kbd_struct *kb = &kbd_table[console];
1881 
1882 	guard(spinlock_irqsave)(&kbd_event_lock);
1883 	switch(arg) {
1884 	case K_RAW:
1885 		kb->kbdmode = VC_RAW;
1886 		return 0;
1887 	case K_MEDIUMRAW:
1888 		kb->kbdmode = VC_MEDIUMRAW;
1889 		return 0;
1890 	case K_XLATE:
1891 		kb->kbdmode = VC_XLATE;
1892 		do_compute_shiftstate();
1893 		return 0;
1894 	case K_UNICODE:
1895 		kb->kbdmode = VC_UNICODE;
1896 		do_compute_shiftstate();
1897 		return 0;
1898 	case K_OFF:
1899 		kb->kbdmode = VC_OFF;
1900 		return 0;
1901 	default:
1902 		return -EINVAL;
1903 	}
1904 }
1905 
1906 /**
1907  *	vt_do_kdskbmeta		-	set keyboard meta state
1908  *	@console: the console to use
1909  *	@arg: the requested meta state
1910  *
1911  *	Update the keyboard meta bits while holding the correct locks.
1912  *	Return 0 for success or an error code.
1913  */
vt_do_kdskbmeta(unsigned int console,unsigned int arg)1914 int vt_do_kdskbmeta(unsigned int console, unsigned int arg)
1915 {
1916 	struct kbd_struct *kb = &kbd_table[console];
1917 
1918 	guard(spinlock_irqsave)(&kbd_event_lock);
1919 	switch(arg) {
1920 	case K_METABIT:
1921 		clr_vc_kbd_mode(kb, VC_META);
1922 		return 0;
1923 	case K_ESCPREFIX:
1924 		set_vc_kbd_mode(kb, VC_META);
1925 		return 0;
1926 	default:
1927 		return -EINVAL;
1928 	}
1929 }
1930 
vt_do_kbkeycode_ioctl(int cmd,struct kbkeycode __user * user_kbkc,int perm)1931 int vt_do_kbkeycode_ioctl(int cmd, struct kbkeycode __user *user_kbkc, int perm)
1932 {
1933 	struct kbkeycode tmp;
1934 	int kc;
1935 
1936 	if (copy_from_user(&tmp, user_kbkc, sizeof(struct kbkeycode)))
1937 		return -EFAULT;
1938 
1939 	switch (cmd) {
1940 	case KDGETKEYCODE:
1941 		kc = getkeycode(tmp.scancode);
1942 		if (kc < 0)
1943 			return kc;
1944 		return put_user(kc, &user_kbkc->keycode);
1945 	case KDSETKEYCODE:
1946 		if (!perm)
1947 			return -EPERM;
1948 		return setkeycode(tmp.scancode, tmp.keycode);
1949 	}
1950 
1951 	return 0;
1952 }
1953 
vt_kdgkbent(unsigned char kbdmode,unsigned char idx,unsigned char map)1954 static unsigned short vt_kdgkbent(unsigned char kbdmode, unsigned char idx,
1955 		unsigned char map)
1956 {
1957 	unsigned short *key_map;
1958 
1959 	/* Ensure another thread doesn't free it under us */
1960 	guard(spinlock_irqsave)(&kbd_event_lock);
1961 	key_map = key_maps[map];
1962 	if (key_map) {
1963 		unsigned short val = U(key_map[idx]);
1964 		if (kbdmode != VC_UNICODE && KTYP(val) >= NR_TYPES)
1965 			return K_HOLE;
1966 		return val;
1967 	}
1968 
1969 	return idx ? K_HOLE : K_NOSUCHMAP;
1970 }
1971 
vt_kdskbent(unsigned char kbdmode,unsigned char idx,unsigned char map,unsigned short val)1972 static int vt_kdskbent(unsigned char kbdmode, unsigned char idx,
1973 		unsigned char map, unsigned short val)
1974 {
1975 	unsigned short *key_map, oldval;
1976 
1977 	if (!idx && val == K_NOSUCHMAP) {
1978 		guard(spinlock_irqsave)(&kbd_event_lock);
1979 		/* deallocate map */
1980 		key_map = key_maps[map];
1981 		if (map && key_map) {
1982 			key_maps[map] = NULL;
1983 			if (key_map[0] == U(K_ALLOCATED)) {
1984 				kfree(key_map);
1985 				keymap_count--;
1986 			}
1987 		}
1988 
1989 		return 0;
1990 	}
1991 
1992 	if (KTYP(val) < NR_TYPES) {
1993 		if (KVAL(val) > max_vals[KTYP(val)])
1994 			return -EINVAL;
1995 	} else if (kbdmode != VC_UNICODE)
1996 		return -EINVAL;
1997 
1998 	/* ++Geert: non-PC keyboards may generate keycode zero */
1999 #if !defined(__mc68000__) && !defined(__powerpc__)
2000 	/* assignment to entry 0 only tests validity of args */
2001 	if (!idx)
2002 		return 0;
2003 #endif
2004 
2005 	unsigned short __free(kfree) *new_map = kmalloc(sizeof(plain_map), GFP_KERNEL);
2006 	if (!new_map)
2007 		return -ENOMEM;
2008 
2009 	guard(spinlock_irqsave)(&kbd_event_lock);
2010 	key_map = key_maps[map];
2011 	if (key_map == NULL) {
2012 		int j;
2013 
2014 		if (keymap_count >= MAX_NR_OF_USER_KEYMAPS && !capable(CAP_SYS_RESOURCE))
2015 			return -EPERM;
2016 
2017 		key_map = key_maps[map] = no_free_ptr(new_map);
2018 		key_map[0] = U(K_ALLOCATED);
2019 		for (j = 1; j < NR_KEYS; j++)
2020 			key_map[j] = U(K_HOLE);
2021 		keymap_count++;
2022 	}
2023 
2024 	oldval = U(key_map[idx]);
2025 	if (val == oldval)
2026 		return 0;
2027 
2028 	/* Attention Key */
2029 	if ((oldval == K_SAK || val == K_SAK) && !capable(CAP_SYS_ADMIN))
2030 		return -EPERM;
2031 
2032 	key_map[idx] = U(val);
2033 	if (!map && (KTYP(oldval) == KT_SHIFT || KTYP(val) == KT_SHIFT))
2034 		do_compute_shiftstate();
2035 
2036 	return 0;
2037 }
2038 
vt_do_kdsk_ioctl(int cmd,struct kbentry __user * user_kbe,int perm,unsigned int console)2039 int vt_do_kdsk_ioctl(int cmd, struct kbentry __user *user_kbe, int perm,
2040 						unsigned int console)
2041 {
2042 	struct kbd_struct *kb = &kbd_table[console];
2043 	struct kbentry kbe;
2044 
2045 	if (copy_from_user(&kbe, user_kbe, sizeof(struct kbentry)))
2046 		return -EFAULT;
2047 
2048 	switch (cmd) {
2049 	case KDGKBENT:
2050 		return put_user(vt_kdgkbent(kb->kbdmode, kbe.kb_index,
2051 					kbe.kb_table),
2052 				&user_kbe->kb_value);
2053 	case KDSKBENT:
2054 		if (!perm || !capable(CAP_SYS_TTY_CONFIG))
2055 			return -EPERM;
2056 		return vt_kdskbent(kb->kbdmode, kbe.kb_index, kbe.kb_table,
2057 				kbe.kb_value);
2058 	}
2059 	return 0;
2060 }
2061 
vt_kdskbsent(char * kbs,unsigned char cur)2062 static char *vt_kdskbsent(char *kbs, unsigned char cur)
2063 {
2064 	static DECLARE_BITMAP(is_kmalloc, MAX_NR_FUNC);
2065 	char *cur_f = func_table[cur];
2066 
2067 	if (cur_f && strlen(cur_f) >= strlen(kbs)) {
2068 		strcpy(cur_f, kbs);
2069 		return kbs;
2070 	}
2071 
2072 	func_table[cur] = kbs;
2073 
2074 	return __test_and_set_bit(cur, is_kmalloc) ? cur_f : NULL;
2075 }
2076 
vt_do_kdgkb_ioctl(int cmd,struct kbsentry __user * user_kdgkb,int perm)2077 int vt_do_kdgkb_ioctl(int cmd, struct kbsentry __user *user_kdgkb, int perm)
2078 {
2079 	unsigned char kb_func;
2080 
2081 	if (get_user(kb_func, &user_kdgkb->kb_func))
2082 		return -EFAULT;
2083 
2084 	kb_func = array_index_nospec(kb_func, MAX_NR_FUNC);
2085 
2086 	switch (cmd) {
2087 	case KDGKBSENT: {
2088 		/* size should have been a struct member */
2089 		ssize_t len = sizeof(user_kdgkb->kb_string);
2090 
2091 		char __free(kfree) *kbs = kmalloc(len, GFP_KERNEL);
2092 		if (!kbs)
2093 			return -ENOMEM;
2094 
2095 		scoped_guard(spinlock_irqsave, &func_buf_lock)
2096 			len = strscpy(kbs, func_table[kb_func] ? : "", len);
2097 
2098 		if (len < 0)
2099 			return -ENOSPC;
2100 
2101 		if (copy_to_user(user_kdgkb->kb_string, kbs, len + 1))
2102 			return -EFAULT;
2103 
2104 		return 0;
2105 	}
2106 	case KDSKBSENT:
2107 		if (!perm || !capable(CAP_SYS_TTY_CONFIG))
2108 			return -EPERM;
2109 
2110 		char __free(kfree) *kbs = strndup_user(user_kdgkb->kb_string,
2111 						       sizeof(user_kdgkb->kb_string));
2112 		if (IS_ERR(kbs))
2113 			return PTR_ERR(kbs);
2114 
2115 		guard(spinlock_irqsave)(&func_buf_lock);
2116 		kbs = vt_kdskbsent(kbs, kb_func);
2117 
2118 		return 0;
2119 	}
2120 
2121 	return 0;
2122 }
2123 
vt_do_kdskled(unsigned int console,int cmd,unsigned long arg,int perm)2124 int vt_do_kdskled(unsigned int console, int cmd, unsigned long arg, int perm)
2125 {
2126 	struct kbd_struct *kb = &kbd_table[console];
2127 	unsigned char ucval;
2128 
2129         switch(cmd) {
2130 	/* the ioctls below read/set the flags usually shown in the leds */
2131 	/* don't use them - they will go away without warning */
2132 	case KDGKBLED:
2133 		scoped_guard(spinlock_irqsave, &kbd_event_lock)
2134 			ucval = kb->ledflagstate | (kb->default_ledflagstate << 4);
2135 		return put_user(ucval, (char __user *)arg);
2136 
2137 	case KDSKBLED:
2138 		if (!perm)
2139 			return -EPERM;
2140 		if (arg & ~0x77)
2141 			return -EINVAL;
2142 		scoped_guard(spinlock_irqsave, &led_lock) {
2143 			kb->ledflagstate = (arg & 7);
2144 			kb->default_ledflagstate = ((arg >> 4) & 7);
2145 			set_leds();
2146 		}
2147 		return 0;
2148 
2149 	/* the ioctls below only set the lights, not the functions */
2150 	/* for those, see KDGKBLED and KDSKBLED above */
2151 	case KDGETLED:
2152 		ucval = getledstate();
2153 		return put_user(ucval, (char __user *)arg);
2154 
2155 	case KDSETLED:
2156 		if (!perm)
2157 			return -EPERM;
2158 		setledstate(kb, arg);
2159 		return 0;
2160         }
2161         return -ENOIOCTLCMD;
2162 }
2163 
vt_do_kdgkbmode(unsigned int console)2164 int vt_do_kdgkbmode(unsigned int console)
2165 {
2166 	struct kbd_struct *kb = &kbd_table[console];
2167 	/* This is a spot read so needs no locking */
2168 	switch (kb->kbdmode) {
2169 	case VC_RAW:
2170 		return K_RAW;
2171 	case VC_MEDIUMRAW:
2172 		return K_MEDIUMRAW;
2173 	case VC_UNICODE:
2174 		return K_UNICODE;
2175 	case VC_OFF:
2176 		return K_OFF;
2177 	default:
2178 		return K_XLATE;
2179 	}
2180 }
2181 
2182 /**
2183  *	vt_do_kdgkbmeta		-	report meta status
2184  *	@console: console to report
2185  *
2186  *	Report the meta flag status of this console
2187  */
vt_do_kdgkbmeta(unsigned int console)2188 int vt_do_kdgkbmeta(unsigned int console)
2189 {
2190 	struct kbd_struct *kb = &kbd_table[console];
2191         /* Again a spot read so no locking */
2192 	return vc_kbd_mode(kb, VC_META) ? K_ESCPREFIX : K_METABIT;
2193 }
2194 
2195 /**
2196  *	vt_reset_unicode	-	reset the unicode status
2197  *	@console: console being reset
2198  *
2199  *	Restore the unicode console state to its default
2200  */
vt_reset_unicode(unsigned int console)2201 void vt_reset_unicode(unsigned int console)
2202 {
2203 	guard(spinlock_irqsave)(&kbd_event_lock);
2204 	kbd_table[console].kbdmode = default_utf8 ? VC_UNICODE : VC_XLATE;
2205 }
2206 
2207 /**
2208  *	vt_get_shift_state	-	shift bit state
2209  *
2210  *	Report the shift bits from the keyboard state. We have to export
2211  *	this to support some oddities in the vt layer.
2212  */
vt_get_shift_state(void)2213 int vt_get_shift_state(void)
2214 {
2215         /* Don't lock as this is a transient report */
2216         return shift_state;
2217 }
2218 
2219 /**
2220  *	vt_reset_keyboard	-	reset keyboard state
2221  *	@console: console to reset
2222  *
2223  *	Reset the keyboard bits for a console as part of a general console
2224  *	reset event
2225  */
vt_reset_keyboard(unsigned int console)2226 void vt_reset_keyboard(unsigned int console)
2227 {
2228 	struct kbd_struct *kb = &kbd_table[console];
2229 
2230 	guard(spinlock_irqsave)(&kbd_event_lock);
2231 	set_vc_kbd_mode(kb, VC_REPEAT);
2232 	clr_vc_kbd_mode(kb, VC_CKMODE);
2233 	clr_vc_kbd_mode(kb, VC_APPLIC);
2234 	clr_vc_kbd_mode(kb, VC_CRLF);
2235 	kb->lockstate = 0;
2236 	kb->slockstate = 0;
2237 	guard(spinlock)(&led_lock);
2238 	kb->ledmode = LED_SHOW_FLAGS;
2239 	kb->ledflagstate = kb->default_ledflagstate;
2240 	/* do not do set_leds here because this causes an endless tasklet loop
2241 	   when the keyboard hasn't been initialized yet */
2242 }
2243 
2244 /**
2245  *	vt_get_kbd_mode_bit	-	read keyboard status bits
2246  *	@console: console to read from
2247  *	@bit: mode bit to read
2248  *
2249  *	Report back a vt mode bit. We do this without locking so the
2250  *	caller must be sure that there are no synchronization needs
2251  */
2252 
vt_get_kbd_mode_bit(unsigned int console,int bit)2253 int vt_get_kbd_mode_bit(unsigned int console, int bit)
2254 {
2255 	struct kbd_struct *kb = &kbd_table[console];
2256 	return vc_kbd_mode(kb, bit);
2257 }
2258 
2259 /**
2260  *	vt_set_kbd_mode_bit	-	read keyboard status bits
2261  *	@console: console to read from
2262  *	@bit: mode bit to read
2263  *
2264  *	Set a vt mode bit. We do this without locking so the
2265  *	caller must be sure that there are no synchronization needs
2266  */
2267 
vt_set_kbd_mode_bit(unsigned int console,int bit)2268 void vt_set_kbd_mode_bit(unsigned int console, int bit)
2269 {
2270 	struct kbd_struct *kb = &kbd_table[console];
2271 
2272 	guard(spinlock_irqsave)(&kbd_event_lock);
2273 	set_vc_kbd_mode(kb, bit);
2274 }
2275 
2276 /**
2277  *	vt_clr_kbd_mode_bit	-	read keyboard status bits
2278  *	@console: console to read from
2279  *	@bit: mode bit to read
2280  *
2281  *	Report back a vt mode bit. We do this without locking so the
2282  *	caller must be sure that there are no synchronization needs
2283  */
2284 
vt_clr_kbd_mode_bit(unsigned int console,int bit)2285 void vt_clr_kbd_mode_bit(unsigned int console, int bit)
2286 {
2287 	struct kbd_struct *kb = &kbd_table[console];
2288 
2289 	guard(spinlock_irqsave)(&kbd_event_lock);
2290 	clr_vc_kbd_mode(kb, bit);
2291 }
2292