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