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