• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *	Linux Magic System Request Key Hacks
4  *
5  *	(c) 1997 Martin Mares <mj@atrey.karlin.mff.cuni.cz>
6  *	based on ideas by Pavel Machek <pavel@atrey.karlin.mff.cuni.cz>
7  *
8  *	(c) 2000 Crutcher Dunnavant <crutcher+kernel@datastacks.com>
9  *	overhauled to use key registration
10  *	based upon discusions in irc://irc.openprojects.net/#kernelnewbies
11  *
12  *	Copyright (c) 2010 Dmitry Torokhov
13  *	Input handler conversion
14  */
15 
16 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
17 
18 #include <linux/sched/signal.h>
19 #include <linux/sched/rt.h>
20 #include <linux/sched/debug.h>
21 #include <linux/sched/task.h>
22 #include <linux/ctype.h>
23 #include <linux/interrupt.h>
24 #include <linux/mm.h>
25 #include <linux/fs.h>
26 #include <linux/mount.h>
27 #include <linux/kdev_t.h>
28 #include <linux/major.h>
29 #include <linux/reboot.h>
30 #include <linux/sysrq.h>
31 #include <linux/kbd_kern.h>
32 #include <linux/proc_fs.h>
33 #include <linux/nmi.h>
34 #include <linux/quotaops.h>
35 #include <linux/perf_event.h>
36 #include <linux/kernel.h>
37 #include <linux/module.h>
38 #include <linux/suspend.h>
39 #include <linux/writeback.h>
40 #include <linux/swap.h>
41 #include <linux/spinlock.h>
42 #include <linux/vt_kern.h>
43 #include <linux/workqueue.h>
44 #include <linux/hrtimer.h>
45 #include <linux/oom.h>
46 #include <linux/slab.h>
47 #include <linux/input.h>
48 #include <linux/uaccess.h>
49 #include <linux/moduleparam.h>
50 #include <linux/jiffies.h>
51 #include <linux/syscalls.h>
52 #include <linux/of.h>
53 #include <linux/rcupdate.h>
54 
55 #include <asm/ptrace.h>
56 #include <asm/irq_regs.h>
57 
58 #include <trace/hooks/sysrqcrash.h>
59 
60 /* Whether we react on sysrq keys or just ignore them */
61 static int __read_mostly sysrq_enabled = CONFIG_MAGIC_SYSRQ_DEFAULT_ENABLE;
62 static bool __read_mostly sysrq_always_enabled;
63 
sysrq_on(void)64 static bool sysrq_on(void)
65 {
66 	return sysrq_enabled || sysrq_always_enabled;
67 }
68 
69 /**
70  * sysrq_mask - Getter for sysrq_enabled mask.
71  *
72  * Return: 1 if sysrq is always enabled, enabled sysrq_key_op mask otherwise.
73  */
sysrq_mask(void)74 int sysrq_mask(void)
75 {
76 	if (sysrq_always_enabled)
77 		return 1;
78 	return sysrq_enabled;
79 }
80 EXPORT_SYMBOL_GPL(sysrq_mask);
81 
82 /*
83  * A value of 1 means 'all', other nonzero values are an op mask:
84  */
sysrq_on_mask(int mask)85 static bool sysrq_on_mask(int mask)
86 {
87 	return sysrq_always_enabled ||
88 	       sysrq_enabled == 1 ||
89 	       (sysrq_enabled & mask);
90 }
91 
sysrq_always_enabled_setup(char * str)92 static int __init sysrq_always_enabled_setup(char *str)
93 {
94 	sysrq_always_enabled = true;
95 	pr_info("sysrq always enabled.\n");
96 
97 	return 1;
98 }
99 
100 __setup("sysrq_always_enabled", sysrq_always_enabled_setup);
101 
102 
sysrq_handle_loglevel(int key)103 static void sysrq_handle_loglevel(int key)
104 {
105 	int i;
106 
107 	i = key - '0';
108 	console_loglevel = CONSOLE_LOGLEVEL_DEFAULT;
109 	pr_info("Loglevel set to %d\n", i);
110 	console_loglevel = i;
111 }
112 static const struct sysrq_key_op sysrq_loglevel_op = {
113 	.handler	= sysrq_handle_loglevel,
114 	.help_msg	= "loglevel(0-9)",
115 	.action_msg	= "Changing Loglevel",
116 	.enable_mask	= SYSRQ_ENABLE_LOG,
117 };
118 
119 #ifdef CONFIG_VT
sysrq_handle_SAK(int key)120 static void sysrq_handle_SAK(int key)
121 {
122 	struct work_struct *SAK_work = &vc_cons[fg_console].SAK_work;
123 
124 	schedule_work(SAK_work);
125 }
126 static const struct sysrq_key_op sysrq_SAK_op = {
127 	.handler	= sysrq_handle_SAK,
128 	.help_msg	= "sak(k)",
129 	.action_msg	= "SAK",
130 	.enable_mask	= SYSRQ_ENABLE_KEYBOARD,
131 };
132 #else
133 #define sysrq_SAK_op (*(const struct sysrq_key_op *)NULL)
134 #endif
135 
136 #ifdef CONFIG_VT
sysrq_handle_unraw(int key)137 static void sysrq_handle_unraw(int key)
138 {
139 	vt_reset_unicode(fg_console);
140 }
141 
142 static const struct sysrq_key_op sysrq_unraw_op = {
143 	.handler	= sysrq_handle_unraw,
144 	.help_msg	= "unraw(r)",
145 	.action_msg	= "Keyboard mode set to system default",
146 	.enable_mask	= SYSRQ_ENABLE_KEYBOARD,
147 };
148 #else
149 #define sysrq_unraw_op (*(const struct sysrq_key_op *)NULL)
150 #endif /* CONFIG_VT */
151 
sysrq_handle_crash(int key)152 static void sysrq_handle_crash(int key)
153 {
154 	/* release the RCU read lock before crashing */
155 	rcu_read_unlock();
156 
157 	trace_android_vh_sysrq_crash(current);
158 
159 	panic("sysrq triggered crash\n");
160 }
161 static const struct sysrq_key_op sysrq_crash_op = {
162 	.handler	= sysrq_handle_crash,
163 	.help_msg	= "crash(c)",
164 	.action_msg	= "Trigger a crash",
165 	.enable_mask	= SYSRQ_ENABLE_DUMP,
166 };
167 
sysrq_handle_reboot(int key)168 static void sysrq_handle_reboot(int key)
169 {
170 	lockdep_off();
171 	local_irq_enable();
172 	emergency_restart();
173 }
174 static const struct sysrq_key_op sysrq_reboot_op = {
175 	.handler	= sysrq_handle_reboot,
176 	.help_msg	= "reboot(b)",
177 	.action_msg	= "Resetting",
178 	.enable_mask	= SYSRQ_ENABLE_BOOT,
179 };
180 
181 const struct sysrq_key_op *__sysrq_reboot_op = &sysrq_reboot_op;
182 
sysrq_handle_sync(int key)183 static void sysrq_handle_sync(int key)
184 {
185 	emergency_sync();
186 }
187 static const struct sysrq_key_op sysrq_sync_op = {
188 	.handler	= sysrq_handle_sync,
189 	.help_msg	= "sync(s)",
190 	.action_msg	= "Emergency Sync",
191 	.enable_mask	= SYSRQ_ENABLE_SYNC,
192 };
193 
sysrq_handle_show_timers(int key)194 static void sysrq_handle_show_timers(int key)
195 {
196 	sysrq_timer_list_show();
197 }
198 
199 static const struct sysrq_key_op sysrq_show_timers_op = {
200 	.handler	= sysrq_handle_show_timers,
201 	.help_msg	= "show-all-timers(q)",
202 	.action_msg	= "Show clockevent devices & pending hrtimers (no others)",
203 };
204 
sysrq_handle_mountro(int key)205 static void sysrq_handle_mountro(int key)
206 {
207 	emergency_remount();
208 }
209 static const struct sysrq_key_op sysrq_mountro_op = {
210 	.handler	= sysrq_handle_mountro,
211 	.help_msg	= "unmount(u)",
212 	.action_msg	= "Emergency Remount R/O",
213 	.enable_mask	= SYSRQ_ENABLE_REMOUNT,
214 };
215 
216 #ifdef CONFIG_LOCKDEP
sysrq_handle_showlocks(int key)217 static void sysrq_handle_showlocks(int key)
218 {
219 	debug_show_all_locks();
220 }
221 
222 static const struct sysrq_key_op sysrq_showlocks_op = {
223 	.handler	= sysrq_handle_showlocks,
224 	.help_msg	= "show-all-locks(d)",
225 	.action_msg	= "Show Locks Held",
226 };
227 #else
228 #define sysrq_showlocks_op (*(const struct sysrq_key_op *)NULL)
229 #endif
230 
231 #ifdef CONFIG_SMP
232 static DEFINE_RAW_SPINLOCK(show_lock);
233 
showacpu(void * dummy)234 static void showacpu(void *dummy)
235 {
236 	unsigned long flags;
237 
238 	/* Idle CPUs have no interesting backtrace. */
239 	if (idle_cpu(smp_processor_id())) {
240 		pr_info("CPU%d: backtrace skipped as idling\n", smp_processor_id());
241 		return;
242 	}
243 
244 	raw_spin_lock_irqsave(&show_lock, flags);
245 	pr_info("CPU%d:\n", smp_processor_id());
246 	show_stack(NULL, NULL, KERN_INFO);
247 	raw_spin_unlock_irqrestore(&show_lock, flags);
248 }
249 
sysrq_showregs_othercpus(struct work_struct * dummy)250 static void sysrq_showregs_othercpus(struct work_struct *dummy)
251 {
252 	smp_call_function(showacpu, NULL, 0);
253 }
254 
255 static DECLARE_WORK(sysrq_showallcpus, sysrq_showregs_othercpus);
256 
sysrq_handle_showallcpus(int key)257 static void sysrq_handle_showallcpus(int key)
258 {
259 	/*
260 	 * Fall back to the workqueue based printing if the
261 	 * backtrace printing did not succeed or the
262 	 * architecture has no support for it:
263 	 */
264 	if (!trigger_all_cpu_backtrace()) {
265 		struct pt_regs *regs = NULL;
266 
267 		if (in_hardirq())
268 			regs = get_irq_regs();
269 
270 		pr_info("CPU%d:\n", get_cpu());
271 		if (regs)
272 			show_regs(regs);
273 		else
274 			show_stack(NULL, NULL, KERN_INFO);
275 
276 		schedule_work(&sysrq_showallcpus);
277 		put_cpu();
278 	}
279 }
280 
281 static const struct sysrq_key_op sysrq_showallcpus_op = {
282 	.handler	= sysrq_handle_showallcpus,
283 	.help_msg	= "show-backtrace-all-active-cpus(l)",
284 	.action_msg	= "Show backtrace of all active CPUs",
285 	.enable_mask	= SYSRQ_ENABLE_DUMP,
286 };
287 #endif
288 
sysrq_handle_showregs(int key)289 static void sysrq_handle_showregs(int key)
290 {
291 	struct pt_regs *regs = NULL;
292 
293 	if (in_hardirq())
294 		regs = get_irq_regs();
295 	if (regs)
296 		show_regs(regs);
297 	perf_event_print_debug();
298 }
299 static const struct sysrq_key_op sysrq_showregs_op = {
300 	.handler	= sysrq_handle_showregs,
301 	.help_msg	= "show-registers(p)",
302 	.action_msg	= "Show Regs",
303 	.enable_mask	= SYSRQ_ENABLE_DUMP,
304 };
305 
sysrq_handle_showstate(int key)306 static void sysrq_handle_showstate(int key)
307 {
308 	show_state();
309 	show_all_workqueues();
310 }
311 static const struct sysrq_key_op sysrq_showstate_op = {
312 	.handler	= sysrq_handle_showstate,
313 	.help_msg	= "show-task-states(t)",
314 	.action_msg	= "Show State",
315 	.enable_mask	= SYSRQ_ENABLE_DUMP,
316 };
317 
sysrq_handle_showstate_blocked(int key)318 static void sysrq_handle_showstate_blocked(int key)
319 {
320 	show_state_filter(TASK_UNINTERRUPTIBLE);
321 }
322 static const struct sysrq_key_op sysrq_showstate_blocked_op = {
323 	.handler	= sysrq_handle_showstate_blocked,
324 	.help_msg	= "show-blocked-tasks(w)",
325 	.action_msg	= "Show Blocked State",
326 	.enable_mask	= SYSRQ_ENABLE_DUMP,
327 };
328 
329 #ifdef CONFIG_TRACING
330 #include <linux/ftrace.h>
331 
sysrq_ftrace_dump(int key)332 static void sysrq_ftrace_dump(int key)
333 {
334 	ftrace_dump(DUMP_ALL);
335 }
336 static const struct sysrq_key_op sysrq_ftrace_dump_op = {
337 	.handler	= sysrq_ftrace_dump,
338 	.help_msg	= "dump-ftrace-buffer(z)",
339 	.action_msg	= "Dump ftrace buffer",
340 	.enable_mask	= SYSRQ_ENABLE_DUMP,
341 };
342 #else
343 #define sysrq_ftrace_dump_op (*(const struct sysrq_key_op *)NULL)
344 #endif
345 
sysrq_handle_showmem(int key)346 static void sysrq_handle_showmem(int key)
347 {
348 	show_mem(0, NULL);
349 }
350 static const struct sysrq_key_op sysrq_showmem_op = {
351 	.handler	= sysrq_handle_showmem,
352 	.help_msg	= "show-memory-usage(m)",
353 	.action_msg	= "Show Memory",
354 	.enable_mask	= SYSRQ_ENABLE_DUMP,
355 };
356 
357 /*
358  * Signal sysrq helper function.  Sends a signal to all user processes.
359  */
send_sig_all(int sig)360 static void send_sig_all(int sig)
361 {
362 	struct task_struct *p;
363 
364 	read_lock(&tasklist_lock);
365 	for_each_process(p) {
366 		if (p->flags & PF_KTHREAD)
367 			continue;
368 		if (is_global_init(p))
369 			continue;
370 
371 		do_send_sig_info(sig, SEND_SIG_PRIV, p, PIDTYPE_MAX);
372 	}
373 	read_unlock(&tasklist_lock);
374 }
375 
sysrq_handle_term(int key)376 static void sysrq_handle_term(int key)
377 {
378 	send_sig_all(SIGTERM);
379 	console_loglevel = CONSOLE_LOGLEVEL_DEBUG;
380 }
381 static const struct sysrq_key_op sysrq_term_op = {
382 	.handler	= sysrq_handle_term,
383 	.help_msg	= "terminate-all-tasks(e)",
384 	.action_msg	= "Terminate All Tasks",
385 	.enable_mask	= SYSRQ_ENABLE_SIGNAL,
386 };
387 
moom_callback(struct work_struct * ignored)388 static void moom_callback(struct work_struct *ignored)
389 {
390 	const gfp_t gfp_mask = GFP_KERNEL;
391 	struct oom_control oc = {
392 		.zonelist = node_zonelist(first_memory_node, gfp_mask),
393 		.nodemask = NULL,
394 		.memcg = NULL,
395 		.gfp_mask = gfp_mask,
396 		.order = -1,
397 	};
398 
399 	mutex_lock(&oom_lock);
400 	if (!out_of_memory(&oc))
401 		pr_info("OOM request ignored. No task eligible\n");
402 	mutex_unlock(&oom_lock);
403 }
404 
405 static DECLARE_WORK(moom_work, moom_callback);
406 
sysrq_handle_moom(int key)407 static void sysrq_handle_moom(int key)
408 {
409 	schedule_work(&moom_work);
410 }
411 static const struct sysrq_key_op sysrq_moom_op = {
412 	.handler	= sysrq_handle_moom,
413 	.help_msg	= "memory-full-oom-kill(f)",
414 	.action_msg	= "Manual OOM execution",
415 	.enable_mask	= SYSRQ_ENABLE_SIGNAL,
416 };
417 
sysrq_handle_thaw(int key)418 static void sysrq_handle_thaw(int key)
419 {
420 	emergency_thaw_all();
421 }
422 static const struct sysrq_key_op sysrq_thaw_op = {
423 	.handler	= sysrq_handle_thaw,
424 	.help_msg	= "thaw-filesystems(j)",
425 	.action_msg	= "Emergency Thaw of all frozen filesystems",
426 	.enable_mask	= SYSRQ_ENABLE_SIGNAL,
427 };
428 
sysrq_handle_kill(int key)429 static void sysrq_handle_kill(int key)
430 {
431 	send_sig_all(SIGKILL);
432 	console_loglevel = CONSOLE_LOGLEVEL_DEBUG;
433 }
434 static const struct sysrq_key_op sysrq_kill_op = {
435 	.handler	= sysrq_handle_kill,
436 	.help_msg	= "kill-all-tasks(i)",
437 	.action_msg	= "Kill All Tasks",
438 	.enable_mask	= SYSRQ_ENABLE_SIGNAL,
439 };
440 
sysrq_handle_unrt(int key)441 static void sysrq_handle_unrt(int key)
442 {
443 	normalize_rt_tasks();
444 }
445 static const struct sysrq_key_op sysrq_unrt_op = {
446 	.handler	= sysrq_handle_unrt,
447 	.help_msg	= "nice-all-RT-tasks(n)",
448 	.action_msg	= "Nice All RT Tasks",
449 	.enable_mask	= SYSRQ_ENABLE_RTNICE,
450 };
451 
452 /* Key Operations table and lock */
453 static DEFINE_SPINLOCK(sysrq_key_table_lock);
454 
455 static const struct sysrq_key_op *sysrq_key_table[62] = {
456 	&sysrq_loglevel_op,		/* 0 */
457 	&sysrq_loglevel_op,		/* 1 */
458 	&sysrq_loglevel_op,		/* 2 */
459 	&sysrq_loglevel_op,		/* 3 */
460 	&sysrq_loglevel_op,		/* 4 */
461 	&sysrq_loglevel_op,		/* 5 */
462 	&sysrq_loglevel_op,		/* 6 */
463 	&sysrq_loglevel_op,		/* 7 */
464 	&sysrq_loglevel_op,		/* 8 */
465 	&sysrq_loglevel_op,		/* 9 */
466 
467 	/*
468 	 * a: Don't use for system provided sysrqs, it is handled specially on
469 	 * sparc and will never arrive.
470 	 */
471 	NULL,				/* a */
472 	&sysrq_reboot_op,		/* b */
473 	&sysrq_crash_op,		/* c */
474 	&sysrq_showlocks_op,		/* d */
475 	&sysrq_term_op,			/* e */
476 	&sysrq_moom_op,			/* f */
477 	/* g: May be registered for the kernel debugger */
478 	NULL,				/* g */
479 	NULL,				/* h - reserved for help */
480 	&sysrq_kill_op,			/* i */
481 #ifdef CONFIG_BLOCK
482 	&sysrq_thaw_op,			/* j */
483 #else
484 	NULL,				/* j */
485 #endif
486 	&sysrq_SAK_op,			/* k */
487 #ifdef CONFIG_SMP
488 	&sysrq_showallcpus_op,		/* l */
489 #else
490 	NULL,				/* l */
491 #endif
492 	&sysrq_showmem_op,		/* m */
493 	&sysrq_unrt_op,			/* n */
494 	/* o: This will often be registered as 'Off' at init time */
495 	NULL,				/* o */
496 	&sysrq_showregs_op,		/* p */
497 	&sysrq_show_timers_op,		/* q */
498 	&sysrq_unraw_op,		/* r */
499 	&sysrq_sync_op,			/* s */
500 	&sysrq_showstate_op,		/* t */
501 	&sysrq_mountro_op,		/* u */
502 	/* v: May be registered for frame buffer console restore */
503 	NULL,				/* v */
504 	&sysrq_showstate_blocked_op,	/* w */
505 	/* x: May be registered on mips for TLB dump */
506 	/* x: May be registered on ppc/powerpc for xmon */
507 	/* x: May be registered on sparc64 for global PMU dump */
508 	NULL,				/* x */
509 	/* y: May be registered on sparc64 for global register dump */
510 	NULL,				/* y */
511 	&sysrq_ftrace_dump_op,		/* z */
512 	NULL,				/* A */
513 	NULL,				/* B */
514 	NULL,				/* C */
515 	NULL,				/* D */
516 	NULL,				/* E */
517 	NULL,				/* F */
518 	NULL,				/* G */
519 	NULL,				/* H */
520 	NULL,				/* I */
521 	NULL,				/* J */
522 	NULL,				/* K */
523 	NULL,				/* L */
524 	NULL,				/* M */
525 	NULL,				/* N */
526 	NULL,				/* O */
527 	NULL,				/* P */
528 	NULL,				/* Q */
529 	NULL,				/* R */
530 	NULL,				/* S */
531 	NULL,				/* T */
532 	NULL,				/* U */
533 	NULL,				/* V */
534 	NULL,				/* W */
535 	NULL,				/* X */
536 	NULL,				/* Y */
537 	NULL,				/* Z */
538 };
539 
540 /* key2index calculation, -1 on invalid index */
sysrq_key_table_key2index(int key)541 static int sysrq_key_table_key2index(int key)
542 {
543 	int retval;
544 
545 	if ((key >= '0') && (key <= '9'))
546 		retval = key - '0';
547 	else if ((key >= 'a') && (key <= 'z'))
548 		retval = key + 10 - 'a';
549 	else if ((key >= 'A') && (key <= 'Z'))
550 		retval = key + 36 - 'A';
551 	else
552 		retval = -1;
553 	return retval;
554 }
555 
556 /*
557  * get and put functions for the table, exposed to modules.
558  */
__sysrq_get_key_op(int key)559 static const struct sysrq_key_op *__sysrq_get_key_op(int key)
560 {
561 	const struct sysrq_key_op *op_p = NULL;
562 	int i;
563 
564 	i = sysrq_key_table_key2index(key);
565 	if (i != -1)
566 		op_p = sysrq_key_table[i];
567 
568 	return op_p;
569 }
570 
__sysrq_put_key_op(int key,const struct sysrq_key_op * op_p)571 static void __sysrq_put_key_op(int key, const struct sysrq_key_op *op_p)
572 {
573 	int i = sysrq_key_table_key2index(key);
574 
575 	if (i != -1)
576 		sysrq_key_table[i] = op_p;
577 }
578 
__handle_sysrq(int key,bool check_mask)579 void __handle_sysrq(int key, bool check_mask)
580 {
581 	const struct sysrq_key_op *op_p;
582 	int orig_log_level;
583 	int orig_suppress_printk;
584 	int i;
585 
586 	orig_suppress_printk = suppress_printk;
587 	suppress_printk = 0;
588 
589 	rcu_sysrq_start();
590 	rcu_read_lock();
591 	/*
592 	 * Raise the apparent loglevel to maximum so that the sysrq header
593 	 * is shown to provide the user with positive feedback.  We do not
594 	 * simply emit this at KERN_EMERG as that would change message
595 	 * routing in the consumers of /proc/kmsg.
596 	 */
597 	orig_log_level = console_loglevel;
598 	console_loglevel = CONSOLE_LOGLEVEL_DEFAULT;
599 
600 	op_p = __sysrq_get_key_op(key);
601 	if (op_p) {
602 		/*
603 		 * Should we check for enabled operations (/proc/sysrq-trigger
604 		 * should not) and is the invoked operation enabled?
605 		 */
606 		if (!check_mask || sysrq_on_mask(op_p->enable_mask)) {
607 			pr_info("%s\n", op_p->action_msg);
608 			console_loglevel = orig_log_level;
609 			op_p->handler(key);
610 		} else {
611 			pr_info("This sysrq operation is disabled.\n");
612 			console_loglevel = orig_log_level;
613 		}
614 	} else {
615 		pr_info("HELP : ");
616 		/* Only print the help msg once per handler */
617 		for (i = 0; i < ARRAY_SIZE(sysrq_key_table); i++) {
618 			if (sysrq_key_table[i]) {
619 				int j;
620 
621 				for (j = 0; sysrq_key_table[i] !=
622 						sysrq_key_table[j]; j++)
623 					;
624 				if (j != i)
625 					continue;
626 				pr_cont("%s ", sysrq_key_table[i]->help_msg);
627 			}
628 		}
629 		pr_cont("\n");
630 		console_loglevel = orig_log_level;
631 	}
632 	rcu_read_unlock();
633 	rcu_sysrq_end();
634 
635 	suppress_printk = orig_suppress_printk;
636 }
637 
handle_sysrq(int key)638 void handle_sysrq(int key)
639 {
640 	if (sysrq_on())
641 		__handle_sysrq(key, true);
642 }
643 EXPORT_SYMBOL(handle_sysrq);
644 
645 #ifdef CONFIG_INPUT
646 static int sysrq_reset_downtime_ms;
647 
648 /* Simple translation table for the SysRq keys */
649 static const unsigned char sysrq_xlate[KEY_CNT] =
650 	"\000\0331234567890-=\177\t"                    /* 0x00 - 0x0f */
651 	"qwertyuiop[]\r\000as"                          /* 0x10 - 0x1f */
652 	"dfghjkl;'`\000\\zxcv"                          /* 0x20 - 0x2f */
653 	"bnm,./\000*\000 \000\201\202\203\204\205"      /* 0x30 - 0x3f */
654 	"\206\207\210\211\212\000\000789-456+1"         /* 0x40 - 0x4f */
655 	"230\177\000\000\213\214\000\000\000\000\000\000\000\000\000\000" /* 0x50 - 0x5f */
656 	"\r\000/";                                      /* 0x60 - 0x6f */
657 
658 struct sysrq_state {
659 	struct input_handle handle;
660 	struct work_struct reinject_work;
661 	unsigned long key_down[BITS_TO_LONGS(KEY_CNT)];
662 	unsigned int alt;
663 	unsigned int alt_use;
664 	unsigned int shift;
665 	unsigned int shift_use;
666 	bool active;
667 	bool need_reinject;
668 	bool reinjecting;
669 
670 	/* reset sequence handling */
671 	bool reset_canceled;
672 	bool reset_requested;
673 	unsigned long reset_keybit[BITS_TO_LONGS(KEY_CNT)];
674 	int reset_seq_len;
675 	int reset_seq_cnt;
676 	int reset_seq_version;
677 	struct timer_list keyreset_timer;
678 };
679 
680 #define SYSRQ_KEY_RESET_MAX	20 /* Should be plenty */
681 static unsigned short sysrq_reset_seq[SYSRQ_KEY_RESET_MAX];
682 static unsigned int sysrq_reset_seq_len;
683 static unsigned int sysrq_reset_seq_version = 1;
684 
sysrq_parse_reset_sequence(struct sysrq_state * state)685 static void sysrq_parse_reset_sequence(struct sysrq_state *state)
686 {
687 	int i;
688 	unsigned short key;
689 
690 	state->reset_seq_cnt = 0;
691 
692 	for (i = 0; i < sysrq_reset_seq_len; i++) {
693 		key = sysrq_reset_seq[i];
694 
695 		if (key == KEY_RESERVED || key > KEY_MAX)
696 			break;
697 
698 		__set_bit(key, state->reset_keybit);
699 		state->reset_seq_len++;
700 
701 		if (test_bit(key, state->key_down))
702 			state->reset_seq_cnt++;
703 	}
704 
705 	/* Disable reset until old keys are not released */
706 	state->reset_canceled = state->reset_seq_cnt != 0;
707 
708 	state->reset_seq_version = sysrq_reset_seq_version;
709 }
710 
sysrq_do_reset(struct timer_list * t)711 static void sysrq_do_reset(struct timer_list *t)
712 {
713 	struct sysrq_state *state = from_timer(state, t, keyreset_timer);
714 
715 	state->reset_requested = true;
716 
717 	orderly_reboot();
718 }
719 
sysrq_handle_reset_request(struct sysrq_state * state)720 static void sysrq_handle_reset_request(struct sysrq_state *state)
721 {
722 	if (state->reset_requested)
723 		__handle_sysrq(sysrq_xlate[KEY_B], false);
724 
725 	if (sysrq_reset_downtime_ms)
726 		mod_timer(&state->keyreset_timer,
727 			jiffies + msecs_to_jiffies(sysrq_reset_downtime_ms));
728 	else
729 		sysrq_do_reset(&state->keyreset_timer);
730 }
731 
sysrq_detect_reset_sequence(struct sysrq_state * state,unsigned int code,int value)732 static void sysrq_detect_reset_sequence(struct sysrq_state *state,
733 					unsigned int code, int value)
734 {
735 	if (!test_bit(code, state->reset_keybit)) {
736 		/*
737 		 * Pressing any key _not_ in reset sequence cancels
738 		 * the reset sequence.  Also cancelling the timer in
739 		 * case additional keys were pressed after a reset
740 		 * has been requested.
741 		 */
742 		if (value && state->reset_seq_cnt) {
743 			state->reset_canceled = true;
744 			del_timer(&state->keyreset_timer);
745 		}
746 	} else if (value == 0) {
747 		/*
748 		 * Key release - all keys in the reset sequence need
749 		 * to be pressed and held for the reset timeout
750 		 * to hold.
751 		 */
752 		del_timer(&state->keyreset_timer);
753 
754 		if (--state->reset_seq_cnt == 0)
755 			state->reset_canceled = false;
756 	} else if (value == 1) {
757 		/* key press, not autorepeat */
758 		if (++state->reset_seq_cnt == state->reset_seq_len &&
759 		    !state->reset_canceled) {
760 			sysrq_handle_reset_request(state);
761 		}
762 	}
763 }
764 
765 #ifdef CONFIG_OF
sysrq_of_get_keyreset_config(void)766 static void sysrq_of_get_keyreset_config(void)
767 {
768 	u32 key;
769 	struct device_node *np;
770 	struct property *prop;
771 	const __be32 *p;
772 
773 	np = of_find_node_by_path("/chosen/linux,sysrq-reset-seq");
774 	if (!np) {
775 		pr_debug("No sysrq node found");
776 		return;
777 	}
778 
779 	/* Reset in case a __weak definition was present */
780 	sysrq_reset_seq_len = 0;
781 
782 	of_property_for_each_u32(np, "keyset", prop, p, key) {
783 		if (key == KEY_RESERVED || key > KEY_MAX ||
784 		    sysrq_reset_seq_len == SYSRQ_KEY_RESET_MAX)
785 			break;
786 
787 		sysrq_reset_seq[sysrq_reset_seq_len++] = (unsigned short)key;
788 	}
789 
790 	/* Get reset timeout if any. */
791 	of_property_read_u32(np, "timeout-ms", &sysrq_reset_downtime_ms);
792 
793 	of_node_put(np);
794 }
795 #else
sysrq_of_get_keyreset_config(void)796 static void sysrq_of_get_keyreset_config(void)
797 {
798 }
799 #endif
800 
sysrq_reinject_alt_sysrq(struct work_struct * work)801 static void sysrq_reinject_alt_sysrq(struct work_struct *work)
802 {
803 	struct sysrq_state *sysrq =
804 			container_of(work, struct sysrq_state, reinject_work);
805 	struct input_handle *handle = &sysrq->handle;
806 	unsigned int alt_code = sysrq->alt_use;
807 
808 	if (sysrq->need_reinject) {
809 		/* we do not want the assignment to be reordered */
810 		sysrq->reinjecting = true;
811 		mb();
812 
813 		/* Simulate press and release of Alt + SysRq */
814 		input_inject_event(handle, EV_KEY, alt_code, 1);
815 		input_inject_event(handle, EV_KEY, KEY_SYSRQ, 1);
816 		input_inject_event(handle, EV_SYN, SYN_REPORT, 1);
817 
818 		input_inject_event(handle, EV_KEY, KEY_SYSRQ, 0);
819 		input_inject_event(handle, EV_KEY, alt_code, 0);
820 		input_inject_event(handle, EV_SYN, SYN_REPORT, 1);
821 
822 		mb();
823 		sysrq->reinjecting = false;
824 	}
825 }
826 
sysrq_handle_keypress(struct sysrq_state * sysrq,unsigned int code,int value)827 static bool sysrq_handle_keypress(struct sysrq_state *sysrq,
828 				  unsigned int code, int value)
829 {
830 	bool was_active = sysrq->active;
831 	bool suppress;
832 
833 	switch (code) {
834 
835 	case KEY_LEFTALT:
836 	case KEY_RIGHTALT:
837 		if (!value) {
838 			/* One of ALTs is being released */
839 			if (sysrq->active && code == sysrq->alt_use)
840 				sysrq->active = false;
841 
842 			sysrq->alt = KEY_RESERVED;
843 
844 		} else if (value != 2) {
845 			sysrq->alt = code;
846 			sysrq->need_reinject = false;
847 		}
848 		break;
849 
850 	case KEY_LEFTSHIFT:
851 	case KEY_RIGHTSHIFT:
852 		if (!value)
853 			sysrq->shift = KEY_RESERVED;
854 		else if (value != 2)
855 			sysrq->shift = code;
856 		break;
857 
858 	case KEY_SYSRQ:
859 		if (value == 1 && sysrq->alt != KEY_RESERVED) {
860 			sysrq->active = true;
861 			sysrq->alt_use = sysrq->alt;
862 			/* either RESERVED (for released) or actual code */
863 			sysrq->shift_use = sysrq->shift;
864 			/*
865 			 * If nothing else will be pressed we'll need
866 			 * to re-inject Alt-SysRq keysroke.
867 			 */
868 			sysrq->need_reinject = true;
869 		}
870 
871 		/*
872 		 * Pretend that sysrq was never pressed at all. This
873 		 * is needed to properly handle KGDB which will try
874 		 * to release all keys after exiting debugger. If we
875 		 * do not clear key bit it KGDB will end up sending
876 		 * release events for Alt and SysRq, potentially
877 		 * triggering print screen function.
878 		 */
879 		if (sysrq->active)
880 			clear_bit(KEY_SYSRQ, sysrq->handle.dev->key);
881 
882 		break;
883 
884 	default:
885 		if (sysrq->active && value && value != 2) {
886 			unsigned char c = sysrq_xlate[code];
887 
888 			sysrq->need_reinject = false;
889 			if (sysrq->shift_use != KEY_RESERVED)
890 				c = toupper(c);
891 			__handle_sysrq(c, true);
892 		}
893 		break;
894 	}
895 
896 	suppress = sysrq->active;
897 
898 	if (!sysrq->active) {
899 
900 		/*
901 		 * See if reset sequence has changed since the last time.
902 		 */
903 		if (sysrq->reset_seq_version != sysrq_reset_seq_version)
904 			sysrq_parse_reset_sequence(sysrq);
905 
906 		/*
907 		 * If we are not suppressing key presses keep track of
908 		 * keyboard state so we can release keys that have been
909 		 * pressed before entering SysRq mode.
910 		 */
911 		if (value)
912 			set_bit(code, sysrq->key_down);
913 		else
914 			clear_bit(code, sysrq->key_down);
915 
916 		if (was_active)
917 			schedule_work(&sysrq->reinject_work);
918 
919 		/* Check for reset sequence */
920 		sysrq_detect_reset_sequence(sysrq, code, value);
921 
922 	} else if (value == 0 && test_and_clear_bit(code, sysrq->key_down)) {
923 		/*
924 		 * Pass on release events for keys that was pressed before
925 		 * entering SysRq mode.
926 		 */
927 		suppress = false;
928 	}
929 
930 	return suppress;
931 }
932 
sysrq_filter(struct input_handle * handle,unsigned int type,unsigned int code,int value)933 static bool sysrq_filter(struct input_handle *handle,
934 			 unsigned int type, unsigned int code, int value)
935 {
936 	struct sysrq_state *sysrq = handle->private;
937 	bool suppress;
938 
939 	/*
940 	 * Do not filter anything if we are in the process of re-injecting
941 	 * Alt+SysRq combination.
942 	 */
943 	if (sysrq->reinjecting)
944 		return false;
945 
946 	switch (type) {
947 
948 	case EV_SYN:
949 		suppress = false;
950 		break;
951 
952 	case EV_KEY:
953 		suppress = sysrq_handle_keypress(sysrq, code, value);
954 		break;
955 
956 	default:
957 		suppress = sysrq->active;
958 		break;
959 	}
960 
961 	return suppress;
962 }
963 
sysrq_connect(struct input_handler * handler,struct input_dev * dev,const struct input_device_id * id)964 static int sysrq_connect(struct input_handler *handler,
965 			 struct input_dev *dev,
966 			 const struct input_device_id *id)
967 {
968 	struct sysrq_state *sysrq;
969 	int error;
970 
971 	sysrq = kzalloc(sizeof(struct sysrq_state), GFP_KERNEL);
972 	if (!sysrq)
973 		return -ENOMEM;
974 
975 	INIT_WORK(&sysrq->reinject_work, sysrq_reinject_alt_sysrq);
976 
977 	sysrq->handle.dev = dev;
978 	sysrq->handle.handler = handler;
979 	sysrq->handle.name = "sysrq";
980 	sysrq->handle.private = sysrq;
981 	timer_setup(&sysrq->keyreset_timer, sysrq_do_reset, 0);
982 
983 	error = input_register_handle(&sysrq->handle);
984 	if (error) {
985 		pr_err("Failed to register input sysrq handler, error %d\n",
986 			error);
987 		goto err_free;
988 	}
989 
990 	error = input_open_device(&sysrq->handle);
991 	if (error) {
992 		pr_err("Failed to open input device, error %d\n", error);
993 		goto err_unregister;
994 	}
995 
996 	return 0;
997 
998  err_unregister:
999 	input_unregister_handle(&sysrq->handle);
1000  err_free:
1001 	kfree(sysrq);
1002 	return error;
1003 }
1004 
sysrq_disconnect(struct input_handle * handle)1005 static void sysrq_disconnect(struct input_handle *handle)
1006 {
1007 	struct sysrq_state *sysrq = handle->private;
1008 
1009 	input_close_device(handle);
1010 	cancel_work_sync(&sysrq->reinject_work);
1011 	del_timer_sync(&sysrq->keyreset_timer);
1012 	input_unregister_handle(handle);
1013 	kfree(sysrq);
1014 }
1015 
1016 /*
1017  * We are matching on KEY_LEFTALT instead of KEY_SYSRQ because not all
1018  * keyboards have SysRq key predefined and so user may add it to keymap
1019  * later, but we expect all such keyboards to have left alt.
1020  */
1021 static const struct input_device_id sysrq_ids[] = {
1022 	{
1023 		.flags = INPUT_DEVICE_ID_MATCH_EVBIT |
1024 				INPUT_DEVICE_ID_MATCH_KEYBIT,
1025 		.evbit = { [BIT_WORD(EV_KEY)] = BIT_MASK(EV_KEY) },
1026 		.keybit = { [BIT_WORD(KEY_LEFTALT)] = BIT_MASK(KEY_LEFTALT) },
1027 	},
1028 	{ },
1029 };
1030 
1031 static struct input_handler sysrq_handler = {
1032 	.filter		= sysrq_filter,
1033 	.connect	= sysrq_connect,
1034 	.disconnect	= sysrq_disconnect,
1035 	.name		= "sysrq",
1036 	.id_table	= sysrq_ids,
1037 };
1038 
sysrq_register_handler(void)1039 static inline void sysrq_register_handler(void)
1040 {
1041 	int error;
1042 
1043 	sysrq_of_get_keyreset_config();
1044 
1045 	error = input_register_handler(&sysrq_handler);
1046 	if (error)
1047 		pr_err("Failed to register input handler, error %d", error);
1048 }
1049 
sysrq_unregister_handler(void)1050 static inline void sysrq_unregister_handler(void)
1051 {
1052 	input_unregister_handler(&sysrq_handler);
1053 }
1054 
sysrq_reset_seq_param_set(const char * buffer,const struct kernel_param * kp)1055 static int sysrq_reset_seq_param_set(const char *buffer,
1056 				     const struct kernel_param *kp)
1057 {
1058 	unsigned long val;
1059 	int error;
1060 
1061 	error = kstrtoul(buffer, 0, &val);
1062 	if (error < 0)
1063 		return error;
1064 
1065 	if (val > KEY_MAX)
1066 		return -EINVAL;
1067 
1068 	*((unsigned short *)kp->arg) = val;
1069 	sysrq_reset_seq_version++;
1070 
1071 	return 0;
1072 }
1073 
1074 static const struct kernel_param_ops param_ops_sysrq_reset_seq = {
1075 	.get	= param_get_ushort,
1076 	.set	= sysrq_reset_seq_param_set,
1077 };
1078 
1079 #define param_check_sysrq_reset_seq(name, p)	\
1080 	__param_check(name, p, unsigned short)
1081 
1082 /*
1083  * not really modular, but the easiest way to keep compat with existing
1084  * bootargs behaviour is to continue using module_param here.
1085  */
1086 module_param_array_named(reset_seq, sysrq_reset_seq, sysrq_reset_seq,
1087 			 &sysrq_reset_seq_len, 0644);
1088 
1089 module_param_named(sysrq_downtime_ms, sysrq_reset_downtime_ms, int, 0644);
1090 
1091 #else
1092 
sysrq_register_handler(void)1093 static inline void sysrq_register_handler(void)
1094 {
1095 }
1096 
sysrq_unregister_handler(void)1097 static inline void sysrq_unregister_handler(void)
1098 {
1099 }
1100 
1101 #endif /* CONFIG_INPUT */
1102 
sysrq_toggle_support(int enable_mask)1103 int sysrq_toggle_support(int enable_mask)
1104 {
1105 	bool was_enabled = sysrq_on();
1106 
1107 	sysrq_enabled = enable_mask;
1108 
1109 	if (was_enabled != sysrq_on()) {
1110 		if (sysrq_on())
1111 			sysrq_register_handler();
1112 		else
1113 			sysrq_unregister_handler();
1114 	}
1115 
1116 	return 0;
1117 }
1118 EXPORT_SYMBOL_GPL(sysrq_toggle_support);
1119 
__sysrq_swap_key_ops(int key,const struct sysrq_key_op * insert_op_p,const struct sysrq_key_op * remove_op_p)1120 static int __sysrq_swap_key_ops(int key, const struct sysrq_key_op *insert_op_p,
1121 				const struct sysrq_key_op *remove_op_p)
1122 {
1123 	int retval;
1124 
1125 	spin_lock(&sysrq_key_table_lock);
1126 	if (__sysrq_get_key_op(key) == remove_op_p) {
1127 		__sysrq_put_key_op(key, insert_op_p);
1128 		retval = 0;
1129 	} else {
1130 		retval = -1;
1131 	}
1132 	spin_unlock(&sysrq_key_table_lock);
1133 
1134 	/*
1135 	 * A concurrent __handle_sysrq either got the old op or the new op.
1136 	 * Wait for it to go away before returning, so the code for an old
1137 	 * op is not freed (eg. on module unload) while it is in use.
1138 	 */
1139 	synchronize_rcu();
1140 
1141 	return retval;
1142 }
1143 
register_sysrq_key(int key,const struct sysrq_key_op * op_p)1144 int register_sysrq_key(int key, const struct sysrq_key_op *op_p)
1145 {
1146 	return __sysrq_swap_key_ops(key, op_p, NULL);
1147 }
1148 EXPORT_SYMBOL(register_sysrq_key);
1149 
unregister_sysrq_key(int key,const struct sysrq_key_op * op_p)1150 int unregister_sysrq_key(int key, const struct sysrq_key_op *op_p)
1151 {
1152 	return __sysrq_swap_key_ops(key, NULL, op_p);
1153 }
1154 EXPORT_SYMBOL(unregister_sysrq_key);
1155 
1156 #ifdef CONFIG_PROC_FS
1157 /*
1158  * writing 'C' to /proc/sysrq-trigger is like sysrq-C
1159  */
write_sysrq_trigger(struct file * file,const char __user * buf,size_t count,loff_t * ppos)1160 static ssize_t write_sysrq_trigger(struct file *file, const char __user *buf,
1161 				   size_t count, loff_t *ppos)
1162 {
1163 	if (count) {
1164 		char c;
1165 
1166 		if (get_user(c, buf))
1167 			return -EFAULT;
1168 		__handle_sysrq(c, false);
1169 	}
1170 
1171 	return count;
1172 }
1173 
1174 static const struct proc_ops sysrq_trigger_proc_ops = {
1175 	.proc_write	= write_sysrq_trigger,
1176 	.proc_lseek	= noop_llseek,
1177 };
1178 
sysrq_init_procfs(void)1179 static void sysrq_init_procfs(void)
1180 {
1181 	if (!proc_create("sysrq-trigger", S_IWUSR, NULL,
1182 			 &sysrq_trigger_proc_ops))
1183 		pr_err("Failed to register proc interface\n");
1184 }
1185 
1186 #else
1187 
sysrq_init_procfs(void)1188 static inline void sysrq_init_procfs(void)
1189 {
1190 }
1191 
1192 #endif /* CONFIG_PROC_FS */
1193 
sysrq_init(void)1194 static int __init sysrq_init(void)
1195 {
1196 	sysrq_init_procfs();
1197 
1198 	if (sysrq_on())
1199 		sysrq_register_handler();
1200 
1201 	return 0;
1202 }
1203 device_initcall(sysrq_init);
1204