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